feat: 앱 내 각 — 오늘 피드 내 각 줄, 만들기 창(있는 각 불러오기·아이콘·조건·시간대·미리보기 점수), 상세 창(시간대·조건별 점수, 링크 공유·지우기), 로그인 전 기기에 하나 저장 후 로그인하면 계정으로, ?my= 받은 각 열기 (GA my_gak_save)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
f6884fe9c9
commit
5a88b08a44
6 files changed
+546
-4
No files matched your search
@@ -0,0 +1,159 @@
|
||||
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||
import { scoreMyGak } from '@nalssigak/shared/api/client/sdk.gen';
|
||||
import type { MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
|
||||
import { track } from '@/lib/analytics';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { useRegion } from '@/lib/region';
|
||||
import { useSheet } from '@/lib/sheet';
|
||||
import { SITE_URL } from '@/lib/site';
|
||||
|
||||
const KEY = 'nalssigak.myRule';
|
||||
|
||||
export type Slot = 'morning' | 'day' | 'evening' | 'night';
|
||||
export const SLOTS: [Slot, string][] = [
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['evening', '저녁'],
|
||||
['night', '밤'],
|
||||
];
|
||||
export const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>;
|
||||
|
||||
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) (웹 myGakState.ts) */
|
||||
export type MyGak = { id?: number; name: string; icon?: string | null; rule: MyGakRule };
|
||||
|
||||
/** 아이콘을 안 골랐을 때 */
|
||||
export const MY_GAK_ICON = 'rabbit';
|
||||
|
||||
function readLocal(): MyGak | null {
|
||||
try {
|
||||
const raw = SecureStore.getItem(KEY);
|
||||
return raw ? (JSON.parse(raw) as MyGak) : null;
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 기기에 저장한 각을 읽지 못함', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 창과 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
|
||||
let local: MyGak | null | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
const subscribe = (cb: () => void) => {
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
};
|
||||
const getLocal = () => {
|
||||
if (local === undefined) local = readLocal();
|
||||
return local;
|
||||
};
|
||||
|
||||
function setLocal(g: MyGak | null) {
|
||||
local = g;
|
||||
listeners.forEach((cb) => cb());
|
||||
try {
|
||||
if (g) SecureStore.setItem(KEY, JSON.stringify(g));
|
||||
else void SecureStore.deleteItemAsync(KEY);
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 기기에 저장하지 못함', e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
|
||||
export const gakName = (name: string) => {
|
||||
const n = name.trim().replace(/\s+/g, ' ');
|
||||
return n && !n.endsWith('각') ? `${n}각` : n;
|
||||
};
|
||||
|
||||
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 (웹과 같은 형식) */
|
||||
export function shareUrl(g: MyGak) {
|
||||
const json = JSON.stringify({ n: g.name, i: g.icon ?? undefined, r: g.rule });
|
||||
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)));
|
||||
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`;
|
||||
}
|
||||
|
||||
export function fromShare(code: string): MyGak | null {
|
||||
try {
|
||||
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'));
|
||||
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; i?: unknown; r?: unknown };
|
||||
const icon = typeof v.i === 'string' && /^[a-z_]{1,32}$/.test(v.i) ? v.i : null;
|
||||
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, icon, rule: v.r as MyGakRule } : null;
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 받은 링크를 읽지 못함', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
|
||||
export function useMyGakScores(rules: MyGakRule[]) {
|
||||
const { region } = useRegion();
|
||||
return useQuery({
|
||||
queryKey: ['myGakScore', region.code, rules],
|
||||
enabled: rules.length > 0,
|
||||
staleTime: 5 * 60_000,
|
||||
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
|
||||
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } });
|
||||
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score');
|
||||
return { nowSlot: data.now_slot as Slot | null | undefined, scores: data.scores ?? [] };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */
|
||||
export function usePresets() {
|
||||
return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] });
|
||||
}
|
||||
|
||||
export function useMyGak() {
|
||||
const { loggedIn } = useAuth();
|
||||
const { open } = useSheet();
|
||||
const queryClient = useQueryClient();
|
||||
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn });
|
||||
const saved = useSyncExternalStore(subscribe, getLocal);
|
||||
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() });
|
||||
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh });
|
||||
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh });
|
||||
|
||||
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
|
||||
const { mutate } = add;
|
||||
useEffect(() => {
|
||||
if (!loggedIn || !saved) return;
|
||||
mutate({ body: { name: saved.name, icon: saved.icon, rule: saved.rule } }, { onSuccess: () => setLocal(null) });
|
||||
}, [loggedIn, saved, mutate]);
|
||||
|
||||
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, icon: g.icon, rule: g.rule })) : saved ? [saved] : [];
|
||||
|
||||
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
|
||||
const create = (g: MyGak, onDone?: () => void) => {
|
||||
const item = { name: gakName(g.name), icon: g.icon, rule: g.rule };
|
||||
if (loggedIn) {
|
||||
add.mutate(
|
||||
{ body: item },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success) return;
|
||||
track('my_gak_save', { gak_name: item.name });
|
||||
onDone?.();
|
||||
},
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (saved) {
|
||||
open({ type: 'login' });
|
||||
return;
|
||||
}
|
||||
setLocal(item);
|
||||
track('my_gak_save', { gak_name: item.name });
|
||||
onDone?.();
|
||||
};
|
||||
|
||||
const remove = (g: MyGak) => {
|
||||
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } });
|
||||
setLocal(null);
|
||||
};
|
||||
|
||||
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false };
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createContext, use } from 'react';
|
||||
|
||||
import type { WeatherWhyPayload } from '@/components/sheets/weather-why';
|
||||
import type { MyGak } from '@/lib/my-gak';
|
||||
|
||||
/** 댓글이 달린 곳: 운영 포스트 또는 사람 글 */
|
||||
export type CommentTarget = { postId: number } | { talkId: number };
|
||||
@@ -17,6 +18,8 @@ export type SheetState =
|
||||
| { type: 'weatherWhy'; why: WeatherWhyPayload }
|
||||
| { type: 'level' }
|
||||
| { type: 'levelUp'; level: number }
|
||||
| { type: 'mix'; shared?: MyGak }
|
||||
| { type: 'myGak'; gak: MyGak }
|
||||
| null;
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void };
|
||||
|
||||
Reference in new issue
Block a user