Files
o2o-weather/frontend/src/b/level.tsx
T
minaChoi 41b09664eb fix: 날씨 사주 문구·해석 검수 반영, 생년월일 계정 저장, 입력 폼 다시 짜기
- 문구: 십성·이달·올해 제목을 자연스러운 말로('버티면 크는 날' → '책임이 무거운 날' 등), 근거 줄은 쉬운 말 + 괄호 용어, 숫자 대신 ↑↓
- 해석: 일간(나)과 일지(연인 자리) 구분, 조심할 것·좋은 흐름은 무게로 고르고 같은 자리에 둘 다 있으면 좋은 쪽을 뺌, 군겁쟁재는 일간 빼고 비겁 3개 이상 + 재성 있을 때만
- 궁합 점수를 두 방향 평균으로(누구를 먼저 넣어도 같음), 날씨 보완은 축마다 실제 비교, 같이 나가기 좋은 날은 비·눈 없고 둘 다 60점 이상일 때만
- 연애운: 연인 자리가 부딪히는 날은 좋은 날에서 빼고 눈 오는 날 문구 구분, 금전·일 날짜는 그날 점수로 고름
- 외출 시간은 체감 5~30°인 때에서만, 예보 없는 날 점수 체계 통일, 남은 달 중 잘 맞는 달
- 로그인하면 생년월일·시각·지역·성별을 계정에 저장 (GET·PUT·DELETE /v1/saju/birth), 내 정보에 '내 생년월일' 줄
- 입력 폼: 시각을 시·분 선택 칸으로, 칸 넘침 없게, 오류 문구 구체적으로, 취소·다시 시도, 성별 바꾸기
- 레벨업하면 사주 결과를 다시 받아 새로 열린 칸이 바로 보임, 레벨 창 문구 정리
2026-10-28 17:13:41 +09:00

232 lines
11 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 { 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' }
// 받침 있으면 a, 없으면 b: josa('연애운', '이', '가') → '연애운이'
const josa = (w: string, a: string, b: string) => {
const c = w.charCodeAt(w.length - 1) - 0xac00
return w + (c >= 0 && c < 11172 && c % 28 === 0 ? b : a)
}
// 창이 쌓아 둔 방문 기록을 닫으며 되돌리므로, 되돌린 뒤(popstate)에 이동해야 새 주소가 안 지워진다
export 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]
const SEEN_KEY = 'nalssigak.b.levelSeen'
/** 서버 응답에서 기본값이 있는 칸은 생략될 수 있어 채워 둔다 */
export type Level = ResLevel & { points: number; level: number; floor: number; streak: number }
const toLevel = (d: ResLevel): Level | undefined => (d.result?.success ? { ...d, points: d.points ?? 0, level: d.level ?? 1, floor: d.floor ?? 0, streak: d.streak ?? 0 } : undefined)
/** 내 레벨 (로그인했을 때만). 각을 주는 일은 모두 mutation 이라 끝날 때마다 다시 받는다(main.tsx) */
export function useLevel() {
const { loggedIn } = useAuth()
return useQuery({ ...myLevelOptions(), enabled: loggedIn, staleTime: 60_000, select: toLevel })
}
/** 다음 레벨까지 진행률 0~1 */
export function progress(l: Level) {
if (l.next_points == null) return 1
return Math.min(1, (l.points - l.floor) / (l.next_points - l.floor))
}
/** 다음 레벨에서 열리는 것 이름 */
export const nextUnlock = (l: Level) => (l.unlocks ?? []).filter((u) => u.level === l.level + 1).map((u) => u.name)
/** 로그인한 사람이 앱을 열면 하루 한 번 출석 각. 레벨이 오르면 축하 창을 띄운다 (레이아웃에 한 번 둔다) */
export function LevelWatcher() {
const { loggedIn, me } = useAuth()
const { open } = useSheet()
const queryClient = useQueryClient()
const level = useLevel().data
const { mutate } = useMutation({ ...attendMutation() })
const attended = useRef<string | null>(null)
useEffect(() => {
if (!loggedIn || !me || attended.current === me.login_id) return
attended.current = me.login_id
mutate({}, { onSuccess: (res) => res.result?.success && queryClient.setQueryData(myLevelQueryKey(), res) })
}, [loggedIn, me, mutate, queryClient])
useEffect(() => {
if (!level || !me) return
const key = `${SEEN_KEY}.${me.login_id}`
let seen: number | null = null
try {
seen = Number(localStorage.getItem(key)) || null
localStorage.setItem(key, String(level.level))
} catch (e) {
console.warn('[level] 본 레벨을 저장하지 못함', e)
}
// 처음 보는 기기에선 축하하지 않는다 (예전 레벨을 모름)
if (seen != null && level.level > seen) open({ type: 'levelUp', level: level.level })
}, [level, me, open])
return null
}
/** 공유를 마치면 하루 한 번 각 (로그인했을 때만) */
export function useShareReward() {
const { loggedIn } = useAuth()
const { mutate } = useMutation({ ...sharedMutation() })
return () => {
if (loggedIn) mutate({})
}
}
/** 헤더 아바타 옆 작은 레벨 표시 */
export function LevelBadge() {
const level = useLevel().data
if (!level) return null
return <span className="pointer-events-none absolute -right-1.5 -bottom-1.5 rounded-full bg-(--ink) px-1.5 text-[9.5px] leading-4 font-extrabold text-white ring-2 ring-white">Lv.{level.level}</span>
}
function Bar({ value }: { value: number }) {
return (
<span className="block h-2 overflow-hidden rounded-full bg-[#eef1f6]">
<span className="block h-full rounded-full bg-[linear-gradient(90deg,#ffb27a,var(--orange))]" style={{ width: `${Math.round(value * 100)}%` }} />
</span>
)
}
/** 내 정보 위쪽: 레벨·모은 각·다음 레벨에서 열리는 것. link 가 있으면 '각 모으는 법'으로 내 레벨 창을 연다 */
export function LevelCard({ link = true }: { link?: boolean }) {
const level = useLevel().data
const { open } = useSheet()
if (!level) return null
const unlock = nextUnlock(level)
return (
<section aria-label="내 레벨" className="rounded-2xl bg-[#fff6ef] px-3.5 py-3">
<div className="flex items-center gap-2">
<Ic name={levelIcon(level.level)} className="size-7" />
<b className="font-jua text-[16px] font-normal">
Lv.{level.level} {level.name}
</b>
<b className="ml-auto font-bagel text-[15px] font-normal">{level.points}각</b>
</div>
<div className="mt-2">
<Bar value={progress(level)} />
</div>
<div className="mt-1.5 flex items-center justify-between gap-2 text-xs font-bold text-(--ink2)">
<span>
{level.next_points == null
? '가장 높은 레벨이에요'
: unlock.length > 0
? `${level.next_points - level.points}각 더 모으면 ${josa(unlock.join(', '), '이', '가')} 열려요`
: `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}`}
</span>
{link && (
<button type="button" onClick={() => open({ type: 'level' })} className="shrink-0 cursor-pointer text-(--orange)">
각 모으는 법 ›
</button>
)}
</div>
</section>
)
}
/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */
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 (
<div className="flex flex-col gap-4 px-4 pb-4">
<LevelCard link={false} />
<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 ?? []).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}
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)">
{done ? `오늘 ${a.earned}각 받음` : a.earned > 0 ? `${a.earned}/${a.cap}각` : `+${a.points}각`}
</span>
{to && !done && <span className="text-(--ink3)">›</span>}
</li>
)
})}
</ul>
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">{level.streak > 0 ? `${level.streak}일째 연속 출석 중 · 7일 연속이면 +50각` : '7일 연속 출석하면 +50각을 더 받아요'}</p>
</section>
<section>
<h4 className="m-0 mb-2 text-sm font-extrabold">레벨이 오르면 열려요</h4>
<ol className="m-0 flex list-none flex-col gap-1.5 p-0">
{(level.levels ?? []).map(({ level: lv, name, points }) => {
const reached = level.level >= lv
return (
<li key={lv} className={cx('flex items-center gap-2.5 rounded-xl px-2.5 py-2', lv === level.level ? 'bg-[#fff6ef]' : '')}>
<Ic name={levelIcon(lv)} className={cx('size-7', !reached && 'opacity-40 grayscale')} />
<span className="min-w-0 flex-1">
<b className="block text-[13.5px] font-extrabold">
Lv.{lv} {name} <span className="font-semibold text-(--ink3)">· {points}각</span>
</b>
<span className="block text-xs font-semibold text-(--ink2)">{lv === 1 ? '날씨각의 기본 기능 모두' : (steps[lv] ?? []).join(', ')}</span>
</span>
</li>
)
})}
</ol>
</section>
</div>
)
}
/** 레벨이 오른 순간 */
export function LevelUpSheet({ level: lv }: { level: number }) {
const level = useLevel().data
const { open } = useSheet()
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">
<Ic name={levelIcon(lv)} className="size-24" />
<b className="font-jua text-[28px] font-normal">
Lv.{lv} {name}
</b>
{opened.length > 0 && <p className="m-0 text-[15px] font-bold text-(--ink2)">이제 {josa(opened.join(', '), '을', '를')} 볼 수 있어요</p>}
{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>
)
}