96 lines
4.0 KiB
TypeScript
96 lines
4.0 KiB
TypeScript
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 { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
import { router, type Href } from 'expo-router';
|
|
import * as SecureStore from 'expo-secure-store';
|
|
import { useEffect, useRef } from 'react';
|
|
|
|
import { useAuth } from '@/lib/auth';
|
|
import { useSheet } from '@/lib/sheet';
|
|
|
|
/** 잠시 숨긴 기능 (아이콘 줄·각 모으는 법에서 뺀다, 웹 features.ts 와 같게) */
|
|
export const HIDDEN = new Set<string>(['tarot']);
|
|
|
|
// 받침 있으면 a, 없으면 b: josa('연애운', '이', '가') → '연애운이'
|
|
export 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);
|
|
};
|
|
|
|
// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 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];
|
|
|
|
/** 서버 응답에서 기본값이 있는 칸은 생략될 수 있어 채워 둔다 */
|
|
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 이라 끝날 때마다 다시 받는다(query-client.ts) */
|
|
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 useCloseAndGo() {
|
|
const { close } = useSheet();
|
|
return (to: string) => {
|
|
close();
|
|
router.push(to as Href);
|
|
};
|
|
}
|
|
|
|
const SEEN_KEY = 'nalssigak.levelSeen';
|
|
|
|
/** 로그인한 사람이 앱을 열면 하루 한 번 출석 각. 레벨이 오르면 축하 창을 띄운다 (루트 레이아웃에 한 번 둔다) */
|
|
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;
|
|
// SecureStore 키는 영문·숫자·._- 만 된다
|
|
const key = `${SEEN_KEY}.${me.login_id.replace(/[^\w.-]/g, '_')}`;
|
|
let seen: number | null = null;
|
|
try {
|
|
seen = Number(SecureStore.getItem(key)) || null;
|
|
SecureStore.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({});
|
|
};
|
|
}
|