Files
o2o-weather/mobile/src/components/my-gak/my-gak.tsx
T

363 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, useState, type ReactNode } from 'react';
import { Pressable, ScrollView, TextInput, View } from 'react-native';
import { Body, useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Ic, Rail, Sec } from '@/components/ui';
import { gakName, MY_GAK_ICON, shareUrl, SLOT_WORD, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from '@/lib/my-gak';
import { useRegion } from '@/lib/region';
import { useShare } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
const v = s?.score;
return <Text className={`ml-auto font-bagel ${big ? 'text-[36px] leading-[38px]' : 'text-[28px] leading-[30px]'} ${v == null || v < 50 ? 'text-ink3' : 'text-orange'}`}>{v ?? '–'}</Text>;
}
function Reasons({ s }: { s?: MyGakScore }) {
if (!s?.slot) return <Text className="text-[12.5px] font-semibold text-ink3">예보를 불러오는 중이에요</Text>;
return (
<Text className="text-[12.5px] leading-snug font-semibold text-ink2">
<Text className="font-extrabold text-ink">{SLOT_WORD[s.slot as Slot]} </Text>
{s.reasons?.join(' · ')}
</Text>
);
}
// 조건 이름. 점수 응답의 factors 와 reasons 는 같은 순서다
const AXIS_NAME: Record<string, string> = { temp: '기온', rain: '비', wind: '바람', air: '미세먼지', humidity: '습도' };
// 조건 점수가 이보다 낮으면 '아쉬운 조건'으로 카드에 칩을 단다
const SHORT = 70;
/** 조건마다 이름·점수·실제 값 (실제 값은 근거 문구의 첫 마디: 체감 15°) */
function conditions(s?: MyGakScore) {
const notes = s?.reasons ?? [];
return Object.entries(s?.factors ?? {}).map(([axis, value], i) => ({ axis, label: AXIS_NAME[axis] ?? axis, value, note: notes[i] ?? '', short: (notes[i] ?? '').split(', ')[0] }));
}
/** 오늘 탭의 내 각 줄: 카드엔 아이콘·이름·점수·아쉬운 조건만, 누르면 상세 창 */
export function MyGakRow() {
const { open } = useSheet();
const { items } = useMyGak();
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? [];
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail>
{items.map((g, i) => {
const s = scores[i];
const miss = conditions(s)
.filter((c) => c.value < SHORT)
.slice(0, 2);
return (
<Pressable key={g.id ?? 'local'} onPress={() => open({ type: 'myGak', gak: g })} accessibilityLabel={`${g.name} ${s?.score ?? ''}점 자세히`} className="w-[200px] gap-2 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
<View className="flex-row items-start justify-between">
<Ic name={g.icon ?? MY_GAK_ICON} size={40} />
<Score s={s} big />
</View>
<View>
<Text className="font-jua text-[17px] leading-tight text-ink">{g.name}</Text>
<Text className="text-xs font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'}</Text>
</View>
{!!s?.slot && (
<View className="flex-row flex-wrap gap-1">
{miss.length ? (
miss.map((c) => (
<Text key={c.axis} className="overflow-hidden rounded-full bg-[#ffe8dc] px-2 py-0.5 text-[11.5px] font-extrabold text-[#c2471b]">
{c.short}
</Text>
))
) : (
<Text className="overflow-hidden rounded-full bg-[#dff5ea] px-2 py-0.5 text-[11.5px] font-extrabold text-[#1f7a4f]">조건 다 맞아요</Text>
)}
</View>
)}
</Pressable>
);
})}
<Pressable onPress={() => open({ type: 'mix' })} accessibilityRole="button" className="w-[120px] items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-line p-3">
<Text className="font-jua text-[26px] leading-[28px] text-ink2">+</Text>
<Text className="font-jua text-[15px] text-ink2">내 각 만들기</Text>
</Pressable>
</Rail>
</>
);
}
/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기·지우기 */
export function MyGakSheet({ gak, onDone }: { gak: MyGak; onDone: () => void }) {
const { remove } = useMyGak();
const s = useMyGakScores([gak.rule]).data?.scores?.[0];
const soft = useSoft();
const shareView = useShare();
const shot = useRef<View>(null);
const [confirm, setConfirm] = useState(false);
const rows = conditions(s);
// 받은 사람이 자기 동네 점수로 볼 수 있게 링크를 같이 보낸다
const share = () => void shareView(shot, { title: gak.name, message: `${gak.name} ${s?.score ?? ''}점 · 내 동네 점수 보기 ${shareUrl(gak)}` });
return (
<Body>
<View ref={shot} collapsable={false} className="bg-card">
<View className="flex-row items-center gap-3">
<Ic name={gak.icon ?? MY_GAK_ICON} size={56} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[22px] leading-tight text-ink">{gak.name}</Text>
<Text className="text-[12.5px] font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'}</Text>
</View>
<Score s={s} big />
</View>
<View className="mt-3 flex-row gap-1.5" accessibilityLabel="시간대별 점수">
{SLOTS.map(([k, word]) => {
const v = s?.slots?.[k];
return (
<View key={k} className="flex-1 items-center rounded-2xl px-1 py-2" style={{ backgroundColor: s?.slot === k ? soft.warm : soft.soft }}>
<Text className="text-xs font-extrabold text-ink2">{word}</Text>
<Text className={`font-bagel text-xl ${v != null ? 'text-orange' : 'text-ink3'}`}>{v ?? '–'}</Text>
</View>
);
})}
</View>
<View className="mt-3.5 gap-2.5">
{rows.map((c) => (
<View key={c.axis}>
<View className="flex-row items-center gap-2.5">
<Text className="w-16 text-[13.5px] font-bold text-ink">{c.label}</Text>
<View className="h-[9px] flex-1 overflow-hidden rounded-full" style={{ backgroundColor: soft.bar }}>
<LinearGradient colors={['#ffc86e', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${c.value}%` }} />
</View>
<Text className="w-8 text-right text-xs font-bold text-ink2">{c.value}</Text>
</View>
<Text className="ml-[74px] text-[12.5px] font-semibold text-ink2">{c.note}</Text>
</View>
))}
</View>
</View>
<View className="mt-4 flex-row gap-2">
<Pressable onPress={share} className="flex-1 rounded-2xl bg-orange py-3">
<Text className="text-center font-jua text-[16px] text-white">공유하기</Text>
</Pressable>
{confirm ? (
<>
<Pressable
onPress={() => {
remove(gak);
onDone();
}}
className="rounded-2xl bg-[#fdecec] px-4 py-3"
>
<Text className="font-jua text-[16px] text-heart">지우기</Text>
</Pressable>
<Pressable onPress={() => setConfirm(false)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
<Text className="font-jua text-[16px] text-[#5a6380]">취소</Text>
</Pressable>
</>
) : (
<Pressable onPress={() => setConfirm(true)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
<Text className="font-jua text-[16px] text-[#5a6380]">지우기</Text>
</Pressable>
)}
</View>
{confirm && <Text className="mt-1.5 text-right text-[12.5px] font-bold text-ink2">지울까요?</Text>}
</Body>
);
}
function Row({ label, on, onToggle, disabled, children }: { label: string; on: boolean; onToggle: () => void; disabled?: boolean; children: ReactNode }) {
return (
<View className={`min-h-[44px] flex-row flex-wrap items-center gap-2 border-b border-line py-2 ${on ? '' : 'opacity-60'}`}>
<Pressable onPress={onToggle} disabled={disabled} accessibilityRole="checkbox" accessibilityState={{ checked: on }} className="w-[84px] flex-row items-center gap-1.5">
<View className={`size-4 items-center justify-center rounded-[4px] border-2 ${on ? 'border-orange bg-orange' : 'border-ink3'}`}>{on && <Text className="text-[10px] leading-3 font-extrabold text-white">✓</Text>}</View>
<Text className="text-[14px] font-extrabold text-ink">{label}</Text>
</Pressable>
{on ? <View className="min-w-0 flex-1 flex-row flex-wrap items-center gap-1.5">{children}</View> : <Text className="text-[13px] font-semibold text-ink3">상관없음</Text>}
</View>
);
}
/** 숫자: 휴대폰 숫자 자판엔 '-'가 없을 때가 있어 −/+ 버튼으로 바꾼다 */
function Num({ value, onChange, min, max, step = 1, label, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; step?: number; label: string; disabled?: boolean }) {
const soft = useSoft();
const set = (v: number) => onChange(Math.min(max, Math.max(min, v)));
return (
<View className="flex-row items-center overflow-hidden rounded-xl" style={{ backgroundColor: soft.soft }} accessibilityLabel={label}>
<Pressable onPress={() => set(value - step)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-2 py-1.5 disabled:opacity-30">
<Text className="text-[15px] font-extrabold text-ink2">−</Text>
</Pressable>
<Text className="min-w-[28px] text-center text-[13.5px] font-bold text-ink">{value}</Text>
<Pressable onPress={() => set(value + step)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-2 py-1.5 disabled:opacity-30">
<Text className="text-[15px] font-extrabold text-ink2">+</Text>
</Pressable>
</View>
);
}
function Choice<T extends string>({ value, options, onChange, label, disabled }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string; disabled?: boolean }) {
return (
<View className="flex-row gap-1" accessibilityRole="radiogroup" accessibilityLabel={label}>
{options.map(([k, word]) => (
<Pressable key={k} onPress={() => onChange(k)} disabled={disabled} accessibilityRole="radio" accessibilityState={{ checked: value === k }} className={`rounded-full px-3 py-1.5 ${value === k ? 'bg-orange' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[13.5px] font-bold ${value === k ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
</Pressable>
))}
</View>
);
}
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> };
const DEFAULT_RULE: Filled<MyGakRule> = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] };
type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity';
const condsOf = (r: MyGakRule): Record<Cond, boolean> => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity });
/** 내 각 아이콘 고르기: 있는 각 아이콘 그대로 */
function IconPicker({ value, onPick }: { value: string; onPick: (icon: string) => void }) {
const soft = useSoft();
const icons = [...new Set([MY_GAK_ICON, ...(usePresets().data ?? []).map((p) => p.icon)])];
return (
<View className="mt-3">
<Text className="font-jua text-[19px] text-ink">아이콘</Text>
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-1.5 px-4 pt-2 pb-1">
{icons.map((icon) => (
<Pressable key={icon} onPress={() => onPick(icon)} accessibilityRole="button" accessibilityState={{ selected: value === icon }} accessibilityLabel={`아이콘 ${icon}`} className={`size-12 items-center justify-center rounded-2xl ${value === icon ? 'bg-orange' : ''}`} style={value === icon ? undefined : { backgroundColor: soft.soft }}>
<Ic name={icon} size={32} />
</Pressable>
))}
</ScrollView>
</View>
);
}
/** 있는 각을 골라 그 각 조건으로 채운다 */
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const soft = useSoft();
const items = usePresets().data ?? [];
if (!items.length) return null;
return (
<View className="mb-3">
<Text className="font-jua text-[19px] text-ink">있는 각에서 불러오기</Text>
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-2.5 px-4 pt-2 pb-1">
{items.map((p) => (
<Pressable key={p.code} onPress={() => onPick(p)} accessibilityRole="button" accessibilityState={{ selected: picked === p.code }} className={`w-[68px] items-center gap-1 rounded-2xl px-1 py-2 ${picked === p.code ? 'bg-orange' : ''}`} style={picked === p.code ? undefined : { backgroundColor: soft.soft }}>
<Ic name={p.icon} size={36} />
<Text numberOfLines={1} className={`text-[12px] leading-tight font-extrabold ${picked === p.code ? 'text-white' : 'text-ink2'}`}>
{p.name}
</Text>
</Pressable>
))}
</ScrollView>
</View>
);
}
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
const { region } = useRegion();
const soft = useSoft();
const { create, pending, failed } = useMyGak();
const [name, setName] = useState(shared?.name ?? '');
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE);
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false });
const [picked, setPicked] = useState<string | null>(null);
const [icon, setIcon] = useState(shared?.icon ?? MY_GAK_ICON);
const lock = !!shared;
const pick = (p: MyGakPreset) => {
setPicked(p.code);
setName(p.name);
setIcon(p.icon);
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE);
setOn(condsOf(p.rule));
};
const set = <K extends keyof typeof vals>(k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }));
const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }));
const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial<MyGakRule>) };
const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1]);
const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0];
const title = gakName(name) || '이름 없는 각';
const toggleSlot = (s: Slot) =>
set(
'slots',
vals.slots.includes(s)
? vals.slots.filter((x) => x !== s)
: SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)),
);
return (
<Body>
{shared ? (
<Text className="text-[13px] font-bold text-ink2">친구가 보낸 각이에요. {region.name} 기준 점수예요</Text>
) : (
<>
<PresetPicker picked={picked} onPick={pick} />
<Text className="font-jua text-[19px] text-ink">이름</Text>
<TextInput value={name} onChangeText={setName} maxLength={11} placeholder="소맥, 야독, 새우깡" placeholderTextColor={soft.placeholder} accessibilityLabel="이름" className="mt-1.5 rounded-2xl px-3.5 py-2.5 text-[15px] text-ink" style={{ backgroundColor: soft.soft }} />
<IconPicker value={icon} onPick={setIcon} />
</>
)}
<Text className="mt-3 font-jua text-[19px] text-ink">조건</Text>
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')} disabled={lock}>
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [v, vals.temp[1]])} />
<Text className="text-[13.5px] font-bold text-ink">~</Text>
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [vals.temp[0], v])} />
<Text className="text-[13.5px] font-bold text-ink">° 체감</Text>
</Row>
<Row label="비" on={on.rain} onToggle={() => toggle('rain')} disabled={lock}>
<Choice
label="비"
value={vals.rain}
disabled={lock}
onChange={(v) => set('rain', v)}
options={[
['dry', '안 와야'],
['wet', '와야'],
]}
/>
</Row>
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')} disabled={lock}>
<Text className="text-[13.5px] font-bold text-ink">초속</Text>
<Num label="바람 상한" value={vals.wind_max} min={1} max={20} disabled={lock} onChange={(v) => set('wind_max', v)} />
<Text className="text-[13.5px] font-bold text-ink">m 이하</Text>
</Row>
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')} disabled={lock}>
<Choice
label="미세먼지"
value={vals.air}
disabled={lock}
onChange={(v) => set('air', v)}
options={[
['good', '좋음만'],
['normal', '보통까지'],
]}
/>
</Row>
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')} disabled={lock}>
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />
<Text className="text-[13.5px] font-bold text-ink">~</Text>
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [vals.humidity[0], v])} />
<Text className="text-[13.5px] font-bold text-ink">%</Text>
</Row>
<View className="flex-row flex-wrap items-center gap-1.5 py-2.5">
<Text className="w-[84px] text-[14px] font-extrabold text-ink">시간대</Text>
{SLOTS.map(([k, word]) => (
<Pressable key={k} onPress={() => toggleSlot(k)} disabled={lock} accessibilityRole="button" accessibilityState={{ selected: vals.slots.includes(k) }} className={`rounded-full px-3 py-1.5 ${vals.slots.includes(k) ? 'bg-orange' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[13.5px] font-bold ${vals.slots.includes(k) ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
</Pressable>
))}
</View>
<View className="mt-2 gap-1.5 rounded-[20px] p-3.5" style={{ backgroundColor: soft.soft }}>
<View className="flex-row items-center gap-2">
<Ic name={icon} size={32} />
<Text className="font-jua text-[20px] text-ink">{title}</Text>
<Score s={valid ? score : undefined} big />
</View>
{valid ? <Reasons s={score} /> : <Text className="text-[12.5px] font-semibold text-ink3">조건과 시간대를 하나 이상 골라요</Text>}
</View>
{failed && <Text className="mt-2 text-xs font-bold text-heart">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</Text>}
<Pressable disabled={!valid || !gakName(name) || pending} onPress={() => create({ name, icon, rule }, onDone)} className="mt-3.5 rounded-2xl bg-orange py-3 disabled:opacity-45">
<Text className="text-center font-jua text-[17px] text-white">{shared ? '내 각으로 가져오기' : '내 각으로 저장'}</Text>
</Pressable>
</Body>
);
}