Files
o2o-weather/frontend/src/b/myGak.tsx
T
minaChoi ffe6153148 feat: 내 각 아이콘·상세, 이야기 내 글·무한 스크롤, 공유 이미지 얇은 띠, 행사 주소 수집
- 내 각: 아이콘 고르기(my_gak.icon), 카드는 아이콘·점수·아쉬운 조건만, 눌러서 상세(시간대·조건별 점수), 공유는 공통 공유 창
- 이야기: 오늘 쓴 내 글 묶음, '내 글' 칩·탭, 무한 스크롤, 사진 카메라 버튼, 지우기 확인, ⋯ 메뉴 하트 옆, 글 시간 서버 계산(1일 전)
- 공유 이미지: 1:1·4:5 는 아래 얇은 띠 한 줄로 카드를 크게
- 행사: 수집 때 주소 저장(event.address), 행사 포스트에 장소·주소·기간
- 히어로 말풍선 '오늘 낮은 / 내일 낮은', 내일을 볼 때 배경도 따라감, 달 보름 순간이 낮이면 뜨는 시각으로
- 단풍 지도 피드 맨 위, 행사·계절 띠 포스트 틀 되돌림, 쇼츠 홈 버튼 가림·닫기 버튼, 하단 여백, 회색 글자 대비
- 토스 앱에선 쇼츠 플레이어를 하나만 띄움
2026-10-27 18:55:42 +09:00

372 lines
18 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 { useRef, useState, type ReactNode } from 'react'
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { gakName, MY_GAK_ICON, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
import { MyGakShareCard } from './shareCards'
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>
)
}
// 조건 이름. 점수 응답의 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 ?? []
const shots = useRef<(HTMLDivElement | null)[]>([])
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail label="내 각">
{items.map((g, i) => {
const s = scores[i]
const miss = conditions(s).filter((c) => c.value < SHORT).slice(0, 2)
return (
<button
key={g.id ?? 'local'}
type="button"
onClick={() => open({ type: 'myGak', gak: g, shot: shots.current[i] })}
aria-label={`${g.name} ${s?.score ?? ''}점 자세히`}
className="flex w-[200px] cursor-pointer flex-col gap-2 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]"
>
<span className="flex w-full items-start justify-between">
<Ic name={g.icon ?? MY_GAK_ICON} className="size-10" />
<Score s={s} big />
</span>
<span>
<b className="block font-jua text-[17px] leading-tight font-normal">{g.name}</b>
<small className="text-xs font-bold text-(--ink3)">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'}</small>
</span>
{s?.slot && (
<span className="flex flex-wrap gap-1 text-[11.5px] font-extrabold">
{miss.length ? (
miss.map((c) => (
<span key={c.axis} className="rounded-full bg-[#ffe8dc] px-2 py-0.5 text-[#c2471b]">
{c.short}
</span>
))
) : (
<span className="rounded-full bg-[#dff5ea] px-2 py-0.5 text-[#1f7a4f]">조건 다 맞아요</span>
)}
</span>
)}
</button>
)
})}
<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>
{items.map((g, i) => (
<MyGakShareCard
key={g.id ?? 'local'}
name={g.name}
icon={g.icon ?? MY_GAK_ICON}
score={scores[i]?.score}
slot={scores[i]?.slot ? SLOT_WORD[scores[i].slot as Slot] : undefined}
rows={conditions(scores[i])}
ref={(el) => {
shots.current[i] = el
}}
/>
))}
</>
)
}
/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기(다른 포스트와 같은 공유 창)·지우기 */
export function MyGakSheet({ gak, shot, onDone }: { gak: MyGak; shot?: HTMLElement | null; onDone: () => void }) {
const { open } = useSheet()
const { remove } = useMyGak()
const s = useMyGakScores([gak.rule]).data?.scores?.[0]
const [confirm, setConfirm] = useState(false)
const rows = conditions(s)
return (
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
<div className="flex items-center gap-3">
<Ic name={gak.icon ?? MY_GAK_ICON} className="size-14" />
<span className="min-w-0 flex-1">
<b className="block font-jua text-[22px] leading-tight font-normal">{gak.name}</b>
<small className="text-[12.5px] font-bold text-(--ink3)">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'}</small>
</span>
<Score s={s} big />
</div>
<div className="mt-3 grid grid-cols-4 gap-1.5" aria-label="시간대별 점수">
{SLOTS.map(([k, word]) => {
const v = s?.slots?.[k]
return (
<div key={k} className={cx('rounded-2xl px-1 py-2 text-center', s?.slot === k ? 'bg-[#fff4ec]' : 'bg-[#f3f6fb]')}>
<small className="block text-xs font-extrabold text-(--ink2)">{word}</small>
<b className={cx('block font-bagel text-xl font-normal', v != null ? 'text-(--orange)' : 'text-(--ink3)')}>{v ?? '–'}</b>
</div>
)
})}
</div>
<div className="mt-3.5 flex flex-col gap-2.5">
{rows.map((c) => (
<div key={c.axis} className="grid grid-cols-[64px_1fr_32px] items-center gap-x-2.5 text-[13.5px] font-bold">
<span>{c.label}</span>
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
<s className="b-keep-bg block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${c.value}%` }} />
</i>
<em className="text-right text-xs text-(--ink2) not-italic tabular-nums">{c.value}</em>
<p className="col-start-2 col-end-4 m-0 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{c.note}</p>
</div>
))}
</div>
<div className="mt-4 flex gap-2">
<button
type="button"
onClick={() => open({ type: 'share', share: { title: gak.name, slides: shot ? [shot] : [], url: shareUrl(gak) } })}
disabled={!shot}
className="flex-1 cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[16px] text-white disabled:opacity-45"
>
공유하기
</button>
{confirm ? (
<>
<button
type="button"
onClick={() => {
remove(gak)
onDone()
}}
className="cursor-pointer rounded-2xl bg-[#fdecec] px-4 py-3 font-jua text-[16px] text-(--heart)"
>
지우기
</button>
<button type="button" onClick={() => setConfirm(false)} className="cursor-pointer rounded-2xl bg-[#eef4fc] px-4 py-3 font-jua text-[16px] text-(--ink2)">
취소
</button>
</>
) : (
<button type="button" onClick={() => setConfirm(true)} className="cursor-pointer rounded-2xl bg-[#eef4fc] px-4 py-3 font-jua text-[16px] text-(--ink2)">
지우기
</button>
)}
</div>
{confirm && <p className="mt-1.5 mb-0 text-right text-[12.5px] font-bold text-(--ink2)">지울까요?</p>}
</div>
)
}
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 IconPicker({ value, onPick }: { value: string; onPick: (icon: string) => void }) {
const icons = [...new Set([MY_GAK_ICON, ...(usePresets().data ?? []).map((p) => p.icon)])]
return (
<div className="mt-3">
<span className="font-jua text-[19px]">아이콘</span>
<div className="-mx-4">
<Rail label="아이콘" className="gap-1.5">
{icons.map((icon) => (
<button
key={icon}
type="button"
aria-pressed={value === icon}
aria-label={`아이콘 ${icon}`}
onClick={() => onPick(icon)}
className={cx('grid size-12 cursor-pointer place-items-center rounded-2xl', value === icon ? 'bg-(--orange) ring-2 ring-(--orange)' : 'bg-[#f3f6fb]')}
>
<Ic name={icon} className="size-8" />
</button>
))}
</Rail>
</div>
</div>
)
}
/** 있는 각을 골라 그 각 조건으로 채운다 */
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 [icon, setIcon] = useState(shared?.icon ?? MY_GAK_ICON)
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 (
<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>
<IconPicker value={icon} onPick={setIcon} />
</>
)}
<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 gap-2">
<Ic name={icon} className="size-8" />
<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, icon, 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>
)
}