Merge remote-tracking branch 'origin/main' into feat/weather-game

# Conflicts:
#	shared/api/client/@tanstack/react-query.gen.ts
#	shared/api/client/index.ts
#	shared/api/client/sdk.gen.ts
#	shared/api/client/types.gen.ts
This commit is contained in:
minaChoi committed 2026-10-28 16:49:32 +09:00
commit 9e7bd54c7e
48 files changed
+3253 -189

No files matched your search

+454
View File
@@ -0,0 +1,454 @@
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useNavigate } from 'react-router'
import { useMutation, useQuery } from '@tanstack/react-query'
import { matchMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { reading } from '@nalssigak/shared/api/client/sdk.gen'
import type { ResSaju, ResSajuMatch, SajuCard, SajuLock } from '@nalssigak/shared/api/client/types.gen'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { progress, useLevel } from './level'
import { useRegion } from './regionContext'
import { BIRTH_PLACES, placeLon, setBirth, useBirth, validBirth, type Birth } from './sajuBirth'
import { useSheet } from './sheetContext'
import { Ic, TAP44 } from './ui'
const SEEN_KEY = 'nalssigak.b.sajuSeen'
const EL_COLOR: Record<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] }
const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' }
const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' }
const toBody = (b: Birth) => ({
birth_date: `${b.y}-${String(b.m).padStart(2, '0')}-${String(b.d).padStart(2, '0')}`,
birth_time: b.hour != null ? `${String(b.hour).padStart(2, '0')}:${String(b.minute ?? 0).padStart(2, '0')}` : undefined,
longitude: placeLon(b.place),
})
/** 오늘 아이콘 줄의 빨간 점: 오늘 날씨 사주를 아직 안 봤는지 */
export function sajuSeenToday() {
try {
return localStorage.getItem(SEEN_KEY) === new Date().toDateString()
} catch {
// 저장소를 못 쓰면 점을 보이지 않는다
return true
}
}
function markSeen() {
try {
localStorage.setItem(SEEN_KEY, new Date().toDateString())
} catch (e) {
console.warn('[saju] 본 날을 저장하지 못함', e)
}
}
/** 날씨 사주 페이지(/saju): 오늘 점수와 할 일, 내 기운, 레벨로 열리는 이번 주·금전·연애·궁합·이달·올해 */
export function SajuPage() {
const navigate = useNavigate()
const birth = useBirth()
const [editing, setEditing] = useState(false)
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
return (
<div className="pb-8">
<div className="flex items-center gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<h2 className="m-0 flex items-center gap-1.5 px-1 font-jua text-[24px] font-normal">
<Ic name="yin_yang" className="size-7" />
날씨 사주
</h2>
</div>
{!birth || editing ? <BirthForm initial={birth} onDone={() => setEditing(false)} /> : <Reading birth={birth} onEdit={() => setEditing(true)} />}
</div>
)
}
function BirthForm({ initial, onDone }: { initial: Birth | null; onDone: () => void }) {
const [y, setY] = useState(initial ? String(initial.y) : '')
const [m, setM] = useState(initial ? String(initial.m) : '')
const [d, setD] = useState(initial ? String(initial.d) : '')
const [time, setTime] = useState(initial?.hour != null ? `${String(initial.hour).padStart(2, '0')}:${String(initial.minute ?? 0).padStart(2, '0')}` : '')
const [place, setPlace] = useState(initial?.place ?? 'seoul')
const [error, setError] = useState('')
const input = 'min-w-0 flex-1 rounded-2xl border-[1.5px] border-(--line) bg-white px-3 py-3 text-center text-[17px] font-bold'
const save = () => {
const [yy, mm, dd] = [Number(y), Number(m), Number(d)]
if (!validBirth(yy, mm, dd)) return setError('날짜를 다시 확인해 주세요')
const [hh, mi] = time ? time.split(':').map(Number) : [null, null]
setBirth({ y: yy, m: mm, d: dd, hour: hh, minute: mi, place, gender: initial?.gender ?? null })
track('saju_input', { with_time: time !== '' })
onDone()
}
return (
<div className="mx-4 mt-4 flex flex-col gap-4 rounded-[24px] bg-white p-5 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="text-center">
<Ic name="yin_yang" className="mx-auto size-14" />
<p className="m-0 mt-2 font-jua text-[20px] leading-snug">태어난 날의 기운으로<br />오늘 날씨와 맞춰 봐요</p>
</div>
<label className="flex flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
생년월일 (양력)
<span className="flex gap-1.5">
<input inputMode="numeric" placeholder="1995" value={y} onChange={(e) => setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="년" />
<input inputMode="numeric" placeholder="3" value={m} onChange={(e) => setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="월" />
<input inputMode="numeric" placeholder="14" value={d} onChange={(e) => setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="일" />
</span>
</label>
<label className="flex flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
태어난 시각 (모르면 비워 두세요)
<input type="time" value={time} onChange={(e) => setTime(e.target.value)} className={cx(input, 'w-full')} />
</label>
<label className="flex flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
태어난 곳 (시각을 그곳에 맞춰요)
<select value={place} onChange={(e) => setPlace(e.target.value)} className={cx(input, 'w-full')}>
{BIRTH_PLACES.map(([k, n]) => (
<option key={k} value={k}>
{n}
</option>
))}
</select>
</label>
{error && <p className="m-0 text-center text-[13px] font-bold text-[#d9442f]">{error}</p>}
<button type="button" onClick={save} className="cursor-pointer rounded-full bg-(--orange) py-3.5 text-[15px] font-extrabold text-white">
내 기운 보기
</button>
<p className="m-0 text-center text-xs font-semibold text-(--ink3)">생년월일은 이 기기에만 저장돼요. 계산할 때만 보내고 서버에 남기지 않아요.</p>
</div>
)
}
function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
const { region } = useRegion()
const { loggedIn } = useAuth()
const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined }
const q = useQuery({
queryKey: ['saju', body, loggedIn],
staleTime: 10 * 60_000,
queryFn: async () => {
const { data } = await reading({ body })
if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju')
return data
},
})
const shot = useRef<HTMLDivElement>(null)
const { open } = useSheet()
const r = q.data
useEffect(() => {
if (!r?.today || !window.location.hash) return
document.getElementById(window.location.hash.slice(1))?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}, [r])
useEffect(() => {
if (!r?.today) return
markSeen()
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score })
}, [r])
if (q.isPending) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">기운을 읽는 중이에요…</p>
if (!r?.today || !r.me) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">지금은 읽지 못했어요. 잠시 뒤에 다시 열어 주세요.</p>
const t = r.today
const lock = (key: string) => r.locks?.find((l) => l.key === key)
return (
<div className="flex flex-col gap-3">
<div ref={shot} className="mx-4 mt-3 rounded-[26px] bg-white px-5 pt-4 pb-5 shadow-[inset_0_-5px_0_var(--shade)]">
<p className="m-0 text-center text-[12.5px] font-extrabold text-(--ink3)">
{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수
</p>
<p className="m-0 text-center font-bagel text-[60px] leading-none">{t.score}</p>
<h3 className="m-0 mt-1.5 text-center font-jua text-[23px] leading-tight font-normal">{t.title}</h3>
<div className="mt-2.5 flex flex-wrap justify-center gap-1.5 text-[11.5px] font-extrabold">
<span className="rounded-full bg-[#f3f6fb] px-2.5 py-1">사주 {t.saju_score}</span>
{t.weather_points != null && (
<span className={cx('rounded-full px-2.5 py-1', t.weather_points >= 0 ? 'bg-[#e3f6ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>
오늘 날씨와 궁합 {t.weather_points >= 0 ? '+' : '−'}
{Math.abs(t.weather_points)}
</span>
)}
</div>
{(t.why?.length ?? 0) > 0 && (
<details className="mt-2 text-center">
<summary className="cursor-pointer text-xs font-bold text-(--ink3)">왜 이 점수인가요?</summary>
<ul className="m-0 mt-1.5 list-none p-0 text-xs font-semibold text-(--ink2)">
{t.why!.map((w) => (
<li key={w}>{w}</li>
))}
</ul>
</details>
)}
</div>
<section aria-label="오늘의 결정" className="mx-4 flex flex-col gap-2">
{t.cards.map((c) => (
<DecisionCard key={c.kind} c={c} />
))}
</section>
<MeCard r={r} onEdit={onEdit} />
{r.week && <Week r={r} />}
{r.money && (
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
{[...r.money.map((l) => ['💰', l]), ...(r.work ?? []).map((l) => ['💼', l])].map(([icon, l]) => (
<p key={l} className="m-0 mt-1 text-[14px] font-semibold first:mt-0">
{icon} {l}
</p>
))}
</Panel>
)}
{r.love && <Love r={r} birth={birth} />}
{lock('saju_match')?.unlocked && <Match birth={birth} />}
{r.month && <Period id="saju_month" icon="spiral_calendar" p={r.month} />}
{r.year && <Period id="saju_year" icon="sunrise" p={r.year} />}
<Locked locks={(r.locks ?? []).filter((l) => !l.unlocked)} />
<div className="mx-4 flex items-center justify-between">
<span className="text-xs font-semibold text-(--ink3)">재미로 보는 날씨 사주</span>
<button
type="button"
onClick={() => shot.current && open({ type: 'share', share: { title: `오늘 내 날씨 사주 ${t.score}점 · ${t.title}`, slides: [shot.current] } })}
className="cursor-pointer rounded-full bg-(--ink) px-4 py-2 text-[13px] font-extrabold text-white"
>
공유
</button>
</div>
</div>
)
}
function DecisionCard({ c }: { c: SajuCard }) {
return (
<div className="flex gap-3 rounded-[20px] bg-white px-4 py-3 shadow-[inset_0_-4px_0_var(--shade)]">
<Ic name={CARD_ICON[c.kind] ?? 'sparkles'} className="mt-0.5 size-8 shrink-0" />
<div className="min-w-0">
<p className="m-0 text-[12px] font-extrabold text-(--orange)">{c.kind === 'when' ? '중요한 일은 이때' : c.title}</p>
<p className="m-0 font-jua text-[17px] leading-snug whitespace-pre-line">{c.kind === 'when' ? `${c.title} · ${c.sub}` : c.body}</p>
<p className="m-0 mt-0.5 text-[12px] leading-snug font-semibold text-(--ink3)">{c.kind === 'when' ? c.body : c.sub}</p>
</div>
</div>
)
}
function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
const me = r.me!
const cols = [...me.pillars].reverse()
return (
<Panel icon={me.scene_icon} title={`내 기운 · ${me.scene}`} right={<button type="button" onClick={onEdit} className="cursor-pointer text-xs font-extrabold text-(--orange)">생년월일 바꾸기</button>}>
<p className="m-0 text-[14px] font-semibold text-(--ink2)">{me.scene_desc}</p>
<div className="mt-3 grid grid-cols-4 gap-1.5 text-center">
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
<div key={p?.position ?? `none-${i}`} className="flex flex-col gap-1">
<span className="text-[11px] font-extrabold text-(--ink3)">{p ? POS_WORD[p.position] : '시'}</span>
{p ? (
<>
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} />
<Char c={p.branch} ko={p.branch_ko} el={p.branch_element} />
</>
) : (
<>
<span className="rounded-xl bg-[#f1f3f7] py-3 text-[14px] font-extrabold text-[#a0a8ba]">?</span>
<span className="rounded-xl bg-[#f1f3f7] py-3 text-[14px] font-extrabold text-[#a0a8ba]">?</span>
</>
)}
</div>
))}
</div>
{(me.need?.length ?? 0) > 0 && <p className="m-0 mt-2.5 text-[13px] font-bold">내 기운에 필요한 날씨: {me.need!.join(' · ')}</p>}
{me.jeol_warning && <p className="m-0 mt-1 text-xs font-semibold text-[#c2471b]">태어난 날 절기가 바뀌어요. 시각을 넣으면 더 정확해요.</p>}
</Panel>
)
}
function Char({ c, ko, el }: { c: string; ko: string; el: string }) {
const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb']
return (
<span className="rounded-xl py-1.5" style={{ background: bg, color: fg }}>
<b className="block font-batang text-[22px] leading-tight">{c}</b>
<small className="text-[10.5px] font-extrabold">{ko}</small>
</span>
)
}
function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) {
return (
<section id={id} className="mx-4 scroll-mt-20 rounded-[22px] bg-white px-4 py-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<div className="mb-2 flex items-center gap-2">
<Ic name={icon} className="size-7" />
<h3 className="m-0 font-jua text-[17px] font-normal">{title}</h3>
{right && <span className="ml-auto">{right}</span>}
</div>
{children}
</section>
)
}
/** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */
function Locked({ locks }: { locks: SajuLock[] }) {
const { loggedIn } = useAuth()
const { open } = useSheet()
const level = useLevel().data
if (!locks.length) return null
const [next, ...rest] = [...locks].sort((a, b) => a.level - b.level)
const close = loggedIn && level && level.next_points != null && level.level + 1 === next.level
return (
<section className="mx-4 rounded-[22px] bg-[#eef1f7] px-4 py-3.5">
<div className="flex items-center gap-3">
<Ic name="locked" className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16px]">{loggedIn ? `다음에 열려요: ${next.name}` : '각을 모으면 차례로 열려요'}</p>
<p className="m-0 text-xs font-bold text-(--ink2)">
{loggedIn ? `Lv.${next.level}에서 열려요${close ? ` · ${level.next_points! - level.points}각 남았어요` : ''}` : '출석·사주·좋아요로 모은 각은 로그인해야 쌓여요'}
</p>
</div>
<button type="button" onClick={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-xs font-extrabold text-white">
{loggedIn ? '각 모으기' : '로그인'}
</button>
</div>
{close && (
<span className="mt-2.5 block h-1.5 overflow-hidden rounded-full bg-white">
<span className="block h-full rounded-full bg-(--orange)" style={{ width: `${Math.round(progress(level) * 100)}%` }} />
</span>
)}
<ul className="m-0 mt-2.5 flex list-none flex-wrap gap-1.5 p-0">
{(loggedIn ? rest : [next, ...rest]).map((l) => (
<li key={l.key} className="rounded-full bg-white px-2.5 py-1 text-[11.5px] font-extrabold text-(--ink2)">
Lv.{l.level} {l.name}
</li>
))}
</ul>
</section>
)
}
function Week({ r }: { r: ResSaju }) {
return (
<Panel id="saju_week" icon="spiral_calendar" title="이번 주 흐름">
<ol className="m-0 flex list-none flex-col gap-1 p-0">
{r.week!.map((d) => (
<li key={d.day} className={cx('flex items-center gap-2 rounded-xl px-2 py-1.5 text-[13px] font-bold', d.best && 'bg-[#fff6ef]')}>
<span className="w-14 shrink-0">
{d.weekday} {Number(d.day.slice(8, 10))}일
</span>
{d.icon && <Ic name={d.icon} className="size-6 shrink-0" />}
<span className="w-14 shrink-0 text-(--ink2)">{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}</span>
<span className="min-w-0 flex-1 truncate text-(--ink2)">{d.title}</span>
<b className={cx('font-bagel text-[15px] font-normal', d.best ? 'text-(--orange)' : '')}>{d.score}</b>
</li>
))}
</ol>
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">점수는 그날 사주와 예보로 계산해요. 주황색이 이번 주 가장 좋은 날이에요.</p>
</Panel>
)
}
function Love({ r, birth }: { r: ResSaju; birth: Birth }) {
const love = r.love!
const pick = (g: 'M' | 'F' | null) => setBirth({ ...birth, gender: g })
return (
<Panel id="saju_love" icon="red_heart" title="이번 주 연애운">
{love.good ? (
<div className="rounded-xl bg-[#fff0f3] px-3 py-2.5">
<p className="m-0 text-xs font-extrabold text-[#d6457a]">연애 기운 좋은 날</p>
<p className="m-0 font-jua text-[17px]">
{love.good.weekday}요일 {Number(love.good.day.slice(8, 10))}일{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
</p>
<p className="m-0 text-[13px] font-semibold">{love.good.body}</p>
<p className="m-0 text-[11.5px] font-semibold text-(--ink3)">{love.good.why}</p>
</div>
) : (
<p className="m-0 text-[13px] font-semibold text-(--ink2)">이번 주엔 연애 기운이 특별히 드는 날이 없어요.</p>
)}
{love.caution && (
<p className="m-0 mt-2 text-[13px] font-semibold">
조심할 날: {love.caution.weekday}요일 — {love.caution.body} <span className="text-(--ink3)">({love.caution.why})</span>
</p>
)}
{!love.gender_known && (
<div className="mt-2.5 flex items-center gap-1.5 text-xs font-bold text-(--ink2)">
성별을 고르면 이성 기운까지 봐요
<button type="button" onClick={() => pick('M')} className="cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1">
남
</button>
<button type="button" onClick={() => pick('F')} className="cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1">
여
</button>
</div>
)}
</Panel>
)
}
function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResSaju['month']> }) {
return (
<Panel id={id} icon={icon} title={p.label}>
<p className="m-0 font-jua text-[17px]">
{p.title} <span className="text-[13px] text-(--ink3)">({p.pillar} · {p.ten_god})</span>
</p>
<p className="m-0 mt-0.5 text-[13.5px] font-semibold">{p.body}</p>
{(p.months?.length ?? 0) > 0 && <p className="m-0 mt-1.5 text-[13.5px] font-bold">잘 맞는 달: {p.months!.map((m) => `${m}월`).join(' · ')}</p>}
{(p.notes?.length ?? 0) > 0 && <p className="m-0 mt-1 text-xs font-semibold text-(--ink3)">{p.notes!.join(' · ')}</p>}
</Panel>
)
}
function Match({ birth }: { birth: Birth }) {
const { region } = useRegion()
const [y, setY] = useState('')
const [m, setM] = useState('')
const [d, setD] = useState('')
const [error, setError] = useState('')
const run = useMutation({ ...matchMutation() })
const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined
const input = 'min-w-0 flex-1 rounded-xl border-[1.5px] border-(--line) bg-white px-2 py-2 text-center text-[15px] font-bold'
const go = () => {
const [yy, mm, dd] = [Number(y), Number(m), Number(d)]
if (!validBirth(yy, mm, dd)) return setError('날짜를 다시 확인해 주세요')
setError('')
run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${yy}-${String(mm).padStart(2, '0')}-${String(dd).padStart(2, '0')}`, longitude: 126.98 } } })
}
return (
<Panel id="saju_match" icon="two_hearts" title="궁합">
{res ? (
<>
<p className="m-0 mb-1 flex items-center justify-between text-xs font-bold text-(--ink3)">
상대 {y}.{m}.{d}생
<button type="button" onClick={() => run.reset()} className="cursor-pointer font-extrabold text-(--orange)">
다른 사람 보기
</button>
</p>
<p className="m-0 font-jua text-[19px]">
{res.title} <span className="font-bagel text-[17px] text-(--orange)">{res.score}</span>
</p>
{res.lines?.map((l) => (
<p key={l} className="m-0 mt-1 text-[13.5px] font-semibold">
{l}
</p>
))}
{res.day && (
<p className="m-0 mt-2 rounded-xl bg-[#fff6ef] px-3 py-2 text-[13.5px] font-bold">
이번 주 같이 나가기 좋은 날: {res.day.weekday}요일 {Number(res.day.day.slice(8, 10))}일{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
</p>
)}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 기운: {res.friend_scene}</p>
</>
) : (
<>
<p className="m-0 mb-2 text-[13px] font-semibold text-(--ink2)">상대 생년월일(양력)을 넣으면 둘의 사이와 이번 주 같이 나가기 좋은 날을 봐요.</p>
<div className="flex gap-1.5">
<input inputMode="numeric" placeholder="1996" value={y} onChange={(e) => setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" />
<input inputMode="numeric" placeholder="11" value={m} onChange={(e) => setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" />
<input inputMode="numeric" placeholder="2" value={d} onChange={(e) => setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" />
<button type="button" onClick={go} disabled={run.isPending} className="shrink-0 cursor-pointer rounded-xl bg-(--orange) px-3 text-[14px] font-extrabold text-white">
보기
</button>
</div>
{error && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">{error}</p>}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 생년월일은 저장하지 않아요.</p>
</>
)}
</Panel>
)
}
+4 -6
View File
@@ -37,7 +37,6 @@ import { InstallSheet } from './installBanner'
import { ARTICLE_CAT, SHEET_CLOSE_MS, SHEET_OPEN_MS } from './lib'
import { MixSheet, MyGakSheet } from './myGak'
import { TarotSheet } from './fortune'
import { OotdSheet } from './todayIcons'
import { LevelCard, LevelSheet, LevelUpSheet, useShareReward } from './level'
import { ownPage, useRegion } from './regionContext'
import { WeatherWhySheet } from './weatherWhy'
@@ -90,7 +89,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
)
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', tarot: '오늘 타로', ootd: '오늘 코디', level: '내 레벨', levelUp: '레벨이 올랐어요', gameHelp: '구름 합치기 하는 법' } as const
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기', tarot: '오늘 타로', level: '내 레벨', levelUp: '레벨이 올랐어요', gameHelp: '구름 합치기 하는 법' } as const
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
@@ -170,7 +169,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{shown.type === 'seasonWeek' && <SeasonWeekSheet />}
{shown.type === 'share' && <ShareSheet share={shown.share} />}
{shown.type === 'comments' && <CommentsSheet postId={shown.postId} draft={shown.draft} />}
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{shown.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={shown.why} />}
{shown.type === 'me' && <MeSheet onDone={onClose} />}
{shown.type === 'region' && <RegionSheet onDone={onClose} />}
{shown.type === 'mix' && <MixSheet shared={shown.shared} onDone={onClose} />}
@@ -178,7 +177,6 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{shown.type === 'install' && <InstallSheet />}
{shown.type === 'weatherWhy' && <WeatherWhySheet d={shown.why} />}
{shown.type === 'tarot' && <TarotSheet />}
{shown.type === 'ootd' && <OotdSheet />}
{shown.type === 'level' && <LevelSheet />}
{shown.type === 'levelUp' && <LevelUpSheet level={shown.level} />}
{shown.type === 'talk' && <TalkSheet talk={shown.talk} />}
@@ -1025,7 +1023,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
}
/* ---------- 로그인 ---------- */
function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
function LoginSheet({ onDone, onLoggedIn, why }: { onDone: () => void; onLoggedIn: () => void; why?: 'level' }) {
const { me } = useAuth()
const [error, setError] = useState('')
@@ -1046,7 +1044,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: ()
return (
<Body>
<div className="flex flex-col gap-2.5">
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기는 로그인한 뒤에 할 수 있어요.</p>
<p className="text-center text-sm font-semibold text-(--ink2)">{why === 'level' ? '로그인하면 출석·사주·좋아요로 각이 쌓여 레벨이 올라요.' : '글쓰기는 로그인한 뒤에 할 수 있어요.'}</p>
<GoogleButton
onResult={(res) => {
setError('')
+2
View File
@@ -0,0 +1,2 @@
/** 잠시 숨긴 기능 (아이콘 줄·각 모으는 법에서 뺀다). 다시 보이려면 여기서 지운다 */
export const HIDDEN = new Set<string>(['tarot'])
+34 -4
View File
@@ -1,12 +1,28 @@
import { useEffect, useRef } from 'react'
import { useNavigate } from 'react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { attendMutation, myLevelOptions, myLevelQueryKey, sharedMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import type { ResLevel } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { HIDDEN } from './features'
import { useSheet } from './sheetContext'
import { Ic } from './ui'
// 각을 주는 일 → 그 일을 하러 가는 곳, 숨긴 기능에 딸린 일 (서버 ACTIONS 키)
const ACTION_TO: Record<string, string> = { saju: '/saju', react: '/', talk: '/talk' }
const ACTION_FEATURE: Record<string, string> = { tarot: 'tarot', checkin: 'tarot' }
// 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로, 되돌린 뒤(popstate)에 이동해야 새 주소가 안 지워진다
function useCloseAndGo() {
const { close } = useSheet()
const navigate = useNavigate()
return (to: string) => {
window.addEventListener('popstate', () => navigate(to), { once: true })
close()
}
}
// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 LEVELS)
const LEVEL_ICON = ['droplet', 'sun', 'leaf', 'rainbow', 'sunset', 'milky_way', 'shooting_star']
export const levelIcon = (level: number) => LEVEL_ICON[Math.min(Math.max(level, 1), LEVEL_ICON.length) - 1]
@@ -125,6 +141,7 @@ export function LevelCard({ link = true }: { link?: boolean }) {
/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */
export function LevelSheet() {
const level = useLevel().data
const go = useCloseAndGo()
if (!level) return null
const steps = (level.unlocks ?? []).reduce<Record<number, string[]>>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {})
return (
@@ -133,15 +150,21 @@ export function LevelSheet() {
<section>
<h4 className="m-0 mb-2 text-sm font-extrabold">오늘 받을 수 있는 각</h4>
<ul className="m-0 list-none rounded-2xl bg-white p-0 shadow-[inset_0_-4px_0_var(--shade)]">
{(level.today ?? []).map((a) => {
{(level.today ?? []).filter((a) => !HIDDEN.has(ACTION_FEATURE[a.action] ?? a.action)).map((a) => {
const done = a.earned >= a.cap
const to = ACTION_TO[a.action]
return (
<li key={a.action} className="flex items-center gap-2.5 border-b border-[#eef1f6] px-3.5 py-2.5 text-[13.5px] font-bold last:border-0">
<li
key={a.action}
onClick={to && !done ? () => go(to) : undefined}
className={cx('flex items-center gap-2.5 border-b border-[#eef1f6] px-3.5 py-2.5 text-[13.5px] font-bold last:border-0', to && !done && 'cursor-pointer')}
>
<span className={cx('grid size-5 place-items-center rounded-full text-[11px] text-white', done ? 'bg-[#1f9d62]' : 'bg-[#dfe5ef]')}>{done ? '✓' : ''}</span>
<span className={cx(done && 'text-(--ink3) line-through')}>{a.name}</span>
<span className="ml-auto font-bagel text-[13px] font-normal text-(--orange)">
{a.earned > 0 && a.cap > a.points ? `${a.earned}/${a.cap}` : `+${a.points}`}각
</span>
{to && !done && <span className="text-(--ink3)">›</span>}
</li>
)
})}
@@ -175,7 +198,9 @@ export function LevelSheet() {
export function LevelUpSheet({ level: lv }: { level: number }) {
const level = useLevel().data
const { open } = useSheet()
const opened = (level?.unlocks ?? []).filter((u) => u.level === lv).map((u) => u.name)
const go = useCloseAndGo()
const unlocks = (level?.unlocks ?? []).filter((u) => u.level === lv)
const opened = unlocks.map((u) => u.name)
const name = level?.levels?.find((l) => l.level === lv)?.name
return (
<div className="flex flex-col items-center gap-2 px-6 pt-2 pb-6 text-center">
@@ -184,7 +209,12 @@ export function LevelUpSheet({ level: lv }: { level: number }) {
Lv.{lv} {name}
</b>
{opened.length > 0 && <p className="m-0 text-[15px] font-bold text-(--ink2)">새로 열렸어요: {opened.join(', ')}</p>}
<button type="button" onClick={() => open({ type: 'level' })} className="mt-3 w-full cursor-pointer rounded-full bg-(--orange) py-3 text-[15px] font-extrabold text-white">
{unlocks.length > 0 && (
<button type="button" onClick={() => go(`/saju#${unlocks[0].key}`)} className="mt-3 w-full cursor-pointer rounded-full bg-(--orange) py-3 text-[15px] font-extrabold text-white">
{opened[0]} 보러 가기
</button>
)}
<button type="button" onClick={() => open({ type: 'level' })} className={cx('w-full cursor-pointer py-2 text-[14px] font-extrabold', unlocks.length ? 'text-(--ink2)' : 'mt-3 rounded-full bg-(--orange) py-3 text-white')}>
내 레벨 보기
</button>
</div>
+1 -1
View File
@@ -2,7 +2,7 @@ import type { CSSProperties } from 'react'
import { ARTICLE_LABEL } from '@nalssigak/shared/lib'
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert', 'crystal_ball', 'tshirt', 'clapper', 'speech', 'droplet', 'leaf', 'rainbow', 'milky_way', 'shooting_star'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert', 'crystal_ball', 'yin_yang', 'tshirt', 'clapper', 'speech', 'droplet', 'leaf', 'rainbow', 'milky_way', 'shooting_star', 'alarm_clock', 'check_mark_button', 'sparkles', 'warning', 'locked', 'money_bag', 'red_heart', 'briefcase', 'spiral_calendar', 'two_hearts', 'sunrise'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
export function iconSrc(name: string) {
+66
View File
@@ -0,0 +1,66 @@
import { useSyncExternalStore } from 'react'
/** 날씨 사주에 쓰는 태어난 정보. 이 기기에만 저장하고, 계산할 때만 서버에 보낸다(서버는 남기지 않는다) */
export type Birth = { y: number; m: number; d: number; hour: number | null; minute: number | null; place: string; gender: 'M' | 'F' | null }
const KEY = 'nalssigak.b.birth'
/** 태어난 곳: 시각을 그곳 경도로 맞춘다 (시·도청 경도) */
export const BIRTH_PLACES: [string, string, number][] = [
['seoul', '서울', 126.98],
['busan', '부산', 129.08],
['daegu', '대구', 128.6],
['incheon', '인천', 126.71],
['gwangju', '광주', 126.85],
['daejeon', '대전', 127.38],
['ulsan', '울산', 129.31],
['sejong', '세종', 127.29],
['gyeonggi', '경기', 127.01],
['gangwon', '강원', 127.73],
['chungbuk', '충북', 127.49],
['chungnam', '충남', 126.67],
['jeonbuk', '전북', 127.11],
['jeonnam', '전남', 126.46],
['gyeongbuk', '경북', 128.51],
['gyeongnam', '경남', 128.69],
['jeju', '제주', 126.5],
]
export const placeLon = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[2] ?? 127
function read(): Birth | null {
try {
const raw = localStorage.getItem(KEY)
return raw ? (JSON.parse(raw) as Birth) : null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return null
}
}
let birth = read()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
export function setBirth(b: Birth | null) {
birth = b
listeners.forEach((cb) => cb())
try {
if (b) localStorage.setItem(KEY, JSON.stringify(b))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[saju] 기기에 저장하지 못함', e)
}
}
export const useBirth = () => useSyncExternalStore(subscribe, () => birth)
/** 있는 날짜이고 1900-01-01 ~ 오늘 사이인지 */
export function validBirth(y: number, m: number, d: number) {
const at = new Date(Date.UTC(y, m - 1, d))
const ok = at.getUTCFullYear() === y && at.getUTCMonth() === m - 1 && at.getUTCDate() === d
return ok && y >= 1900 && at.getTime() <= Date.now()
}
+1 -2
View File
@@ -13,7 +13,7 @@ export type SheetState =
| { type: 'share'; share: SharePayload }
| CommentsState
| { type: 'seasonWeek' }
| { type: 'login'; then?: CommentsState }
| { type: 'login'; then?: CommentsState; why?: 'level' }
| { type: 'me' }
| { type: 'region' }
| { type: 'mix'; shared?: MyGak }
@@ -22,7 +22,6 @@ export type SheetState =
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| { type: 'talk'; talk: TalkData }
| { type: 'tarot' }
| { type: 'ootd' }
| { type: 'level' }
| { type: 'levelUp'; level: number }
| { type: 'gameHelp' }
+6 -63
View File
@@ -1,47 +1,16 @@
import { useState, type ReactNode } from 'react'
import { type ReactNode } from 'react'
import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { getPostOptions, latestCardOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { kst } from '@nalssigak/shared/lib'
import { track } from '../lib/analytics'
import { HIDDEN } from './features'
import { useFoliage } from './foliage'
import { useTarotBadge } from './fortune'
import { PostCard, PostCardSkel } from './Post'
import { useRegion } from './regionContext'
import { sajuSeenToday } from './SajuPage'
import { useSheet } from './sheetContext'
import { Ic, Rail } from './ui'
/** 오늘 탭 '내 각' 줄 자리 (아이콘에서 거기로 내려간다) */
export const MY_GAK_ID = 'my-gak'
const OOTD_SEEN = 'nalssigak.b.ootdSeen'
function readSeen() {
try {
return Number(localStorage.getItem(OOTD_SEEN)) || null
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 매번 새로 보는 것으로
return null
}
}
function markSeen(postId: number) {
try {
localStorage.setItem(OOTD_SEEN, String(postId))
} catch (e) {
console.warn('[ootd] 본 코디를 저장하지 못함', e)
}
}
function isToday(iso?: string | null) {
if (!iso) return false
const a = kst(iso)
const b = kst(new Date())
return a.y === b.y && a.mo === b.mo && a.d === b.d
}
const useLatestOotd = () => useQuery({ ...latestCardOptions({ query: { template: 'ootd' } }), staleTime: 10 * 60_000 })
type Item = { key: string; label: string; icon: string; badge?: ReactNode; to?: string; onClick?: () => void }
const Dot = () => <span className="absolute -top-0.5 -right-0.5 size-[11px] rounded-full border-2 border-white bg-[#ff4d4f]" />
@@ -50,10 +19,7 @@ const Dot = () => <span className="absolute -top-0.5 -right-0.5 size-[11px] roun
export function TodayIcons() {
const { open } = useSheet()
const tarot = useTarotBadge()
const ootd = useLatestOotd().data
const [seen, setSeen] = useState(readSeen)
const { inSeason } = useFoliage()
const newOotd = !!ootd?.post_id && isToday(ootd.published_at) && seen !== ootd.post_id
const items: Item[] = [
{
@@ -67,24 +33,13 @@ export function TodayIcons() {
),
onClick: () => open({ type: 'tarot' }),
},
{
key: 'ootd',
label: '오늘 코디',
icon: 'tshirt',
badge: newOotd ? <Dot /> : null,
onClick: () => {
if (ootd?.post_id) {
markSeen(ootd.post_id)
setSeen(ootd.post_id)
}
open({ type: 'ootd' })
},
},
{ key: 'saju', label: '날씨 사주', icon: 'yin_yang', badge: sajuSeenToday() ? null : <Dot />, to: '/saju' },
{ key: 'game', label: '날씨 게임', icon: 'game', to: '/game' },
...(inSeason ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' }] : []),
{ key: 'shorts', label: '쇼츠', icon: 'clapper', to: '/shorts' },
{ key: 'myGak', label: '내 각', icon: 'rabbit', onClick: () => document.getElementById(MY_GAK_ID)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) },
{ key: 'talk', label: '동네 이야기', icon: 'speech', to: '/talk' },
]
].filter((it) => !HIDDEN.has(it.key))
const tile = (it: Item) => (
<>
@@ -122,15 +77,3 @@ export function TodayIcons() {
)
}
/** 오늘 코디 창: 오늘 피드에 올린 코디 카드 (오늘 것이 없으면 안내) */
export function OotdSheet() {
const { region } = useRegion()
const latest = useLatestOotd()
const postId = latest.data?.post_id
const today = isToday(latest.data?.published_at)
const post = useQuery({ ...getPostOptions({ path: { post_id: postId ?? 0 }, query: { region: region.code } }), enabled: !!postId && today })
if (latest.isPending || (postId && today && post.isPending)) return <PostCardSkel />
if (!postId || !today || !post.data?.post) return <p className="m-0 px-4 py-10 text-center text-[14px] font-semibold text-(--ink2)">아직 오늘 코디가 없어요</p>
return <PostCard post={post.data.post} />
}