- 각: 출석 10, 오늘 타로 10, 날씨 사주 10, 좋아요·댓글 5씩(하루 10), 동네 이야기 글 20, 저녁 체크인 10, 공유 10, 7일 연속 50. 같은 날 같은 대상은 한 번 (point_log) - 레벨: 모은 총량으로 이슬 0 → 햇살 30 → 산들바람 100 → 무지개 200 → 노을 400 → 은하수 700 → 별똥별 1000. 지금 있는 기능은 잠그지 않음 - API: GET /v1/level/me, POST /v1/level/attend, POST /v1/level/share - 화면: 헤더 아바타 레벨 배지, 내 정보 레벨 카드, 내 레벨 창(오늘 받을 각·레벨별로 열리는 것), 레벨이 오르면 축하 창 - 로그인한 사람만 쌓임 (기기 기록은 조작할 수 있어 받지 않음)
193 lines
8.8 KiB
TypeScript
193 lines
8.8 KiB
TypeScript
import { useEffect, useRef } from 'react'
|
||
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 { useSheet } from './sheetContext'
|
||
import { Ic } from './ui'
|
||
|
||
// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 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 ? `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}` : '가장 높은 레벨이에요'}
|
||
{unlock.length > 0 && <b className="text-(--orange)"> · {unlock.join(', ')}</b>}
|
||
</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
|
||
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 ?? []).map((a) => {
|
||
const done = a.earned >= a.cap
|
||
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">
|
||
<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>
|
||
</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 opened = (level?.unlocks ?? []).filter((u) => u.level === lv).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)">새로 열렸어요: {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">
|
||
내 레벨 보기
|
||
</button>
|
||
</div>
|
||
)
|
||
}
|