diff --git a/docs/이벤트_추적.md b/docs/이벤트_추적.md index efa5039..141b4c0 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`(`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`)으로 잡힌다. - 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다. ## GA4 설정 diff --git a/mobile/src/app/(tabs)/week.tsx b/mobile/src/app/(tabs)/week.tsx index 1287cf3..b05057b 100644 --- a/mobile/src/app/(tabs)/week.tsx +++ b/mobile/src/app/(tabs)/week.tsx @@ -9,7 +9,7 @@ import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/w import { DaysSkel, EventsSkel, PickSkel, PlacesSkel, RankSkel } from '@/components/week/skels'; import { Chips, Rail, Sec, Skel, StateBox } from '@/components/ui'; import { useRegion } from '@/lib/region'; -import { shareView } from '@/lib/share-image'; +import { useShare } from '@/lib/share-image'; import { SITE_URL } from '@/lib/site'; // 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다 @@ -46,6 +46,7 @@ export default function WeekScreen() { const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready'; const refresh = () => Promise.all([week.refetch(), events.refetch(), ranking.refetch(), sel ? places.refetch() : null]); + const shareView = useShare(); const pickShot = useRef(null); // 고른 날 추천 카드를 이미지로 const sendPlan = () => { diff --git a/mobile/src/app/_layout.tsx b/mobile/src/app/_layout.tsx index 9ba94f4..444dbc4 100644 --- a/mobile/src/app/_layout.tsx +++ b/mobile/src/app/_layout.tsx @@ -14,6 +14,7 @@ import { SkyBg } from '@/components/sky-bg'; import { FirstLoad } from '@/components/first-load'; import { SheetProvider } from '@/components/sheets'; import { AuthProvider } from '@/lib/auth'; +import { LevelWatcher } from '@/lib/level'; import { queryClient } from '@/lib/query-client'; import { RegionProvider } from '@/lib/region'; import { SkyProvider, useSky } from '@/lib/sky'; @@ -47,6 +48,7 @@ export default function RootLayout() { + diff --git a/mobile/src/components/post/post-card.tsx b/mobile/src/components/post/post-card.tsx index b7f68b6..5edc37f 100644 --- a/mobile/src/components/post/post-card.tsx +++ b/mobile/src/components/post/post-card.tsx @@ -15,7 +15,7 @@ import { slideBg, SlideView, type Slide } from '@/components/post/slides'; import { Ic, Skel } from '@/components/ui'; import { track } from '@/lib/analytics'; import { useSheet } from '@/lib/sheet'; -import { shareView } from '@/lib/share-image'; +import { useShare } from '@/lib/share-image'; import { SITE_URL } from '@/lib/site'; const ACCOUNTS: Partial> = { @@ -133,6 +133,7 @@ function FullCard({ post }: PostProps) { const comments = () => open({ type: 'comments', postId: post.post_id }); const shot = useRef(null); // 지금 보고 있는 슬라이드를 이미지로 + const shareView = useShare(); const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` }); useEffect(() => { diff --git a/mobile/src/components/post/post-frame.tsx b/mobile/src/components/post/post-frame.tsx index 1fc8165..a264f84 100644 --- a/mobile/src/components/post/post-frame.tsx +++ b/mobile/src/components/post/post-frame.tsx @@ -10,7 +10,7 @@ import { Text } from '@/components/text'; import { Ic } from '@/components/ui'; import { usePinnedLike } from '@/lib/pinned-like'; import { useSheet } from '@/lib/sheet'; -import { shareView } from '@/lib/share-image'; +import { useShare } from '@/lib/share-image'; import { SITE_URL } from '@/lib/site'; type Props = { title: string; account: string; avatar: string; caption?: string; more?: ReactNode; pinned?: { key: PinnedKey; post?: PostReaction | null }; children: ReactNode }; @@ -22,6 +22,7 @@ export function PostFrame({ title, account, avatar, caption, more, pinned, child const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post); const postId = pinned?.post?.post_id; const shot = useRef(null); + const shareView = useShare(); const share = () => void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` }); return ( diff --git a/mobile/src/components/sheets/index.tsx b/mobile/src/components/sheets/index.tsx index ff547ab..450738d 100644 --- a/mobile/src/components/sheets/index.tsx +++ b/mobile/src/components/sheets/index.tsx @@ -13,6 +13,7 @@ import { CommentsSheet } from './comments'; import { GakSheet } from './gak'; import { LoginSheet } from './login'; import { MeSheet } from './me'; +import { LevelSheet, LevelUpSheet } from './level'; import { RegionSheet } from './region'; import { WeatherWhySheet } from './weather-why'; @@ -36,7 +37,7 @@ export function SheetProvider({ children }: { children: ReactNode }) { ); } -const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', weatherWhy: '날씨 점수는 이렇게 나와요' } as const; +const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', weatherWhy: '날씨 점수는 이렇게 나와요', level: '내 레벨', levelUp: '레벨이 올랐어요' } as const; /** 판만 아래에서 올라온다 (웹 b-sheet: 0.26초, 40px 아래·흐릿하게에서) */ function Rise({ children }: { children: ReactNode }) { @@ -90,10 +91,12 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () => {state.type === 'article' && } {state.type === 'seasonWeek' && } {state.type === 'comments' && } - {state.type === 'login' && open(then) : onClose} />} + {state.type === 'login' && open(then) : onClose} why={state.why} />} {state.type === 'me' && } {state.type === 'region' && } {state.type === 'weatherWhy' && } + {state.type === 'level' && } + {state.type === 'levelUp' && } )} diff --git a/mobile/src/components/sheets/level.tsx b/mobile/src/components/sheets/level.tsx new file mode 100644 index 0000000..f49241c --- /dev/null +++ b/mobile/src/components/sheets/level.tsx @@ -0,0 +1,138 @@ +import { LinearGradient } from 'expo-linear-gradient'; +import { Pressable, View } from 'react-native'; + +import { Text } from '@/components/text'; +import { Ic } from '@/components/ui'; +import { HIDDEN, josa, levelIcon, nextUnlock, progress, useCloseAndGo, useLevel } from '@/lib/level'; +import { useSheet } from '@/lib/sheet'; + +import { Body, useSoft } from './parts'; + +// 각을 주는 일 → 그 일을 하러 가는 곳, 숨긴 기능에 딸린 일 (서버 ACTIONS 키, 웹 level.tsx) +const ACTION_TO: Record = { saju: '/saju', react: '/', talk: '/talk' }; +const ACTION_FEATURE: Record = { tarot: 'tarot', checkin: 'tarot' }; + +function Bar({ value }: { value: number }) { + const s = useSoft(); + return ( + + + + ); +} + +/** 내 정보 위쪽: 레벨·모은 각·다음 레벨에서 열리는 것. link 가 있으면 '각 모으는 법'으로 내 레벨 창을 연다 */ +export function LevelCard({ link = true }: { link?: boolean }) { + const level = useLevel().data; + const { open } = useSheet(); + const s = useSoft(); + if (!level) return null; + const unlock = nextUnlock(level); + return ( + + + + + Lv.{level.level} {level.name} + + {level.points}각 + + + + + + + {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}`} + + {link && ( + open({ type: 'level' })} hitSlop={8} accessibilityRole="button"> + 각 모으는 법 › + + )} + + + ); +} + +/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */ +export function LevelSheet() { + const level = useLevel().data; + const go = useCloseAndGo(); + const s = useSoft(); + if (!level) return null; + const steps = (level.unlocks ?? []).reduce>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {}); + const actions = (level.today ?? []).filter((a) => !HIDDEN.has(ACTION_FEATURE[a.action] ?? a.action)); + return ( + + + + 오늘 받을 수 있는 각 + + {actions.map((a, i) => { + const done = a.earned >= a.cap; + const to = ACTION_TO[a.action]; + return ( + to && go(to)} className={`flex-row items-center gap-2.5 px-3.5 py-2.5 ${i < actions.length - 1 ? 'border-b border-line' : ''}`}> + {done && ✓} + {a.name} + {done ? `오늘 ${a.earned}각 받음` : a.earned > 0 ? `${a.earned}/${a.cap}각` : `+${a.points}각`} + {!!to && !done && ›} + + ); + })} + + {level.streak > 0 ? `${level.streak}일째 연속 출석 중 · 7일 연속이면 +50각` : '7일 연속 출석하면 +50각을 더 받아요'} + + + 레벨이 오르면 열려요 + + {(level.levels ?? []).map(({ level: lv, name, points }) => { + const reached = level.level >= lv; + return ( + + + + + Lv.{lv} {name} · {points}각 + + {lv === 1 ? '날씨각의 기본 기능 모두' : (steps[lv] ?? []).join(', ')} + + + ); + })} + + + + ); +} + +/** 레벨이 오른 순간 */ +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 ( + + + + Lv.{lv} {name} + + {opened.length > 0 && 이제 {josa(opened.join(', '), '을', '를')} 볼 수 있어요} + {unlocks.length > 0 && ( + go(`/saju?open=${unlocks[0].key}`)} className="mt-3 w-full rounded-full bg-orange py-3"> + {opened[0]} 보러 가기 + + )} + open({ type: 'level' })} className={`w-full py-2 ${unlocks.length ? '' : 'mt-3 rounded-full bg-orange py-3'}`}> + 내 레벨 보기 + + + ); +} diff --git a/mobile/src/components/sheets/login.tsx b/mobile/src/components/sheets/login.tsx index 4353a86..7b84cce 100644 --- a/mobile/src/components/sheets/login.tsx +++ b/mobile/src/components/sheets/login.tsx @@ -11,7 +11,7 @@ import { GoogleButton } from './google'; import { MeSheet } from './me'; import { Body, ErrorLine } from './parts'; -export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) { +export function LoginSheet({ onDone, onLoggedIn, why }: { onDone: () => void; onLoggedIn: () => void; why?: 'level' }) { const { me } = useAuth(); const [error, setError] = useState(''); @@ -30,7 +30,7 @@ export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLogge return ( - 글쓰기는 로그인한 뒤에 할 수 있어요. + {why === 'level' ? '로그인하면 출석·사주·좋아요로 각이 쌓여 레벨이 올라요.' : '글쓰기는 로그인한 뒤에 할 수 있어요.'} { setError(''); diff --git a/mobile/src/components/sheets/me.tsx b/mobile/src/components/sheets/me.tsx index 1755504..bdb6af4 100644 --- a/mobile/src/components/sheets/me.tsx +++ b/mobile/src/components/sheets/me.tsx @@ -1,5 +1,6 @@ import { clearTokens } from '@nalssigak/shared/api/auth'; import { listBlockedOptions, listBlockedQueryKey, meQueryKey, unblockMutation, updateMeMutation, withdrawMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import { AuthProvider } from '@nalssigak/shared/api/client/types.gen'; import { AVATAR_COLORS, CHARACTERS, MOODS } from '@nalssigak/shared/lib'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useState } from 'react'; @@ -10,6 +11,7 @@ import { Avatar, Ic } from '@/components/ui'; import { useAuth } from '@/lib/auth'; import { isCommentList } from './comments'; +import { LevelCard } from './level'; import { Body, Field, useSoft } from './parts'; /** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */ @@ -132,8 +134,9 @@ export function MeSheet({ onDone }: { onDone: () => void }) { - {me.login_id}(으)로 로그인했어요 + {me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`} + 내 캐릭터 diff --git a/mobile/src/components/today/hero.tsx b/mobile/src/components/today/hero.tsx index 4334d2d..dbc8344 100644 --- a/mobile/src/components/today/hero.tsx +++ b/mobile/src/components/today/hero.tsx @@ -19,7 +19,7 @@ import { Ic, Skel } from '@/components/ui'; import { track } from '@/lib/analytics'; import { usePinnedLike } from '@/lib/pinned-like'; import { useRegion } from '@/lib/region'; -import { shareView } from '@/lib/share-image'; +import { useShare } from '@/lib/share-image'; import { useSheet } from '@/lib/sheet'; import { SITE_URL } from '@/lib/site'; import { useSky } from '@/lib/sky'; @@ -198,6 +198,7 @@ export function Hero({ hero, post, today, ranked, feedLoad, todayLoad }: Props) if (v !== tmr) track('hero_day_switch', { day: v ? 'tomorrow' : 'today' }); setTmr(v); }; + const shareView = useShare(); const share = () => { const title = `${region.name} ${tmr ? '내일' : '오늘'} 날씨`; void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` }); diff --git a/mobile/src/components/top-bar.tsx b/mobile/src/components/top-bar.tsx index 44ca30e..a7e7a89 100644 --- a/mobile/src/components/top-bar.tsx +++ b/mobile/src/components/top-bar.tsx @@ -11,6 +11,7 @@ import { useCSSVariable } from 'uniwind'; import { PinIcon } from '@/components/svg'; import { Avatar, Ic, Skel } from '@/components/ui'; import { useAuth } from '@/lib/auth'; +import { useLevel } from '@/lib/level'; import { useRegion } from '@/lib/region'; import { useSheet } from '@/lib/sheet'; import { useSky } from '@/lib/sky'; @@ -35,6 +36,17 @@ function SeasonChip() { ); } +/** 아바타 옆 작은 레벨 표시 */ +function LevelBadge() { + const level = useLevel().data; + if (!level) return null; + return ( + + Lv.{level.level} + + ); +} + /** 오른쪽 끝: 내 정보(아바타) 또는 로그인 버튼 */ function Account() { const { open } = useSheet(); @@ -44,6 +56,7 @@ function Account() { return ( open({ type: 'me' })} accessibilityLabel={`내 정보, ${me.nickname}`} className="shrink-0 rounded-full" style={{ boxShadow: '0 6px 12px rgb(40 48 74 / 0.12)' }}> + ); return ( diff --git a/mobile/src/lib/icons.ts b/mobile/src/lib/icons.ts index 7a9443b..b8c7b0f 100644 --- a/mobile/src/lib/icons.ts +++ b/mobile/src/lib/icons.ts @@ -1,4 +1,4 @@ -// frontend/public 의 아이콘을 그대로 쓴다. Metro 는 정적 require 만 묶을 수 있어 이름마다 적는다 +// frontend/public 의 아이콘을 그대로 쓴다 (공용 public/icons, 웹 전용 public/b/icons). Metro 는 정적 require 만 묶을 수 있어 이름마다 적는다 export const ICONS: Record = { apple: require('../../../frontend/public/icons/apple.png'), baseball: require('../../../frontend/public/icons/baseball.png'), @@ -6,6 +6,7 @@ export const ICONS: Record = { bike: require('../../../frontend/public/icons/bike.png'), bingsu: require('../../../frontend/public/icons/bingsu.png'), blanket: require('../../../frontend/public/icons/blanket.png'), + boiler: require('../../../frontend/public/icons/boiler.png'), bronze: require('../../../frontend/public/icons/bronze.png'), bungeoppang: require('../../../frontend/public/icons/bungeoppang.png'), camping: require('../../../frontend/public/icons/camping.png'), @@ -14,17 +15,24 @@ export const ICONS: Record = { chimaek: require('../../../frontend/public/icons/chimaek.png'), cloud: require('../../../frontend/public/icons/cloud.png'), coldwind: require('../../../frontend/public/icons/coldwind.png'), + date: require('../../../frontend/public/icons/date.png'), delivery: require('../../../frontend/public/icons/delivery.png'), dog: require('../../../frontend/public/icons/dog.png'), drive: require('../../../frontend/public/icons/drive.png'), fallen_leaf: require('../../../frontend/public/icons/fallen_leaf.png'), fishing: require('../../../frontend/public/icons/fishing.png'), flower: require('../../../frontend/public/icons/flower.png'), + frizz: require('../../../frontend/public/icons/frizz.png'), + game: require('../../../frontend/public/icons/game.png'), garden: require('../../../frontend/public/icons/garden.png'), + gift: require('../../../frontend/public/icons/gift.png'), + ginkgo: require('../../../frontend/public/icons/ginkgo.png'), glasses: require('../../../frontend/public/icons/glasses.png'), gold: require('../../../frontend/public/icons/gold.png'), golf: require('../../../frontend/public/icons/golf.png'), + hangang: require('../../../frontend/public/icons/hangang.png'), hiking: require('../../../frontend/public/icons/hiking.png'), + hyodo: require('../../../frontend/public/icons/hyodo.png'), iced_hot: require('../../../frontend/public/icons/iced_hot.png'), indoordry: require('../../../frontend/public/icons/indoordry.png'), jipkok: require('../../../frontend/public/icons/jipkok.png'), @@ -38,10 +46,12 @@ export const ICONS: Record = { maple: require('../../../frontend/public/icons/maple.png'), mask: require('../../../frontend/public/icons/mask.png'), moon: require('../../../frontend/public/icons/moon.png'), + mosquito: require('../../../frontend/public/icons/mosquito.png'), muggy: require('../../../frontend/public/icons/muggy.png'), naengmyeon: require('../../../frontend/public/icons/naengmyeon.png'), netflix: require('../../../frontend/public/icons/netflix.png'), pajeon: require('../../../frontend/public/icons/pajeon.png'), + party: require('../../../frontend/public/icons/party.png'), peanut: require('../../../frontend/public/icons/peanut.png'), photo: require('../../../frontend/public/icons/photo.png'), picnic: require('../../../frontend/public/icons/picnic.png'), @@ -49,29 +59,84 @@ export const ICONS: Record = { rain: require('../../../frontend/public/icons/rain.png'), riverwind: require('../../../frontend/public/icons/riverwind.png'), running: require('../../../frontend/public/icons/running.png'), + selfie: require('../../../frontend/public/icons/selfie.png'), + sentimental: require('../../../frontend/public/icons/sentimental.png'), silver: require('../../../frontend/public/icons/silver.png'), singing_rain: require('../../../frontend/public/icons/singing_rain.png'), snow: require('../../../frontend/public/icons/snow.png'), stars: require('../../../frontend/public/icons/stars.png'), study: require('../../../frontend/public/icons/study.png'), - sun_cloud: require('../../../frontend/public/icons/sun_cloud.png'), sun: require('../../../frontend/public/icons/sun.png'), + sun_cloud: require('../../../frontend/public/icons/sun_cloud.png'), + sunscreen: require('../../../frontend/public/icons/sunscreen.png'), sunset: require('../../../frontend/public/icons/sunset.png'), sweet_potato: require('../../../frontend/public/icons/sweet_potato.png'), tangerine: require('../../../frontend/public/icons/tangerine.png'), taxi: require('../../../frontend/public/icons/taxi.png'), + tennis: require('../../../frontend/public/icons/tennis.png'), + thanks: require('../../../frontend/public/icons/thanks.png'), + themepark: require('../../../frontend/public/icons/themepark.png'), trot: require('../../../frontend/public/icons/trot.png'), umbrella: require('../../../frontend/public/icons/umbrella.png'), vent: require('../../../frontend/public/icons/vent.png'), walk: require('../../../frontend/public/icons/walk.png'), waterplay: require('../../../frontend/public/icons/waterplay.png'), yajang: require('../../../frontend/public/icons/yajang.png'), + alarm_clock: require('../../../frontend/public/b/icons/alarm_clock.png'), + bat: require('../../../frontend/public/b/icons/bat.png'), + briefcase: require('../../../frontend/public/b/icons/briefcase.png'), bulb: require('../../../frontend/public/b/icons/bulb.png'), calendar: require('../../../frontend/public/b/icons/calendar.png'), + candy: require('../../../frontend/public/b/icons/candy.png'), + check_mark_button: require('../../../frontend/public/b/icons/check_mark_button.png'), + christmas_tree: require('../../../frontend/public/b/icons/christmas_tree.png'), + clapper: require('../../../frontend/public/b/icons/clapper.png'), concert: require('../../../frontend/public/b/icons/concert.png'), + crystal_ball: require('../../../frontend/public/b/icons/crystal_ball.png'), + dango: require('../../../frontend/public/b/icons/dango.png'), + droplet: require('../../../frontend/public/b/icons/droplet.png'), exhibition: require('../../../frontend/public/b/icons/exhibition.png'), fireworks: require('../../../frontend/public/b/icons/fireworks.png'), + full_moon: require('../../../frontend/public/b/icons/full_moon.png'), + ghost: require('../../../frontend/public/b/icons/ghost.png'), + jack_o_lantern: require('../../../frontend/public/b/icons/jack_o_lantern.png'), + leaf: require('../../../frontend/public/b/icons/leaf.png'), + locked: require('../../../frontend/public/b/icons/locked.png'), + lollipop: require('../../../frontend/public/b/icons/lollipop.png'), + milky_way: require('../../../frontend/public/b/icons/milky_way.png'), + money_bag: require('../../../frontend/public/b/icons/money_bag.png'), + moon_viewing: require('../../../frontend/public/b/icons/moon_viewing.png'), + pear: require('../../../frontend/public/b/icons/pear.png'), + pepero_almond: require('../../../frontend/public/b/icons/pepero_almond.png'), + pepero_basket: require('../../../frontend/public/b/icons/pepero_basket.png'), + pepero_box: require('../../../frontend/public/b/icons/pepero_box.png'), + pepero_bundle: require('../../../frontend/public/b/icons/pepero_bundle.png'), + pepero_choco: require('../../../frontend/public/b/icons/pepero_choco.png'), + pepero_nude: require('../../../frontend/public/b/icons/pepero_nude.png'), + pepero_pair: require('../../../frontend/public/b/icons/pepero_pair.png'), + pepero_strawberry: require('../../../frontend/public/b/icons/pepero_strawberry.png'), popup: require('../../../frontend/public/b/icons/popup.png'), + rainbow: require('../../../frontend/public/b/icons/rainbow.png'), + red_heart: require('../../../frontend/public/b/icons/red_heart.png'), sheaf: require('../../../frontend/public/b/icons/sheaf.png'), + shooting_star: require('../../../frontend/public/b/icons/shooting_star.png'), + skull: require('../../../frontend/public/b/icons/skull.png'), + sparkles: require('../../../frontend/public/b/icons/sparkles.png'), + speech: require('../../../frontend/public/b/icons/speech.png'), + spider: require('../../../frontend/public/b/icons/spider.png'), + spider_web: require('../../../frontend/public/b/icons/spider_web.png'), + spiral_calendar: require('../../../frontend/public/b/icons/spiral_calendar.png'), + sunrise: require('../../../frontend/public/b/icons/sunrise.png'), thermo: require('../../../frontend/public/b/icons/thermo.png'), + tshirt: require('../../../frontend/public/b/icons/tshirt.png'), + two_hearts: require('../../../frontend/public/b/icons/two_hearts.png'), + warning: require('../../../frontend/public/b/icons/warning.png'), + xmas_candy_cane: require('../../../frontend/public/b/icons/xmas_candy_cane.png'), + xmas_gingerbread: require('../../../frontend/public/b/icons/xmas_gingerbread.png'), + xmas_ornament: require('../../../frontend/public/b/icons/xmas_ornament.png'), + xmas_santa: require('../../../frontend/public/b/icons/xmas_santa.png'), + xmas_santa_hat: require('../../../frontend/public/b/icons/xmas_santa_hat.png'), + xmas_stocking: require('../../../frontend/public/b/icons/xmas_stocking.png'), + xmas_wreath: require('../../../frontend/public/b/icons/xmas_wreath.png'), + yin_yang: require('../../../frontend/public/b/icons/yin_yang.png'), }; diff --git a/mobile/src/lib/level.ts b/mobile/src/lib/level.ts new file mode 100644 index 0000000..ccd2ea7 --- /dev/null +++ b/mobile/src/lib/level.ts @@ -0,0 +1,95 @@ +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(['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(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({}); + }; +} diff --git a/mobile/src/lib/query-client.ts b/mobile/src/lib/query-client.ts index de71424..c39006d 100644 --- a/mobile/src/lib/query-client.ts +++ b/mobile/src/lib/query-client.ts @@ -1,4 +1,5 @@ -import { focusManager, keepPreviousData, QueryClient } from '@tanstack/react-query'; +import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import { focusManager, keepPreviousData, MutationCache, QueryClient } from '@tanstack/react-query'; import { AppState, Platform } from 'react-native'; // 앱이 다시 앞으로 오면 '포커스'로 보고, 5분 넘게 묵은 데이터만 다시 받는다 @@ -10,6 +11,8 @@ if (Platform.OS !== 'web') { } // 웹과 같은 기본값: 다시 받는 동안 이전 결과를 그대로 두어 화면이 비지 않게 한다 -export const queryClient = new QueryClient({ +export const queryClient: QueryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, placeholderData: keepPreviousData } }, + // 각을 주는 일(좋아요·댓글·글·공유·사주)은 모두 mutation 이라, 끝나면 내 레벨을 다시 받는다 (웹 main.tsx) + mutationCache: new MutationCache({ onSuccess: () => queryClient.invalidateQueries({ queryKey: myLevelQueryKey() }) }), }); diff --git a/mobile/src/lib/share-image.ts b/mobile/src/lib/share-image.ts index 9de6574..1f8b681 100644 --- a/mobile/src/lib/share-image.ts +++ b/mobile/src/lib/share-image.ts @@ -4,19 +4,32 @@ import { Share, type View } from 'react-native'; import { captureRef } from 'react-native-view-shot'; import { track } from '@/lib/analytics'; +import { useShareReward } from '@/lib/level'; -/** 보이는 화면 조각을 PNG로 찍어 공유. 이미지 공유가 안 되는 곳(웹 등)이면 글로 보낸다 */ -export async function shareView(ref: RefObject, { title, message }: { title: string; message: string }) { +type ShareText = { title: string; message: string }; + +/** 보이는 화면 조각을 PNG로 찍어 공유. 이미지 공유가 안 되는 곳(웹 등)이면 글로 보낸다. 보냈으면 true */ +async function shareView(ref: RefObject, { title, message }: ShareText) { try { if (ref.current && (await Sharing.isAvailableAsync())) { const uri = await captureRef(ref, { format: 'png', quality: 1, result: 'tmpfile' }); await Sharing.shareAsync(uri, { mimeType: 'image/png', UTI: 'public.png', dialogTitle: title }); // 앱은 보이는 카드를 그대로 찍어 보내므로 비율은 'card' track('share', { content_type: 'image', item_id: title, method: 'share_sheet', ratio: 'card' }); - return; + return true; } - await Share.share({ message }); + const res = await Share.share({ message }); + return res.action === Share.sharedAction; } catch (e) { console.warn('공유 실패', e); + return false; } } + +/** 화면 조각 공유. 보내면 하루 한 번 각을 받는다 (로그인했을 때만) */ +export function useShare() { + const reward = useShareReward(); + return async (ref: RefObject, text: ShareText) => { + if (await shareView(ref, text)) reward(); + }; +} diff --git a/mobile/src/lib/sheet.ts b/mobile/src/lib/sheet.ts index 78b32de..ecf884b 100644 --- a/mobile/src/lib/sheet.ts +++ b/mobile/src/lib/sheet.ts @@ -9,10 +9,12 @@ export type SheetState = | { type: 'article'; articleId: number } | CommentsState | { type: 'seasonWeek' } - | { type: 'login'; then?: CommentsState } + | { type: 'login'; then?: CommentsState; why?: 'level' } | { type: 'me' } | { type: 'region' } | { type: 'weatherWhy'; why: WeatherWhyPayload } + | { type: 'level' } + | { type: 'levelUp'; level: number } | null; export type SheetApi = { open: (s: Exclude) => void; close: () => void };