Files
o2o-weather/frontend/src/b/myGak.tsx
T

236 lines
12 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 { useState, type ReactNode } from 'react'
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Rail, Sec } from './ui'
const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
const v = s?.score
return (
<em className={cx('ml-auto font-bagel leading-none not-italic', big ? 'text-[36px]' : 'text-[28px]', v == null || v < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>
{v ?? '–'}
</em>
)
}
function Reasons({ s }: { s?: MyGakScore }) {
if (!s?.slot) return <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">예보를 불러오는 중이에요</p>
return (
<p className="m-0 text-[12.5px] leading-snug font-semibold text-(--ink2)">
<b className="mr-1 text-(--ink)">{SLOT_WORD[s.slot as Slot]}</b>
{s.reasons?.join(' · ')}
</p>
)
}
/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */
export function MyGakRow() {
const { open } = useSheet()
const { items, remove } = useMyGak()
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []
const [copied, setCopied] = useState<number | null>(null)
const send = (g: MyGak, i: number) => {
const url = shareUrl(g)
if (navigator.share) {
navigator.share({ title: `${g.name} · 날씨각`, url }).catch((e: unknown) => {
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
})
return
}
navigator.clipboard.writeText(url).then(
() => setCopied(i),
(e: unknown) => console.error('[myGak] copy', e),
)
}
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail label="내 각">
{items.map((g, i) => (
<div key={g.id ?? 'local'} className="flex w-[220px] flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="flex items-center gap-1">
<b className="font-jua text-[17px] leading-tight font-normal">{g.name}</b>
<Score s={scores[i]} />
</div>
<Reasons s={scores[i]} />
<div className="mt-auto flex gap-1.5 pt-0.5">
<button type="button" onClick={() => send(g, i)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
{copied === i ? '링크 복사함' : '친구에게 보내기'}
</button>
<button type="button" onClick={() => remove(g)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)">
지우기
</button>
</div>
</div>
))}
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] cursor-pointer flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
<span className="text-[26px] leading-none">+</span>
내 각 만들기
</button>
</Rail>
</>
)
}
function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) {
return (
<div className={cx('flex min-h-[44px] flex-wrap items-center gap-2 border-b border-(--line) py-2', !on && 'opacity-60')}>
<label className="flex w-[84px] cursor-pointer items-center gap-1.5 text-[14px] font-extrabold">
<input type="checkbox" checked={on} onChange={onToggle} className="size-4 accent-(--orange)" />
{label}
</label>
{on ? <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 text-[13.5px] font-bold">{children}</div> : <span className="text-[13px] font-semibold text-(--ink3)">상관없음</span>}
</div>
)
}
function Num({ value, onChange, min, max, label }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string }) {
return (
<input
type="number"
inputMode="numeric"
aria-label={label}
value={value}
min={min}
max={max}
onChange={(e) => {
const v = Number(e.target.value)
if (e.target.value !== '' && Number.isFinite(v)) onChange(Math.min(max, Math.max(min, v)))
}}
className="w-[58px] rounded-xl bg-[#f3f6fb] px-2 py-1.5 text-center tabular-nums"
/>
)
}
function Choice<T extends string>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<span className="flex gap-1" role="radiogroup" aria-label={label}>
{options.map(([k, word]) => (
<button key={k} type="button" role="radio" aria-checked={value === k} onClick={() => onChange(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', value === k ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</span>
)
}
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 PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const items = usePresets().data ?? []
if (!items.length) return null
return (
<div className="mb-3">
<span className="font-jua text-[19px]">있는 각에서 불러오기</span>
<div className="-mx-4">
<Rail label="있는 각에서 불러오기">
{items.map((p) => (
<button
key={p.code}
type="button"
aria-pressed={picked === p.code}
onClick={() => onPick(p)}
className={cx('flex w-[68px] cursor-pointer flex-col items-center gap-1 rounded-2xl px-1 py-2 text-[12px] leading-tight font-extrabold', picked === p.code ? 'bg-(--orange) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
>
<Ic name={p.icon} className="size-9" />
<span className="w-full truncate">{p.name}</span>
</button>
))}
</Rail>
</div>
</div>
)
}
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
const { region } = useRegion()
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 pick = (p: MyGakPreset) => {
setPicked(p.code)
setName(p.name)
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 (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
{shared ? (
<p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>
) : (
<>
<PresetPicker picked={picked} onPick={pick} />
<label className="block">
<span className="font-jua text-[19px]">이름</span>
<input value={name} onChange={(e) => setName(e.target.value)} maxLength={11} placeholder="소맥, 야독, 새우깡" className="mt-1.5 w-full rounded-2xl bg-[#f3f6fb] px-3.5 py-2.5 text-[15px]" />
</label>
</>
)}
<fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0">
<legend className="font-jua text-[19px]">조건</legend>
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')}>
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} onChange={(v) => set('temp', [v, vals.temp[1]])} />~
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} onChange={(v) => set('temp', [vals.temp[0], v])} />° 체감
</Row>
<Row label="비" on={on.rain} onToggle={() => toggle('rain')}>
<Choice label="비" value={vals.rain} onChange={(v) => set('rain', v)} options={[['dry', '안 와야'], ['wet', '와야']]} />
</Row>
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')}>
초속 <Num label="바람 상한" value={vals.wind_max} min={1} max={20} onChange={(v) => set('wind_max', v)} />m 이하
</Row>
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')}>
<Choice label="미세먼지" value={vals.air} onChange={(v) => set('air', v)} options={[['good', '좋음만'], ['normal', '보통까지']]} />
</Row>
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')}>
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />~
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} onChange={(v) => set('humidity', [vals.humidity[0], v])} />%
</Row>
<div className="flex flex-wrap items-center gap-1.5 py-2.5 text-[13.5px] font-bold">
<span className="w-[84px] text-[14px] font-extrabold">시간대</span>
{SLOTS.map(([k, word]) => (
<button key={k} type="button" aria-pressed={vals.slots.includes(k)} onClick={() => toggleSlot(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', vals.slots.includes(k) ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
{word}
</button>
))}
</div>
</fieldset>
<div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5">
<div className="flex items-center">
<b className="font-jua text-[20px] font-normal">{title}</b>
<Score s={valid ? score : undefined} big />
</div>
{valid ? <Reasons s={score} /> : <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">조건과 시간대를 하나 이상 골라요</p>}
</div>
{failed && <p className="mt-2 mb-0 text-xs font-bold text-(--heart)">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</p>}
<button
type="button"
disabled={!valid || !gakName(name) || pending}
onClick={() => create({ name, rule }, onDone)}
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
>
{shared ? '내 각으로 가져오기' : '내 각으로 저장'}
</button>
</div>
)
}