diff --git a/docs/이벤트_추적.md b/docs/이벤트_추적.md index f3b2bc1..f7d08c7 100644 --- a/docs/이벤트_추적.md +++ b/docs/이벤트_추적.md @@ -78,7 +78,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화 - 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다. - **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다. -- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). +- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). - 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다. ## GA4 설정 diff --git a/mobile/src/app/(tabs)/index.tsx b/mobile/src/app/(tabs)/index.tsx index 5b90df7..5d3099f 100644 --- a/mobile/src/app/(tabs)/index.tsx +++ b/mobile/src/app/(tabs)/index.tsx @@ -3,9 +3,11 @@ import { PostType } from '@nalssigak/shared/api/client/types.gen'; import { kst, loadOf } from '@nalssigak/shared/lib'; import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today'; import { useQuery } from '@tanstack/react-query'; -import { Fragment, useRef, type ReactNode } from 'react'; +import { router, useLocalSearchParams } from 'expo-router'; +import { Fragment, useEffect, useRef, type ReactNode } from 'react'; import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-native'; +import { MyGakRow } from '@/components/my-gak/my-gak'; import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card'; import { Composer, TalkPost } from '@/components/talk/talk'; import { GakCard } from '@/components/today/gak-card'; @@ -13,7 +15,9 @@ import { Hero } from '@/components/today/hero'; import { SeasonBand } from '@/components/today/rails'; import { StateBox } from '@/components/ui'; import { track } from '@/lib/analytics'; +import { fromShare } from '@/lib/my-gak'; import { useRegion } from '@/lib/region'; +import { useSheet } from '@/lib/sheet'; import { useSky } from '@/lib/sky'; import { useTopicTalks } from '@/lib/talk'; @@ -67,6 +71,16 @@ export default function TodayScreen() { const talkFrom = Math.floor(posts.length / TALK_EVERY); const eventNo = new Map(posts.filter((p) => p.post_type === PostType.EVENT).map((p, n) => [p.post_id, n + 1])); const seen = useSeen(); + const { open } = useSheet(); + const { my } = useLocalSearchParams<{ my?: string }>(); + + // 친구가 보낸 내 각 링크(?my=...)로 들어오면 내 동네 기준으로 보여 준다 + useEffect(() => { + if (!my) return; + router.setParams({ my: undefined }); + const g = fromShare(my); + if (g) open({ type: 'mix', shared: g }); + }, [my, open]); const refresh = () => Promise.all([feed.refetch(), today.refetch(), talkList.refetch()]); // 웹처럼 9번째 글 뒤에 계절 이야기 띠를 넣고, 글이 모자라면 맨 뒤에 붙인다 @@ -86,6 +100,7 @@ export default function TodayScreen() { > + {/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */} {stories.some((g) => g.active) ? ( diff --git a/mobile/src/components/my-gak/my-gak.tsx b/mobile/src/components/my-gak/my-gak.tsx new file mode 100644 index 0000000..3ba4603 --- /dev/null +++ b/mobile/src/components/my-gak/my-gak.tsx @@ -0,0 +1,362 @@ +import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'; +import { LinearGradient } from 'expo-linear-gradient'; +import { useRef, useState, type ReactNode } from 'react'; +import { Pressable, ScrollView, TextInput, View } from 'react-native'; + +import { Body, useSoft } from '@/components/sheets/parts'; +import { Text } from '@/components/text'; +import { Ic, Rail, Sec } from '@/components/ui'; +import { gakName, MY_GAK_ICON, shareUrl, SLOT_WORD, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from '@/lib/my-gak'; +import { useRegion } from '@/lib/region'; +import { useShare } from '@/lib/share-image'; +import { useSheet } from '@/lib/sheet'; + +function Score({ s, big }: { s?: MyGakScore; big?: boolean }) { + const v = s?.score; + return {v ?? '–'}; +} + +function Reasons({ s }: { s?: MyGakScore }) { + if (!s?.slot) return 예보를 불러오는 중이에요; + return ( + + {SLOT_WORD[s.slot as Slot]} + {s.reasons?.join(' · ')} + + ); +} + +// 조건 이름. 점수 응답의 factors 와 reasons 는 같은 순서다 +const AXIS_NAME: Record = { temp: '기온', rain: '비', wind: '바람', air: '미세먼지', humidity: '습도' }; +// 조건 점수가 이보다 낮으면 '아쉬운 조건'으로 카드에 칩을 단다 +const SHORT = 70; + +/** 조건마다 이름·점수·실제 값 (실제 값은 근거 문구의 첫 마디: 체감 15°) */ +function conditions(s?: MyGakScore) { + const notes = s?.reasons ?? []; + return Object.entries(s?.factors ?? {}).map(([axis, value], i) => ({ axis, label: AXIS_NAME[axis] ?? axis, value, note: notes[i] ?? '', short: (notes[i] ?? '').split(', ')[0] })); +} + +/** 오늘 탭의 내 각 줄: 카드엔 아이콘·이름·점수·아쉬운 조건만, 누르면 상세 창 */ +export function MyGakRow() { + const { open } = useSheet(); + const { items } = useMyGak(); + const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []; + return ( + <> + + + {items.map((g, i) => { + const s = scores[i]; + const miss = conditions(s) + .filter((c) => c.value < SHORT) + .slice(0, 2); + return ( + open({ type: 'myGak', gak: g })} accessibilityLabel={`${g.name} ${s?.score ?? ''}점 자세히`} className="w-[200px] gap-2 rounded-[22px] border-b-[5px] border-shade bg-card p-3"> + + + + + + {g.name} + {s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'} + + {!!s?.slot && ( + + {miss.length ? ( + miss.map((c) => ( + + {c.short} + + )) + ) : ( + 조건 다 맞아요 + )} + + )} + + ); + })} + open({ type: 'mix' })} accessibilityRole="button" className="w-[120px] items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-line p-3"> + + + 내 각 만들기 + + + + ); +} + +/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기·지우기 */ +export function MyGakSheet({ gak, onDone }: { gak: MyGak; onDone: () => void }) { + const { remove } = useMyGak(); + const s = useMyGakScores([gak.rule]).data?.scores?.[0]; + const soft = useSoft(); + const shareView = useShare(); + const shot = useRef(null); + const [confirm, setConfirm] = useState(false); + const rows = conditions(s); + // 받은 사람이 자기 동네 점수로 볼 수 있게 링크를 같이 보낸다 + const share = () => void shareView(shot, { title: gak.name, message: `${gak.name} ${s?.score ?? ''}점 · 내 동네 점수 보기 ${shareUrl(gak)}` }); + return ( + + + + + + {gak.name} + {s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'} + + + + + {SLOTS.map(([k, word]) => { + const v = s?.slots?.[k]; + return ( + + {word} + {v ?? '–'} + + ); + })} + + + {rows.map((c) => ( + + + {c.label} + + + + {c.value} + + {c.note} + + ))} + + + + + 공유하기 + + {confirm ? ( + <> + { + remove(gak); + onDone(); + }} + className="rounded-2xl bg-[#fdecec] px-4 py-3" + > + 지우기 + + setConfirm(false)} className="rounded-2xl bg-[#eef4fc] px-4 py-3"> + 취소 + + + ) : ( + setConfirm(true)} className="rounded-2xl bg-[#eef4fc] px-4 py-3"> + 지우기 + + )} + + {confirm && 지울까요?} + + ); +} + +function Row({ label, on, onToggle, disabled, children }: { label: string; on: boolean; onToggle: () => void; disabled?: boolean; children: ReactNode }) { + return ( + + + {on && ✓} + {label} + + {on ? {children} : 상관없음} + + ); +} + +/** 숫자: 휴대폰 숫자 자판엔 '-'가 없을 때가 있어 −/+ 버튼으로 바꾼다 */ +function Num({ value, onChange, min, max, step = 1, label, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; step?: number; label: string; disabled?: boolean }) { + const soft = useSoft(); + const set = (v: number) => onChange(Math.min(max, Math.max(min, v))); + return ( + + set(value - step)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-2 py-1.5 disabled:opacity-30"> + − + + {value} + set(value + step)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-2 py-1.5 disabled:opacity-30"> + + + + + ); +} + +function Choice({ value, options, onChange, label, disabled }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string; disabled?: boolean }) { + return ( + + {options.map(([k, word]) => ( + onChange(k)} disabled={disabled} accessibilityRole="radio" accessibilityState={{ checked: value === k }} className={`rounded-full px-3 py-1.5 ${value === k ? 'bg-orange' : 'bg-[#eef4fc]'}`}> + {word} + + ))} + + ); +} + +type Filled = { [K in keyof T]-?: NonNullable }; +const DEFAULT_RULE: Filled = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] }; +type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity'; + +const condsOf = (r: MyGakRule): Record => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity }); + +/** 내 각 아이콘 고르기: 있는 각 아이콘 그대로 */ +function IconPicker({ value, onPick }: { value: string; onPick: (icon: string) => void }) { + const soft = useSoft(); + const icons = [...new Set([MY_GAK_ICON, ...(usePresets().data ?? []).map((p) => p.icon)])]; + return ( + + 아이콘 + + {icons.map((icon) => ( + onPick(icon)} accessibilityRole="button" accessibilityState={{ selected: value === icon }} accessibilityLabel={`아이콘 ${icon}`} className={`size-12 items-center justify-center rounded-2xl ${value === icon ? 'bg-orange' : ''}`} style={value === icon ? undefined : { backgroundColor: soft.soft }}> + + + ))} + + + ); +} + +/** 있는 각을 골라 그 각 조건으로 채운다 */ +function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) { + const soft = useSoft(); + const items = usePresets().data ?? []; + if (!items.length) return null; + return ( + + 있는 각에서 불러오기 + + {items.map((p) => ( + onPick(p)} accessibilityRole="button" accessibilityState={{ selected: picked === p.code }} className={`w-[68px] items-center gap-1 rounded-2xl px-1 py-2 ${picked === p.code ? 'bg-orange' : ''}`} style={picked === p.code ? undefined : { backgroundColor: soft.soft }}> + + + {p.name} + + + ))} + + + ); +} + +/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */ +export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) { + const { region } = useRegion(); + const soft = useSoft(); + const { create, pending, failed } = useMyGak(); + const [name, setName] = useState(shared?.name ?? ''); + const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE); + const [on, setOn] = useState>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false }); + const [picked, setPicked] = useState(null); + const [icon, setIcon] = useState(shared?.icon ?? MY_GAK_ICON); + const lock = !!shared; + const pick = (p: MyGakPreset) => { + setPicked(p.code); + setName(p.name); + setIcon(p.icon); + setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE); + setOn(condsOf(p.rule)); + }; + const set = (k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v })); + const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] })); + const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial) }; + const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1]); + const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0]; + const title = gakName(name) || '이름 없는 각'; + const toggleSlot = (s: Slot) => + set( + 'slots', + vals.slots.includes(s) + ? vals.slots.filter((x) => x !== s) + : SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)), + ); + + return ( + + {shared ? ( + 친구가 보낸 각이에요. {region.name} 기준 점수예요 + ) : ( + <> + + 이름 + + + + )} + 조건 + toggle('temp')} disabled={lock}> + set('temp', [v, vals.temp[1]])} /> + ~ + set('temp', [vals.temp[0], v])} /> + ° 체감 + + toggle('rain')} disabled={lock}> + set('rain', v)} + options={[ + ['dry', '안 와야'], + ['wet', '와야'], + ]} + /> + + toggle('wind_max')} disabled={lock}> + 초속 + set('wind_max', v)} /> + m 이하 + + toggle('air')} disabled={lock}> + set('air', v)} + options={[ + ['good', '좋음만'], + ['normal', '보통까지'], + ]} + /> + + toggle('humidity')} disabled={lock}> + set('humidity', [v, vals.humidity[1]])} /> + ~ + set('humidity', [vals.humidity[0], v])} /> + % + + + 시간대 + {SLOTS.map(([k, word]) => ( + toggleSlot(k)} disabled={lock} accessibilityRole="button" accessibilityState={{ selected: vals.slots.includes(k) }} className={`rounded-full px-3 py-1.5 ${vals.slots.includes(k) ? 'bg-orange' : 'bg-[#eef4fc]'}`}> + {word} + + ))} + + + + + {title} + + + {valid ? : 조건과 시간대를 하나 이상 골라요} + + {failed && 저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요} + create({ name, icon, rule }, onDone)} className="mt-3.5 rounded-2xl bg-orange py-3 disabled:opacity-45"> + {shared ? '내 각으로 가져오기' : '내 각으로 저장'} + + + ); +} diff --git a/mobile/src/components/sheets/index.tsx b/mobile/src/components/sheets/index.tsx index 3240f72..5ccdb37 100644 --- a/mobile/src/components/sheets/index.tsx +++ b/mobile/src/components/sheets/index.tsx @@ -5,15 +5,16 @@ import { Text } from '@/components/text'; import Animated, { Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withTiming } from 'react-native-reanimated'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { MixSheet, MyGakSheet } from '@/components/my-gak/my-gak'; import { track } from '@/lib/analytics'; import { SheetContext, useSheet, type SheetState } from '@/lib/sheet'; import { ArticleSheet, SeasonWeekSheet } from './article'; import { CommentsSheet } from './comments'; import { GakSheet } from './gak'; +import { LevelSheet, LevelUpSheet } from './level'; import { LoginSheet } from './login'; import { MeSheet } from './me'; -import { LevelSheet, LevelUpSheet } from './level'; import { RegionSheet } from './region'; import { WeatherWhySheet } from './weather-why'; @@ -68,7 +69,7 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () => const [articleTitle, setArticleTitle] = useState(''); const then = state?.type === 'login' ? state.then : undefined; - const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]; + const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : state.type === 'myGak' ? '내 각' : TITLES[state.type]; return ( @@ -96,6 +97,8 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () => {state.type === 'region' && } {state.type === 'weatherWhy' && } {state.type === 'level' && } + {state.type === 'mix' && } + {state.type === 'myGak' && } {state.type === 'levelUp' && } diff --git a/mobile/src/lib/my-gak.ts b/mobile/src/lib/my-gak.ts new file mode 100644 index 0000000..8ecee44 --- /dev/null +++ b/mobile/src/lib/my-gak.ts @@ -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; + +/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(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 }; +} diff --git a/mobile/src/lib/sheet.ts b/mobile/src/lib/sheet.ts index 59b9488..41f73cc 100644 --- a/mobile/src/lib/sheet.ts +++ b/mobile/src/lib/sheet.ts @@ -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) => void; close: () => void };