- 오늘 한 장 칸을 오늘 타로 창으로 옮김. 안 뽑았으면 빨간 점, 뽑았으면 n일째 (로그인 안 하면 기기 기록으로 계산) - 오늘 코디: 오늘 피드에 올린 코디 카드를 창으로 (GET /v1/card/latest?template=ootd), 오늘 처음 보면 빨간 점 - 단풍 지도 아이콘은 단풍철에만, 아이콘 4개 추가 (Fluent 3D) - GA4 today_icon
361 lines
16 KiB
TypeScript
361 lines
16 KiB
TypeScript
import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
import { getFortuneTodayOptions, getFortuneTodayQueryKey, importFortuneMutation, searchFortunePlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
|
import { drawFortune, saveDayLog } from '@nalssigak/shared/api/client/sdk.gen'
|
|
import type { DayLogData, LocalDraw, LocalLog, ResFortuneToday } from '@nalssigak/shared/api/client/types.gen'
|
|
import { kst } from '@nalssigak/shared/lib'
|
|
import { track } from '../lib/analytics'
|
|
import { cx } from '../lib/utils'
|
|
import { useAuth } from './authContext'
|
|
import { useRegion } from './regionContext'
|
|
import { useSheet } from './sheetContext'
|
|
import { Ic } from './ui'
|
|
|
|
const KEY = 'nalssigak.b.fortune'
|
|
// 기기에 남기는 날 수 (서버도 이 안쪽만 받는다)
|
|
const KEEP_DAYS = 60
|
|
const MOODS = ['😆', '🙂', '😐', '😕', '😢']
|
|
const STAMPS = 7
|
|
|
|
/** 로그인하지 않았을 때 이 기기에 남기는 뽑은 카드·체크인 */
|
|
type Local = { draws: LocalDraw[]; logs: LocalLog[] }
|
|
const EMPTY: Local = { draws: [], logs: [] }
|
|
|
|
function readLocal(): Local {
|
|
try {
|
|
const raw = localStorage.getItem(KEY)
|
|
return raw ? { ...EMPTY, ...(JSON.parse(raw) as Local) } : EMPTY
|
|
} catch {
|
|
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
|
|
return EMPTY
|
|
}
|
|
}
|
|
|
|
let local = readLocal()
|
|
const listeners = new Set<() => void>()
|
|
const subscribe = (cb: () => void) => {
|
|
listeners.add(cb)
|
|
return () => listeners.delete(cb)
|
|
}
|
|
|
|
function setLocal(next: Local) {
|
|
const recent = <T extends { day: string }>(rows: T[]) => [...rows].sort((a, b) => b.day.localeCompare(a.day)).slice(0, KEEP_DAYS)
|
|
local = { draws: recent(next.draws), logs: recent(next.logs) }
|
|
listeners.forEach((cb) => cb())
|
|
try {
|
|
if (local.draws.length || local.logs.length) localStorage.setItem(KEY, JSON.stringify(local))
|
|
else localStorage.removeItem(KEY)
|
|
} catch (e) {
|
|
console.warn('[fortune] 기기에 저장하지 못함', e)
|
|
}
|
|
}
|
|
|
|
const pad = (n: number) => String(n).padStart(2, '0')
|
|
function todayKst() {
|
|
const t = kst(new Date())
|
|
return `${t.y}-${pad(t.mo)}-${pad(t.d)}`
|
|
}
|
|
|
|
async function draw(regionCode: string, cardCode?: string, days: string[] = []): Promise<ResFortuneToday> {
|
|
const { data } = await drawFortune({ body: { region_code: regionCode, card_code: cardCode, days } })
|
|
if (!data.result?.success || !data.card) throw new Error(data.result?.desc ?? 'draw')
|
|
return data
|
|
}
|
|
|
|
/** 오늘 카드·행운·체크인. 로그인했으면 서버, 아니면 이 기기에 있는 오늘 카드로 행운만 서버에서 받는다 */
|
|
export function useTodayCard() {
|
|
const { loggedIn } = useAuth()
|
|
const { region } = useRegion()
|
|
const queryClient = useQueryClient()
|
|
const saved = useSyncExternalStore(subscribe, () => local)
|
|
const day = todayKst()
|
|
const mine = saved.draws.find((d) => d.day === day)
|
|
const pastDays = saved.draws.filter((d) => d.day < day).map((d) => d.day)
|
|
const serverKey = getFortuneTodayQueryKey({ query: { region: region.code } })
|
|
const deviceKey = ['fortuneDevice', region.code, mine?.card_code, day]
|
|
|
|
const server = useQuery({ ...getFortuneTodayOptions({ query: { region: region.code } }), enabled: loggedIn, staleTime: 5 * 60_000 })
|
|
const device = useQuery({
|
|
queryKey: deviceKey,
|
|
enabled: !loggedIn && !!mine,
|
|
staleTime: 5 * 60_000,
|
|
queryFn: () => draw(region.code, mine?.card_code, pastDays),
|
|
})
|
|
|
|
const pick = useMutation({
|
|
mutationFn: () => draw(region.code, undefined, loggedIn ? [] : pastDays),
|
|
onSuccess: (data) => {
|
|
track('fortune_draw', { card: data.card!.code })
|
|
if (loggedIn) {
|
|
queryClient.setQueryData(serverKey, data)
|
|
return
|
|
}
|
|
setLocal({ ...local, draws: [...local.draws.filter((d) => d.day !== data.day), { day: data.day!, card_code: data.card!.code }] })
|
|
queryClient.setQueryData(['fortuneDevice', region.code, data.card!.code, data.day], data)
|
|
},
|
|
})
|
|
|
|
// 로그인하면 이 기기에 있던 기록을 계정으로 옮긴다
|
|
const { mutate: moveUp } = useMutation({ ...importFortuneMutation() })
|
|
useEffect(() => {
|
|
if (!loggedIn || (!saved.draws.length && !saved.logs.length)) return
|
|
moveUp(
|
|
{ body: { draws: saved.draws, logs: saved.logs } },
|
|
{
|
|
onSuccess: (res) => {
|
|
if (!res.result?.success) return
|
|
setLocal(EMPTY)
|
|
queryClient.invalidateQueries({ queryKey: serverKey })
|
|
},
|
|
},
|
|
)
|
|
}, [loggedIn, saved, moveUp, queryClient, serverKey])
|
|
|
|
const today = loggedIn ? server.data : device.data
|
|
const log: DayLogData | LocalLog | undefined = (loggedIn ? today?.log : saved.logs.find((g) => g.day === day)) ?? undefined
|
|
|
|
const saveLog = useMutation({
|
|
mutationFn: async (v: Omit<LocalLog, 'day' | 'region_code'>) => {
|
|
const body = { ...v, region_code: region.code }
|
|
if (!loggedIn) {
|
|
setLocal({ ...local, logs: [...local.logs.filter((g) => g.day !== day), { ...body, day }] })
|
|
return
|
|
}
|
|
const { data } = await saveDayLog({ body })
|
|
if (!data.result?.success || !data.log) throw new Error(data.result?.desc ?? 'log')
|
|
queryClient.setQueryData(serverKey, (old: ResFortuneToday | undefined) => (old ? { ...old, log: data.log } : old))
|
|
},
|
|
onSuccess: (_, v) => track('day_log', { mood: v.mood, went_out: v.went_out, card_hit: v.card_hit ?? null }),
|
|
})
|
|
|
|
const loading = loggedIn ? server.isPending : !!mine && device.isPending
|
|
return { today, log, loading, pick, saveLog, loggedIn }
|
|
}
|
|
|
|
const shift = (day: string, n: number) => new Date(Date.parse(`${day}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10)
|
|
|
|
/** 서버 streak 과 같은 규칙: 오늘(안 뽑았으면 어제)부터 거꾸로 이어 뽑은 날 수, 하루 빠진 날은 7일에 한 번 봐준다 */
|
|
function localStreak(days: Set<string>, today: string) {
|
|
let d = days.has(today) ? today : shift(today, -1)
|
|
let count = 0
|
|
const rests: string[] = []
|
|
for (;;) {
|
|
if (days.has(d)) count++
|
|
else if (days.has(shift(d, -1)) && rests.every((r) => (Date.parse(r) - Date.parse(d)) / 86_400_000 >= 7)) rests.push(d)
|
|
else return count
|
|
d = shift(d, -1)
|
|
}
|
|
}
|
|
|
|
/** 아이콘 줄의 오늘 타로 표시: 오늘 뽑았는지, 이어 뽑은 날 수 (로그인 안 했으면 이 기기 기록으로, 서버를 부르지 않는다) */
|
|
export function useTarotBadge() {
|
|
const { loggedIn } = useAuth()
|
|
const { region } = useRegion()
|
|
const saved = useSyncExternalStore(subscribe, () => local)
|
|
const server = useQuery({ ...getFortuneTodayOptions({ query: { region: region.code } }), enabled: loggedIn, staleTime: 5 * 60_000 })
|
|
if (loggedIn) return { drawn: !!server.data?.card, streak: server.data?.streak ?? 0 }
|
|
const day = todayKst()
|
|
const days = new Set(saved.draws.map((d) => d.day))
|
|
return { drawn: days.has(day), streak: days.has(day) ? localStreak(days, day) : 0 }
|
|
}
|
|
|
|
/** 오늘 타로 창: 하루 한 장 뽑는 날씨 카드, 실제 날씨로 정한 행운, 연속 도장, 저녁엔 체크인 */
|
|
export function TarotSheet() {
|
|
const { today, log, loading, pick, saveLog, loggedIn } = useTodayCard()
|
|
const { open } = useSheet()
|
|
const shot = useRef<HTMLDivElement>(null)
|
|
const card = today?.card
|
|
const luck = today?.luck
|
|
const streak = today?.streak ?? 0
|
|
const filled = streak > 0 ? ((streak - 1) % STAMPS) + 1 : 0
|
|
|
|
const share = () => {
|
|
if (card && shot.current) open({ type: 'share', share: { title: `오늘 내 날씨 카드는 ${card.name}`, slides: [shot.current] } })
|
|
}
|
|
|
|
return (
|
|
<div className="px-4 pb-2">
|
|
{!card ? (
|
|
<button
|
|
type="button"
|
|
onClick={() => pick.mutate()}
|
|
disabled={loading || pick.isPending}
|
|
className="mx-auto flex w-full cursor-pointer flex-col items-center gap-2"
|
|
>
|
|
<img src="/fortune/back.webp" alt="" className={cx('aspect-[2/3] w-[150px] rounded-2xl object-cover', (loading || pick.isPending) && 'animate-pulse')} />
|
|
<span className="font-jua text-[16px] text-(--orange)">눌러서 오늘 카드 뽑기</span>
|
|
</button>
|
|
) : (
|
|
<div ref={shot} className="b-card-flip rounded-2xl bg-white">
|
|
<div className="flex gap-3">
|
|
<img src={`/fortune/${card.code}.webp`} alt={card.name} className="aspect-[2/3] w-[112px] shrink-0 rounded-xl object-cover" />
|
|
<div className="flex min-w-0 flex-col justify-center gap-1.5">
|
|
<b className="font-jua text-[22px] leading-tight font-normal">{card.name}</b>
|
|
<p className="m-0 text-[14px] leading-snug font-semibold text-(--ink2)">{card.reading}</p>
|
|
</div>
|
|
</div>
|
|
{luck && (
|
|
<dl className="m-0 mt-3 grid grid-cols-2 gap-1.5">
|
|
<Luck label="행운 시간" value={luck.time} sub="날씨가 가장 좋은 때" />
|
|
<Luck label="행운 장소" value={luck.place} />
|
|
<Luck label="행운 색" value={card.color} swatch={card.hex} />
|
|
<Luck label="오늘 1위" value={luck.top_gak} icon={luck.top_icon} />
|
|
</dl>
|
|
)}
|
|
<p className="m-0 mt-2 text-center text-[11px] font-semibold text-(--ink3)">재미로 보는 날씨 운세</p>
|
|
</div>
|
|
)}
|
|
{(streak > 0 || card) && (
|
|
<div className="mt-2.5 flex items-center gap-1.5">
|
|
{streak > 0 && (
|
|
<>
|
|
<span className="flex gap-1" aria-hidden>
|
|
{Array.from({ length: STAMPS }, (_, i) => (
|
|
<i key={i} className={cx('grid size-[18px] place-items-center rounded-full text-[10px] not-italic', i < filled ? 'bg-(--orange) text-white' : 'bg-[#ffe2cf]')}>
|
|
{i < filled ? '✓' : ''}
|
|
</i>
|
|
))}
|
|
</span>
|
|
<span className="text-xs font-bold text-(--ink2)">{streak}일째</span>
|
|
</>
|
|
)}
|
|
{card && (
|
|
<button type="button" onClick={share} className="ml-auto cursor-pointer rounded-full bg-(--ink) px-4 py-1.5 text-[13px] font-extrabold text-white">
|
|
공유
|
|
</button>
|
|
)}
|
|
</div>
|
|
)}
|
|
{card && today?.checkin_open && <CheckIn log={log} saving={saveLog.isPending} onSave={(v) => saveLog.mutate(v)} anon={!loggedIn} />}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function Luck({ label, value, sub, swatch, icon }: { label: string; value?: string | null; sub?: string; swatch?: string; icon?: string | null }) {
|
|
if (!value) return null
|
|
return (
|
|
<div className="rounded-xl bg-[#fff6ef] px-2.5 py-2">
|
|
<dt className="text-[11px] font-bold text-(--ink3)">{label}</dt>
|
|
<dd className="m-0 flex items-center gap-1 text-[14px] leading-tight font-extrabold">
|
|
{swatch && <span aria-hidden className="size-3 shrink-0 rounded-[4px] border border-black/10" style={{ background: swatch }} />}
|
|
{icon && <Ic name={icon} className="size-5 shrink-0" />}
|
|
<span className="truncate">{value}</span>
|
|
</dd>
|
|
{sub && <p className="m-0 text-[10.5px] font-semibold text-(--ink3)">{sub}</p>}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
type LogInput = { mood: number; went_out: boolean; place_name?: string | null; place_ref?: string | null; card_hit?: boolean | null }
|
|
|
|
/** 저녁 체크인: 기분 하나, 다녀온 곳(목록에서 찾거나 직접), 오늘 카드 맞았나 */
|
|
function CheckIn({ log, saving, onSave, anon }: { log?: LogInput; saving: boolean; onSave: (v: LogInput) => void; anon: boolean }) {
|
|
const { region } = useRegion()
|
|
const [editing, setEditing] = useState(!log)
|
|
const [mood, setMood] = useState(log?.mood ?? 0)
|
|
const [place, setPlace] = useState(log?.place_name ?? '')
|
|
const [ref, setRef] = useState<string | null>(log?.place_ref ?? null)
|
|
const [stayed, setStayed] = useState(log ? !log.went_out : false)
|
|
const [hit, setHit] = useState<boolean | null>(log?.card_hit ?? null)
|
|
const [q, setQ] = useState('')
|
|
|
|
// 글자를 멈춘 뒤에 찾는다
|
|
useEffect(() => {
|
|
const t = setTimeout(() => setQ(ref ? '' : place.trim()), 250)
|
|
return () => clearTimeout(t)
|
|
}, [place, ref])
|
|
const found = useQuery({ ...searchFortunePlacesOptions({ query: { region: region.code, q } }), enabled: q.length > 0, select: (d) => d.items ?? [] })
|
|
|
|
if (log && !editing) {
|
|
return (
|
|
<button type="button" onClick={() => setEditing(true)} className="mt-3 flex w-full cursor-pointer items-center gap-2 rounded-xl bg-[#f3f6fb] px-3 py-2.5 text-left">
|
|
<span className="text-[22px] leading-none">{MOODS[log.mood - 1]}</span>
|
|
<span className="min-w-0 flex-1">
|
|
<b className="block text-[13.5px] font-extrabold">오늘 하루를 적어 뒀어요</b>
|
|
{log.place_name && <span className="block truncate text-xs font-semibold text-(--ink2)">{log.place_name}</span>}
|
|
</span>
|
|
</button>
|
|
)
|
|
}
|
|
|
|
const ready = mood > 0 && (stayed || place.trim().length > 0)
|
|
const save = () => {
|
|
onSave({ mood, went_out: !stayed, place_name: stayed ? null : place.trim(), place_ref: stayed ? null : ref, card_hit: hit })
|
|
setEditing(false)
|
|
}
|
|
const chip = (on: boolean) => cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', on ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)')
|
|
|
|
return (
|
|
<div className="mt-3 border-t border-(--line) pt-3">
|
|
<p className="m-0 font-jua text-[17px]">오늘 하루 어땠어요?</p>
|
|
<div className="mt-2 flex justify-between">
|
|
{MOODS.map((m, i) => (
|
|
<button key={m} type="button" onClick={() => setMood(i + 1)} aria-pressed={mood === i + 1} className={cx('grid size-11 cursor-pointer place-items-center rounded-full text-[24px]', mood === i + 1 ? 'bg-[#ffe2cf] ring-2 ring-(--orange)' : 'bg-[#f3f6fb]')}>
|
|
{m}
|
|
</button>
|
|
))}
|
|
</div>
|
|
|
|
<p className="m-0 mt-3.5 text-[14px] font-extrabold">어디 다녀왔어요?</p>
|
|
<div className="relative mt-1.5 flex gap-1.5">
|
|
<input
|
|
value={place}
|
|
onChange={(e) => {
|
|
setPlace(e.target.value.slice(0, 40))
|
|
setRef(null)
|
|
setStayed(false)
|
|
}}
|
|
placeholder="장소 이름"
|
|
disabled={stayed}
|
|
className="min-w-0 flex-1 rounded-xl border border-(--line) bg-white px-3 py-2 text-[14px] font-semibold disabled:opacity-50"
|
|
/>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setStayed(!stayed)
|
|
setPlace('')
|
|
setRef(null)
|
|
}}
|
|
aria-pressed={stayed}
|
|
className={chip(stayed)}
|
|
>
|
|
안 나갔어요
|
|
</button>
|
|
{!stayed && !ref && (found.data?.length ?? 0) > 0 && (
|
|
<ul className="absolute top-full right-0 left-0 z-10 m-0 mt-1 max-h-48 list-none overflow-auto rounded-xl border border-(--line) bg-white p-1 shadow-lg">
|
|
{found.data!.map((p) => (
|
|
<li key={p.ref}>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setPlace(p.name)
|
|
setRef(p.ref)
|
|
}}
|
|
className="w-full cursor-pointer rounded-lg px-2.5 py-2 text-left text-[14px] font-semibold hover:bg-[#f3f6fb]"
|
|
>
|
|
{p.name}
|
|
</button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</div>
|
|
|
|
<p className="m-0 mt-3.5 text-[14px] font-extrabold">오늘 카드, 맞았어요?</p>
|
|
<div className="mt-1.5 flex gap-1.5">
|
|
<button type="button" onClick={() => setHit(hit === true ? null : true)} aria-pressed={hit === true} className={chip(hit === true)}>
|
|
맞았어요
|
|
</button>
|
|
<button type="button" onClick={() => setHit(hit === false ? null : false)} aria-pressed={hit === false} className={chip(hit === false)}>
|
|
글쎄요
|
|
</button>
|
|
</div>
|
|
|
|
<button type="button" onClick={save} disabled={!ready || saving} className="mt-3.5 w-full cursor-pointer rounded-full bg-(--orange) py-2.5 text-[14px] font-extrabold text-white disabled:opacity-40">
|
|
적어 두기
|
|
</button>
|
|
{anon && <p className="m-0 mt-2 text-center text-[11.5px] font-semibold text-(--ink3)">이 기기에만 남아요. 로그인하면 폰을 바꿔도 남아요.</p>}
|
|
</div>
|
|
)
|
|
}
|