This commit is contained in:
skkim committed 2026-11-24 11:28:29 +09:00
commit ceda60bde7
89 files changed
+70 -9214

No files matched your search

+3 -6
View File
@@ -98,12 +98,9 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
## 앱 (안드로이드, `mobile/`)
- **웹뷰 셸 전환(`feat/app-webview-shell`)**: 앱이 날씨각 웹을 웹뷰로 띄우는 껍데기가 되면 아래 앱 이벤트는 쓰지 않고, 웹이 같은 이벤트를 그대로 보내며 `platform: 'android_app'`으로 찍힌다. 앱 안에서 구글 로그인·공유·위치가 실패하면 `app_bridge_error`, 앱을 켜면 `app_launch`(`mode: 'android_app'`)가 나간다. 앱 사용자는 `platform`으로 가른다.
- 앱도 같은 이벤트 이름·값으로 `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`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 오늘 아이콘 줄: `today_icon`(`components/today/icons.tsx`). 사주: `saju_input`(`components/saju/birth-form.tsx`), `saju_view`(`saju/reading.tsx`). 단풍 지도: `foliage_open`(`app/foliage.tsx`), `foliage_spot`(`components/foliage/*`, 화면 `page`·피드 카드 `card`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음).
- 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다.
- 앱은 날씨각 웹을 웹뷰로 띄우는 껍데기라(`mobile/src/components/web-shell.tsx`) 앱에서 따로 보내는 이벤트가 없다. 웹이 같은 이벤트를 그대로 보내고 `platform: 'android_app'`으로 찍힌다. 앱 사용자는 `platform`으로 가른다.
- 앱에서만 나가는 것: 앱을 켜면 `app_launch`(`mode: 'android_app'`), 앱 안에서 구글 로그인·공유·위치가 실패하면 `app_bridge_error`. 둘 다 웹 코드가 보낸다.
- 예전 네이티브 화면과 그 화면의 `track()`(`mobile/src/lib/analytics.ts`)은 지웠다. 새 화면·이벤트는 웹(`frontend/`)에만 더한다.
## GA4 설정
+2 -8
View File
@@ -223,15 +223,9 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
}, [tmr, tmrKind, setPreview])
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
// 지금은 가장 가까운 3시간 칸(17시면 18시 칸). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
// 지금은 지금이 든 3시간 칸(17시면 15시 칸. 서버가 그 칸에 지금 시각 예보를 넣어 준다). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
const slotOf = (k: TimeKind | 'now') => {
if (k === 'now') {
const known = slots.filter((x) => x.temp_c != null)
const at = t.h + t.mi / 60
return known.length ? known.reduce((a, b) => (Math.abs(kst(b.at).h - at) < Math.abs(kst(a.at).h - at) ? b : a)) : undefined
}
const h = PREVIEW[k].hour
const h = k === 'now' ? t.h : PREVIEW[k].hour
const s = slots.length ? slotAt(slots, h) : undefined
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s)
}
+3 -3
View File
@@ -25,9 +25,9 @@ Run lint and typecheck before declaring any task done.
## Navigation & Routing
- Use **Expo Router** for all navigation. Routes live in `src/app/` — every file there is a screen, `_layout.tsx` files define navigators. Keep non-route code (components, hooks, utils) outside `src/app/`.
- Import `Link`, `router`, and `useLocalSearchParams` from `expo-router`.
- Docs: https://docs.expo.dev/router/introduction.md
- The app is a WebView shell: `src/app/_layout.tsx` renders only `WebShell` (`src/components/web-shell.tsx`), which loads the 날씨각 web site. All screens and navigation live in the web app (`frontend/`), not here. Do not add native screens under `src/app/`.
- Expo Router is kept only as the app entry point. `src/app/+native-intent.tsx` redirects every incoming link to `/` so the shell can open it in the WebView.
- Native features the web needs (Google sign-in, location, sharing) go through the bridge in `src/lib/web-bridge.ts`.
## Building with EAS
+3 -12
View File
@@ -2,7 +2,7 @@
"expo": {
"name": "날씨각",
"slug": "nalssigak",
"version": "1.1.1",
"version": "1.1.2",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "nalssigak",
@@ -14,7 +14,7 @@
}
},
"android": {
"versionCode": 1002,
"versionCode": 1005,
"adaptiveIcon": {
"backgroundColor": "#bbeafd",
"foregroundImage": "./assets/images/android-icon-foreground.png",
@@ -55,7 +55,6 @@
"imageWidth": 200
}
],
"expo-secure-store",
"expo-sharing",
[
"expo-location",
@@ -63,15 +62,7 @@
"locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요."
}
],
"@react-native-google-signin/google-signin",
[
"expo-image-picker",
{
"photosPermission": "동네 이야기에 사진을 붙이려고 사진 앨범을 써요.",
"cameraPermission": false,
"microphonePermission": false
}
]
"@react-native-google-signin/google-signin"
],
"experiments": {
"typedRoutes": true,
-15
View File
@@ -3,44 +3,29 @@
"main": "expo-router/entry",
"version": "1.0.0",
"dependencies": {
"@expo-google-fonts/bagel-fat-one": "^0.4.0",
"@expo-google-fonts/gowun-batang": "^0.4.1",
"@expo-google-fonts/jua": "^0.4.1",
"@expo/ui": "~57.0.23",
"@nalssigak/shared": "*",
"@react-native-google-signin/google-signin": "^16.1.5",
"@tanstack/react-query": "^5.104.2",
"expo": "~57.0.28",
"expo-constants": "~57.0.21",
"expo-device": "~57.0.2",
"expo-file-system": "~57.0.7",
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-image": "~57.0.5",
"expo-image-picker": "~57.0.20",
"expo-linear-gradient": "~57.0.2",
"expo-linking": "~57.0.12",
"expo-location": "~57.0.21",
"expo-router": "~57.0.26",
"expo-secure-store": "~57.0.4",
"expo-sharing": "~57.0.23",
"expo-splash-screen": "~57.0.10",
"expo-status-bar": "~57.0.1",
"expo-symbols": "~57.0.3",
"expo-system-ui": "~57.0.4",
"expo-web-browser": "~57.0.3",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.86.3",
"react-native-gesture-handler": "~2.32.0",
"react-native-reanimated": "4.5.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "~4.26.0",
"react-native-svg": "15.15.4",
"react-native-view-shot": "5.1.0",
"react-native-web": "~0.21.0",
"react-native-webview": "13.16.1",
"react-native-worklets": "0.10.1",
"tailwindcss": "^4.3.3",
"uniwind": "^1.12.2"
},
-18
View File
@@ -1,18 +0,0 @@
import { Tabs } from 'expo-router/tabs';
import { TabBar } from '@/components/tab-bar';
import { TopBar } from '@/components/top-bar';
/** 아래 탭 다섯 개. 사주·게임 같은 화면은 탭 밖(루트 스택)에서 연다 */
export default function TabsLayout() {
return (
<Tabs initialRouteName="index" tabBar={(props) => <TabBar {...props} />} screenOptions={{ header: () => <TopBar />, sceneStyle: { backgroundColor: 'transparent' } }}>
{/* 메인인 오늘 탭을 가운데에 */}
<Tabs.Screen name="sky" />
<Tabs.Screen name="gak" />
<Tabs.Screen name="index" />
<Tabs.Screen name="week" />
<Tabs.Screen name="season" />
</Tabs>
);
}
-65
View File
@@ -1,65 +0,0 @@
import { listArticlesOptions, listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { ArticleCategory, IndexCategory } from '@nalssigak/shared/api/client/types.gen';
import { kst, loadOf, seasonOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { Text } from '@/components/text';
import { GakGrid, GridSkel } from '@/components/gak/grid';
import { Podium, PodiumSkel } from '@/components/gak/podium';
import { Chips, Ic, Sec, StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core';
// 마지막 칩은 지금 계절의 제철 각 (예: 가을 각)
const CATS: readonly (readonly [Cat, string])[] = [
['all', '전체'],
['out', '밖에서 놀기'],
['food', '먹고 마시기'],
['home', '집안일'],
['life', '생활 고민'],
['core', `${seasonOf(kst(new Date()).mo)[0]} 각`],
];
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE };
export default function GakScreen() {
const { region } = useRegion();
const { open } = useSheet();
const [cat, setCat] = useState<Cat>('all');
const q = useQuery(listIndicesOptions({ query: { region: region.code, category: CAT_PARAM[cat], core: cat === 'core' ? true : undefined } }));
const articles = useQuery(listArticlesOptions({ query: { category: ArticleCategory.GAK } }));
const top = q.data?.top3 ?? [];
const items = q.data?.items ?? [];
const day = q.data?.day?.split('-').map(Number);
const load = loadOf(q);
const howto = articles.data?.articles?.find((a) => a.code === 'howgak');
return (
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={q.isRefetching && !q.isPlaceholderData} onRefresh={() => q.refetch()} />}>
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name}`} />
{top.length === 3 ? <Podium top={top} dim={q.isPlaceholderData} /> : load === 'loading' ? <PodiumSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} />}
<Chips items={CATS} value={cat} onChange={setCat} />
{load === 'loading' ? (
<GridSkel />
) : !items.length ? (
// 실패 안내·다시 시도는 위 받침대 자리에 한 번만
<StateBox load="ready" empty={load === 'ready' ? '이 분야는 오늘 계산된 각이 없어요.' : '각 목록을 불러오지 못했어요.'} hold={<GridSkel />} boxClassName="inset-3" />
) : (
<GakGrid items={items} dim={q.isPlaceholderData} />
)}
{howto && load !== 'loading' && (
<Pressable onPress={() => open({ type: 'article', articleId: howto.article_id })} className="mx-3 mt-1.5 flex-row items-center gap-3 rounded-[22px] bg-[#ece7ff] p-3.5">
<Ic name="bulb" size={44} />
<View className="flex-1">
<Text className="font-jua text-[17px] text-[#28304a]">각 점수는 어떻게 매길까?</Text>
<Text className="text-[12.5px] font-semibold text-[#5a6380]">기온·비·바람·습도·공기·시간대 6가지로 계산해요</Text>
</View>
</Pressable>
)}
</ScrollView>
);
}
-178
View File
@@ -1,178 +0,0 @@
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
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 { router, useLocalSearchParams } from 'expo-router';
import { Fragment, useEffect, useRef, type ReactNode } from 'react';
import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-native';
import { FoliageCard } from '@/components/foliage/foliage-card';
import { MyGakRow } from '@/components/my-gak/my-gak';
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
import { ShortsRail } from '@/components/shorts/rail';
import { Composer, TalkPost } from '@/components/talk/talk';
import { GakCard } from '@/components/today/gak-card';
import { Hero } from '@/components/today/hero';
import { TodayIcons } from '@/components/today/icons';
import { SeasonBand } from '@/components/today/rails';
import { StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useFoliage } from '@/lib/foliage';
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';
// 사람 글은 포스트 두 장마다 한 장씩 최신순으로 끼운다
const TALK_EVERY = 2;
type Spot = { item: 'talk' | 'event'; position: number; y: number; h: number };
/** 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보일 때 한 번 GA 로 보낸다 (웹 Seen) */
function useSeen() {
const spots = useRef(new Map<string, Spot>());
const sent = useRef(new Set<string>());
const view = useRef({ y: 0, h: 0 });
const check = () => {
const { y, h } = view.current;
if (!h) return;
for (const [key, s] of spots.current) {
if (sent.current.has(key) || !s.h) continue;
const shown = Math.min(y + h, s.y + s.h) - Math.max(y, s.y);
if (shown < s.h / 2) continue;
sent.current.add(key);
track('feed_item_view', { item_type: s.item, position: s.position });
}
};
const at = (item: Spot['item'], position: number) => (l: LayoutRectangle) => {
spots.current.set(`${item}:${position}`, { item, position, y: l.y, h: l.height });
check();
};
const onScroll = (y: number, h: number) => {
view.current = { y, h };
check();
};
return { at, onScroll };
}
export default function TodayScreen() {
const { region } = useRegion();
const feed = useQuery(getFeedOptions({ query: { region: region.code } }));
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }));
const { preview } = useSky();
const f = feed.data;
const posts = (f?.posts ?? []).filter(isAppPost);
const stories = atSlot(f?.stories ?? [], preview);
const sloted = preview != null && stories !== f?.stories;
const bands = f?.bands;
const nowAt = f?.hero?.now_at;
const load = loadOf(feed);
const talkList = useTopicTalks();
const talks = talkList.talks;
const talkAt = (i: number) => ((i + 1) % TALK_EVERY === 0 ? talks[(i + 1) / TALK_EVERY - 1] : undefined);
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 { inSeason } = useFoliage();
const scroll = useRef<ScrollView>(null);
const myGakY = useRef(0);
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번째 글 뒤에 계절 이야기 띠를 넣고, 글이 모자라면 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null]];
return (
// 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다
<ScrollView
ref={scroll}
key={region.code}
contentContainerClassName="pb-6"
refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />}
style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}
keyboardShouldPersistTaps="handled"
scrollEventThrottle={200}
onLayout={(e) => seen.onScroll(0, e.nativeEvent.layout.height)}
onScroll={(e) => seen.onScroll(e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height)}
>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<TodayIcons foliage={inSeason} onMyGak={() => scroll.current?.scrollTo({ y: myGakY.current, animated: true })} />
<ShortsRail />
<Composer />
{/* 아이콘 줄 '내 각'이 여기로 내려온다 */}
<View onLayout={(e) => (myGakY.current = e.nativeEvent.layout.y)}>
<MyGakRow />
</View>
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} boxClassName="inset-x-3 top-3 bottom-1" />
)}
{load === 'loading' && (
<>
<PostCardSkel />
<PostCardSkel />
</>
)}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
{load !== 'loading' && !posts.length && (
<StateBox
load="ready"
empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'}
hold={
<>
<PostCardSkel />
<PostCardSkel />
</>
}
boxClassName="inset-x-3 top-3.5"
/>
)}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
{posts.map((p, i) => {
const t = talkAt(i);
const ev = eventNo.get(p.post_id);
return (
<Fragment key={p.post_id}>
{ev ? (
<View onLayout={(e) => seen.at('event', ev)(e.nativeEvent.layout)}>
<PostCard post={p} />
</View>
) : (
<PostCard post={p} />
)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{t && (
<View onLayout={(e) => seen.at('talk', (i + 1) / TALK_EVERY)(e.nativeEvent.layout)}>
<TalkPost key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
</View>
)}
</Fragment>
);
})}
{/* 포스트가 모자라 끼울 자리가 없던 사람 글은 맨 뒤에 */}
{feed.isSuccess &&
talks.slice(talkFrom).map((t, n) => (
<View key={t.talk_id} onLayout={(e) => seen.at('talk', talkFrom + n + 1)(e.nativeEvent.layout)}>
<TalkPost t={t} />
</View>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</ScrollView>
);
}
-45
View File
@@ -1,45 +0,0 @@
import { getSeasonWeekOptions, listArticlesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { ArticleCategory } from '@nalssigak/shared/api/client/types.gen';
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { RefreshControl, ScrollView, View } from 'react-native';
import { ArticleRow, HeadSkel, RowsSkel, SeasonHead } from '@/components/season/parts';
import { Chips, StateBox } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
const CATS = [
['all', '전체'],
['season', '계절 소식'],
['tip', '날씨 상식'],
['gak', '각 원리'],
] as const;
const CAT_PARAM = { season: ArticleCategory.SEASON, tip: ArticleCategory.TIP, gak: ArticleCategory.GAK } as const;
export default function SeasonScreen() {
const { open } = useSheet();
const [cat, setCat] = useState<(typeof CATS)[number][0]>('all');
const week = useQuery(getSeasonWeekOptions());
const arts = useQuery(listArticlesOptions(cat === 'all' ? undefined : { query: { category: CAT_PARAM[cat] } }));
const w = week.data;
const list = arts.data?.articles ?? [];
const weekLoad = loadOf(week);
const artLoad = loadOf(arts);
const refresh = () => Promise.all([week.refetch(), arts.refetch()]);
return (
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={(week.isRefetching || arts.isRefetching) && !arts.isPlaceholderData} onRefresh={refresh} />}>
{w?.headline ? <SeasonHead week={w} onPress={() => open({ type: 'seasonWeek' })} /> : weekLoad === 'loading' ? <HeadSkel /> : <StateBox load={weekLoad} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." hold={<HeadSkel />} />}
<Chips items={CATS} value={cat} onChange={setCat} />
<View className="mt-1.5" style={{ opacity: arts.isPlaceholderData ? 0.6 : 1 }}>
{artLoad === 'loading' && <RowsSkel />}
{artLoad !== 'loading' && !list.length && <StateBox load={artLoad} onRetry={() => arts.refetch()} empty="읽을거리가 아직 없어요." hold={<RowsSkel />} boxClassName="inset-3" />}
{list.map((a) => (
<ArticleRow key={a.article_id} article={a} onPress={() => open({ type: 'article', articleId: a.article_id })} />
))}
</View>
</ScrollView>
);
}
-101
View File
@@ -1,101 +0,0 @@
import { getSkyOptions, getSkyRankingOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { RefreshControl, ScrollView, View } from 'react-native';
import { DayTiles, Li, LiSkel, ScoreHelp, SkyHero, Timeline } from '@/components/sky/parts';
import { Sec, Skel, StateBox } from '@/components/ui';
import { useRegion } from '@/lib/region';
const THREE = [0, 1, 2];
const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i);
/** 히어로 글자 자리 (실패·빈 안내를 같은 높이로 띄우려고) */
function HeroHold() {
return (
<View>
<Skel className="h-7 w-[230px]" />
<Skel className="mt-2 w-[180px]" />
</View>
);
}
function LiSkels({ n }: { n: number[] }) {
return (
<View className="mx-3 mt-1.5">
{n.map((i) => (
<LiSkel key={i} last={i === n.length - 1} />
))}
</View>
);
}
export default function SkyScreen() {
const { region } = useRegion();
const sky = useQuery(getSkyOptions({ query: { region: region.code } }));
const ranking = useQuery(getSkyRankingOptions());
const load = loadOf(sky);
const rankLoad = loadOf(ranking);
const plans = sky.data?.plans ?? [];
const [picked, setPicked] = useState<string>();
// 타일을 누르면 그날, 아니면 다음에 오는 날
const plan = plans.find((p) => p.day === picked) ?? sky.data?.plan ?? undefined;
const spots = (sky.data?.spots ?? []).slice(0, 3);
const items = (ranking.data?.items ?? []).slice(0, 8);
const rise = plan?.kind === 'sunrise';
const refresh = () => Promise.all([sky.refetch(), ranking.refetch()]);
return (
<ScrollView contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={sky.isRefetching && !sky.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: sky.isPlaceholderData ? 0.6 : 1 }}>
{plan || load === 'loading' ? (
<SkyHero plan={plan} />
) : (
<SkyHero>
<StateBox load={load} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." hold={<HeroHold />} boxClassName="inset-x-0 top-1.5 bottom-0" />
</SkyHero>
)}
{plans.length > 1 && <DayTiles plans={plans} day={plan?.day} onPick={setPicked} />}
{plan && <ScoreHelp plan={plan} />}
<Sec title="언제 보면 좋을까" />
{plan?.timeline?.length || load === 'loading' ? <Timeline rows={plan?.timeline} kind={plan?.kind} /> : <StateBox load="ready" empty={load === 'ready' ? '노을 시간 정보가 없어요.' : '노을 시간을 불러오지 못했어요.'} hold={<Timeline />} />}
{!rise && <Sec title="가까운 노을 명소" sub="가까운 순 · 방향은 내 동네에서 본 쪽" />}
{rise ? null : spots.length ? (
<View className="mx-3 mt-1.5">
{spots.map((p, i) => (
<Li key={p.no} no={p.no} title={p.name} sub={p.direction ? `${p.direction}쪽` : null} right={`${p.distance_km}km`} place={p.name} last={i === 2} />
))}
{/* 3곳이 안 되면 빈 줄로 높이를 지켜 아래 순위가 밀리지 않게 */}
{THREE.slice(spots.length).map((i) => (
<LiSkel key={`ghost-${i}`} ghost last={i === 2} />
))}
</View>
) : load === 'loading' ? (
<View className="mx-3 mt-1.5">
{THREE.map((i) => (
<LiSkel key={i} last={i === 2} />
))}
</View>
) : (
// 실패 안내·다시 시도는 위 히어로에 한 번만
<StateBox load="ready" empty={load === 'ready' ? '근처에 등록된 노을 명소가 없어요.' : '명소 정보를 불러오지 못했어요.'} hold={<LiSkels n={THREE} />} />
)}
<Sec title="전국 노을 순위" sub={ranking.data?.summary ?? '오늘 기준'} />
{items.length ? (
<View className="mx-3 mt-1.5">
{items.map((r, i) => (
<Li key={r.region_code} no={r.rank} title={r.name} sub={[r.note, r.situation_label].filter(Boolean).join(' · ')} right={`${r.score}점`} mine={r.region_code === region.code} last={i === items.length - 1} />
))}
</View>
) : rankLoad === 'loading' ? (
<View className="mx-3 mt-1.5">
{RANK_SKELS.map((i) => (
<LiSkel key={i} last={i === RANK_SKELS.length - 1} />
))}
</View>
) : (
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." hold={<LiSkels n={RANK_SKELS} />} boxClassName="inset-x-3 top-1.5 bottom-0" />
)}
</ScrollView>
);
}
-153
View File
@@ -1,153 +0,0 @@
import { getWeekOptions, getWeekRankingOptions, listEventsOptions, listPlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { loadOf, shortDay } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useRef, useState } from 'react';
import { Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { Text } from '@/components/text';
import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/week/sections';
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 { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
const RANK_TABS_HOLD = [
['토', '토요일'],
['일', '일요일'],
] as const;
export default function WeekScreen() {
const { region } = useRegion();
const week = useQuery(getWeekOptions({ query: { region: region.code } }));
const days = week.data?.days ?? [];
const [picked, setPicked] = useState<string | null>(null);
// 지역을 바꾸면 동네 고르기는 전체로 돌아간다
const [areaPick, setAreaPick] = useState({ region: region.code, area: '전체' });
const area = areaPick.region === region.code ? areaPick.area : '전체';
// 처음에는 이번 토요일을 고른다
const sel = days.find((d) => d.day === picked) ?? days.find((d) => d.weekday === '토') ?? days[0];
const places = useQuery({ ...listPlacesOptions({ query: { region: region.code, day: sel?.day, area: area === '전체' ? undefined : area } }), enabled: !!sel });
const events = useQuery(listEventsOptions({ query: { region: region.code } }));
const ranking = useQuery(getWeekRankingOptions());
const rankDays = ranking.data?.days ?? [];
const [rankPick, setRankPick] = useState<string | null>(null);
const rankDay = rankDays.find((d) => d.day === rankPick) ?? rankDays[0];
const rankItems = (rankDay?.items ?? []).slice(0, 10);
const rankLoad = loadOf(ranking);
const areas = places.data?.areas ?? [];
const rainy = places.data?.rainy ?? sel?.is_rainy;
const placeList = places.data?.places ?? [];
const eventList = events.data?.events ?? [];
const weekLoad = loadOf(week);
const eventLoad = loadOf(events);
// 날씨(고른 날)가 와야 명소를 부를 수 있다
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<View>(null);
// 고른 날 추천 카드를 이미지로
const sendPlan = () => {
if (!sel) return;
const message = [`${sel.weekday}요일 일정 · ${region.name}`, sel.headline, sel.summary, sel.pick, `날씨각 ${SITE_URL}`].filter(Boolean).join('\n');
void shareView(pickShot, { title: `${sel.weekday}요일 일정`, message });
};
const placeSub = sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? undefined : '날씨에 맞춰 골라 보여 줘요';
return (
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={week.isRefetching && !week.isPlaceholderData} onRefresh={refresh} />}>
<Sec title="열흘 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
{days.length ? (
<DayStrip days={days} selected={sel?.day} onPick={setPicked} dim={week.isPlaceholderData} />
) : weekLoad === 'loading' ? (
<>
<DaysSkel />
<PickSkel />
</>
) : (
<StateBox
load={weekLoad}
onRetry={() => week.refetch()}
empty="날씨가 아직 없어요."
hold={
<>
<DaysSkel />
<PickSkel />
</>
}
/>
)}
{sel && (
<View ref={pickShot} collapsable={false}>
<PickCard day={sel} />
</View>
)}
{(sel || weekLoad !== 'ready') && (
<>
<Text className="mx-4 mt-3.5 text-[13.5px] font-bold text-ink2">30km 안 · 데이트 명소</Text>
<Chips items={['전체', ...areas].map((a) => [a, a] as const)} value={area} onChange={(a) => setAreaPick({ region: region.code, area: a })} disabled={!areas.length} />
</>
)}
{/* 명소 데이터가 없으면 칸 전체를 숨긴다 */}
{!(placeLoad === 'ready' && !placeList.length) && (
<>
<View className="-mt-2.5">
<Sec title="날씨 맞춤 데이트 명소" sub={placeSub} />
</View>
{!placeSub && <Skel className="mx-4 w-56" />}
{placeList.length ? (
<View style={{ opacity: places.isPlaceholderData ? 0.6 : 1 }}>
<Rail>
{placeList.map((p, i) => (
<PlaceCard key={p.place_id} place={p} index={i} />
))}
</Rail>
</View>
) : placeLoad === 'loading' ? (
<PlacesSkel />
) : (
<StateBox load={placeLoad} onRetry={() => places.refetch()} empty={sel ? '30km 안에 데이트 명소가 아직 없어요.' : '날씨를 불러오면 명소를 골라 드려요.'} hold={<PlacesSkel />} />
)}
</>
)}
<Sec title="이번 주말 전국 날씨 순위" sub="낮 10~17시 나들이 날씨 · 대표 지역 30곳 중 10위까지" />
{rankDays.length ? (
<Chips items={rankDays.map((d) => [d.day, `${d.weekday}요일 ${shortDay(d.day)}`] as const)} value={rankDay?.day ?? ''} onChange={setRankPick} />
) : (
<Chips items={RANK_TABS_HOLD} value="토" onChange={() => undefined} disabled />
)}
{rankItems.length ? (
<View className="mx-3 mt-1.5" style={{ opacity: ranking.isPlaceholderData ? 0.6 : 1 }}>
{rankItems.map((r) => (
<RankRow key={r.region_code} item={r} mine={r.region_code === region.code} />
))}
</View>
) : rankLoad === 'loading' ? (
<RankSkel />
) : (
<StateBox load={rankLoad} onRetry={() => ranking.refetch()} empty="주말 예보가 아직 없어요." hold={<RankSkel />} boxClassName="inset-x-3 top-1.5 bottom-0" />
)}
<Sec title="가까운 축제·행사" sub="30km 안 · 앞으로 30일 · 그날 날씨까지 같이 봐요" />
{eventList.length ? (
<View style={{ opacity: events.isPlaceholderData ? 0.6 : 1 }}>
{eventList.map((e, i) => (
<EventRow key={e.event_id} event={e} index={i} />
))}
</View>
) : eventLoad === 'loading' ? (
<EventsSkel />
) : (
<StateBox load={eventLoad} onRetry={() => events.refetch()} empty="30km 안에 열리는 행사가 아직 없어요. 다른 지역을 골라 보세요." hold={<EventsSkel />} boxClassName="inset-x-3 top-2.5 bottom-0" />
)}
{/* 행사 수가 정해진 뒤에 붙여 목록이 늘어날 때 밀리지 않게 */}
{eventLoad !== 'loading' && (
<Pressable onPress={sendPlan} disabled={!sel} className="mx-3 mt-4 items-center rounded-full border-b-[5px] border-orange-deep bg-orange p-[13px] disabled:opacity-60">
<Text className="font-jua text-[17px] text-white">이번 주말 일정 보내기</Text>
</Pressable>
)}
</ScrollView>
);
}
-85
View File
@@ -1,85 +0,0 @@
import { headline, md, type Kind, type Spot } from '@nalssigak/shared/lib/foliage';
import { useLocalSearchParams } from 'expo-router';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Pressable, ScrollView, useWindowDimensions, View } from 'react-native';
import { useCSSVariable } from 'uniwind';
import { FoliageMap, type FoliageMapHandle } from '@/components/foliage/foliage-map';
import { ChosenBar, SpotList } from '@/components/foliage/spot-list';
import { SendIcon } from '@/components/post/icons';
import { ScreenHeader } from '@/components/screen-header';
import { Text } from '@/components/text';
import { Chips, Ic } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useFoliage } from '@/lib/foliage';
import { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
type Filter = 'all' | Kind;
const FILTERS: [Filter, string][] = [
['all', '전체'],
['maple', '단풍'],
['ginkgo', '은행'],
];
/** 단풍 지도: 명소 67곳을 지도에서 확대해 보고 아래 목록으로 고른다. ?spot= 으로 열면 그 명소로 (웹 FoliagePage) */
export default function FoliageScreen() {
const params = useLocalSearchParams<{ spot?: string }>();
const { today, spots } = useFoliage();
const [filter, setFilter] = useState<Filter>('all');
const [sel, setSel] = useState<string | null>(params.spot ?? null);
const mapRef = useRef<FoliageMapHandle>(null);
const shotRef = useRef<View>(null);
const shareView = useShare();
const ink = String(useCSSVariable('--color-ink'));
const { width, height: winH } = useWindowDimensions();
// 지도는 스크롤 밖에 고정: 가로만큼 정사각형, 화면이 낮으면 화면 높이의 45%까지
const mapH = Math.max(280, Math.min(width * 1.05, winH * 0.45, 560));
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter]);
useEffect(() => track('foliage_open', {}), []);
useEffect(() => {
if (sel) track('foliage_spot', { spot_name: sel, from: 'page' });
}, [sel]);
const chosen = spots.find((m) => m.name === sel);
const peakCount = spots.filter((m) => m.stage === 'peak').length;
const title = headline(spots);
const pick = (m: Spot) => {
setSel(m.name);
mapRef.current?.focus(m);
};
const share = () => void shareView(shotRef, { title: chosen ? `${chosen.name} 단풍` : '단풍 지도', message: `${title} · 날씨각 단풍 지도 ${SITE_URL}/foliage` });
return (
<View className="flex-1">
<ScreenHeader
title="단풍 지도"
right={
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="단풍 지도 보내기" className="size-10 items-center justify-center">
<SendIcon size={24} color={ink} />
</Pressable>
}
/>
<View className="px-4 pt-1 pb-2">
<View className="flex-row items-center gap-1">
<Ic name="maple" size={16} />
<Text className="text-[13px] font-extrabold text-ink2">{`단풍 지도 · ${md(today)}`}</Text>
</View>
<Text className="mt-0.5 font-jua text-[24px] leading-tight text-ink">{title}</Text>
</View>
{/* 보내기는 지금 보이는 지도 그대로 찍어 보낸다 (웹은 따로 만든 공유 그림) */}
<View ref={shotRef} collapsable={false}>
<FoliageMap ref={mapRef} spots={shown} sel={sel} onSelect={setSel} height={mapH} />
</View>
<ChosenBar chosen={chosen} legendColor={ink} />
<ScrollView className="flex-1" contentContainerClassName="pb-8">
<Chips items={FILTERS} value={filter} onChange={setFilter} />
<SpotList spots={shown} sel={sel} onPick={pick} />
<Text className="px-5 pt-4 text-[11.5px] leading-relaxed font-semibold text-ink3">
{`출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요${peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}`}
</Text>
</ScrollView>
</View>
);
}
-98
View File
@@ -1,98 +0,0 @@
import { getAccessToken } from '@nalssigak/shared/api/auth';
import { router } from 'expo-router';
import { useRef, useState } from 'react';
import { ActivityIndicator, Linking, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
import { ScreenHeader } from '@/components/screen-header';
import { Text } from '@/components/text';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
const SITE_ORIGIN = new URL(SITE_URL).origin;
/** 게임 웹뷰는 날씨각 사이트 안에서만 움직인다. 다른 주소(외부 링크)는 휴대폰 브라우저로 연다 */
function stayOnSite(url: string) {
if (url.startsWith(`${SITE_ORIGIN}/`) || url === SITE_ORIGIN || url === 'about:blank') return true;
if (/^https?:/.test(url)) Linking.openURL(url).catch((e: unknown) => console.warn('[game] 외부 주소를 열지 못함', url, e));
return false;
}
/**
* 웹 페이지가 뜨기 전에 넣는 스크립트: 앱의 지역·로그인을 웹 저장소에 옮기고,
* 게임 화면을 떠나는 이동(뒤로 버튼)과 '로그인하면 …' 버튼은 앱으로 알린다 (웹 구글 로그인은 앱 안 웹뷰에서 막힌다).
* 갱신 토큰은 넘기지 않는다: 웹이 갱신하면 앱이 가진 갱신 토큰이 쓸모없어질 수 있다.
* 날씨각 사이트에서 열렸을 때만 토큰을 넣는다 (다른 곳으로 넘어가면 아무것도 하지 않는다).
*/
function bridge(region: unknown, token: string | null) {
return `(function () {
if (location.origin !== ${JSON.stringify(SITE_ORIGIN)}) return;
try {
localStorage.setItem('nalssigak.b.region', ${JSON.stringify(JSON.stringify(region))});
${token ? `localStorage.setItem('nalssigak.accessToken', ${JSON.stringify(token)});` : `localStorage.removeItem('nalssigak.accessToken');`}
localStorage.removeItem('nalssigak.refreshToken');
} catch (e) {}
var post = function (t) { window.ReactNativeWebView.postMessage(t); };
var check = function () { if (location.pathname !== '/game') post('leave'); };
var push = history.pushState, replace = history.replaceState;
history.pushState = function () { push.apply(this, arguments); check(); };
history.replaceState = function () { replace.apply(this, arguments); check(); };
window.addEventListener('popstate', check);
document.addEventListener('click', function (e) {
var b = e.target && e.target.closest && e.target.closest('button');
if (b && b.textContent && b.textContent.trim().indexOf('로그인') === 0) { e.preventDefault(); e.stopPropagation(); post('login'); }
}, true);
})();
true;`;
}
/** 구름 합치기 게임: 웹 /game 을 그대로 띄운다 (물리 엔진·캔버스라 웹과 같은 화면, 사용자 결정 11/04) */
export default function GameScreen() {
const { region } = useRegion();
const { loggedIn } = useAuth();
const { open } = useSheet();
const { top, bottom } = useSafeAreaInsets();
const [failed, setFailed] = useState(false);
const left = useRef(false);
const onMessage = (e: WebViewMessageEvent) => {
if (e.nativeEvent.data === 'leave' && !left.current) {
left.current = true;
if (router.canGoBack()) router.back();
else router.replace('/');
}
if (e.nativeEvent.data === 'login') open({ type: 'login' });
};
if (failed)
return (
<View className="flex-1">
<ScreenHeader title="구름 합치기" />
<Text className="mx-6 mt-10 text-center text-[15px] font-bold text-ink2">게임을 불러오지 못했어요. 인터넷 연결을 확인하고 다시 들어와 주세요.</Text>
</View>
);
return (
<View className="flex-1 bg-[#cfe9ff]" style={{ paddingTop: top, paddingBottom: bottom }}>
{/* 로그인하면 토큰을 다시 넣어야 해서 로그인 여부로 새로 띄운다 */}
<WebView
key={`${region.code}:${loggedIn}`}
source={{ uri: `${SITE_URL}/game` }}
originWhitelist={[SITE_ORIGIN]}
onShouldStartLoadWithRequest={(req) => stayOnSite(req.url)}
injectedJavaScriptBeforeContentLoaded={bridge(region, getAccessToken())}
onMessage={onMessage}
onError={() => setFailed(true)}
startInLoadingState
renderLoading={() => <ActivityIndicator style={{ position: 'absolute', top: '45%', alignSelf: 'center' }} />}
overScrollMode="never"
bounces={false}
setSupportMultipleWindows={false}
style={{ backgroundColor: 'transparent' }}
/>
</View>
);
}
+7
View File
@@ -0,0 +1,7 @@
/**
* 화면은 _layout.tsx 의 웹 셸이 다 그린다. 이 파일은 Expo Router 가 '/' 경로를 알게 하려고 둔다.
* 경로 파일이 하나도 없으면 Expo Router 가 우리 _layout 대신 자기 안내 화면(_sitemap)을 띄우다 앱이 죽는다.
*/
export default function Index() {
return null;
}
-63
View File
@@ -1,63 +0,0 @@
import { useLocalSearchParams } from 'expo-router';
import { useMemo, useRef, useState } from 'react';
import { ScrollView, View } from 'react-native';
import { BirthForm } from '@/components/saju/birth-form';
import { OpenTarget } from '@/components/saju/parts';
import { Reading } from '@/components/saju/reading';
import { ScreenHeader } from '@/components/screen-header';
import { Text } from '@/components/text';
import { useAccountBirth, useBirth } from '@/lib/saju-birth';
type Pos = { base: number | null; panel: number | null; done: boolean };
function tryScroll(p: Pos, view: ScrollView | null) {
if (p.done || p.base == null || p.panel == null || !view) return;
p.done = true;
view.scrollTo({ y: Math.max(0, p.base + p.panel - 12), animated: true });
}
/** 날씨 사주(/saju): 오늘 점수와 할 일, 내 기운, 레벨로 열리는 칸. ?open=saju_love 처럼 열면 그 칸으로 내려간다 (웹 SajuPage, #hash) */
export default function SajuScreen() {
const params = useLocalSearchParams<{ open?: string }>();
const birth = useBirth();
const loading = useAccountBirth();
const [editing, setEditing] = useState(false);
const scroll = useRef<ScrollView>(null);
// 결과 묶음의 위치와 그 안에서 연 칸의 위치를 둘 다 알아야 내려갈 수 있다 (어느 쪽이 먼저 잡힐지 모른다)
const pos = useRef<Pos>({ base: null, panel: null, done: false });
const target = useMemo(
() => ({
id: params.open,
onLayout: (y: number) => {
pos.current.panel = y;
tryScroll(pos.current, scroll.current);
},
}),
[params.open],
);
return (
<View className="flex-1">
<ScreenHeader title="날씨 사주" />
<ScrollView ref={scroll} contentContainerClassName="pb-8" keyboardShouldPersistTaps="handled">
{loading && !birth ? (
<Text className="px-4 py-16 text-center font-semibold text-ink2">내 생년월일을 불러오는 중이에요…</Text>
) : !birth || editing ? (
<BirthForm initial={birth} onDone={() => setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} />
) : (
<View
onLayout={(e) => {
pos.current.base = e.nativeEvent.layout.y;
tryScroll(pos.current, scroll.current);
}}
>
<OpenTarget value={target}>
<Reading birth={birth} onEdit={() => setEditing(true)} />
</OpenTarget>
</View>
)}
</ScrollView>
</View>
);
}
-127
View File
@@ -1,127 +0,0 @@
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { ShortItem } from '@nalssigak/shared/api/client/types.gen';
import { useQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { router, useLocalSearchParams } from 'expo-router';
import { useEffect, useRef, useState } from 'react';
import { FlatList, Pressable, View, type ViewToken } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { ShortPlayer, type PlayerHandle } from '@/components/shorts/player';
import { thumb } from '@/components/shorts/rail';
import { Text } from '@/components/text';
import { track } from '@/lib/analytics';
const BAR = 48;
/** 쇼츠 화면: 그 영상부터 위아래로 넘겨 본다. 보이는 영상과 앞뒤만 소리 없이 미리 띄우고, 누르면 소리 켜기·끄기 (웹 ShortsPage) */
export default function ShortsScreen() {
const { id } = useLocalSearchParams<{ id?: string }>();
const q = useQuery(listShortsOptions());
const { top, bottom } = useSafeAreaInsets();
// 처음 들어온 영상만 시작점으로 쓴다
const [firstId] = useState(id);
const listed = q.data?.items ?? [];
const items: ShortItem[] = firstId && listed.length && !listed.some((s) => s.id === firstId) ? [{ id: firstId, title: '' }, ...listed] : listed;
const start = Math.max(0, items.findIndex((s) => s.id === firstId));
const [at, setAt] = useState(start);
const [sound, setSound] = useState(false);
const [ready, setReady] = useState<ReadonlySet<number>>(new Set());
const [box, setBox] = useState({ w: 0, h: 0 });
const players = useRef(new Map<number, PlayerHandle>());
const soundRef = useRef(false);
const atRef = useRef(start);
useEffect(() => {
if (firstId) track('shorts_open', { video_id: firstId });
}, [firstId]);
// 넘어온 영상만 처음부터 다시 틀고 소리를 맞춘다. 앞뒤는 소리만 끈다 (멈추면 유튜브 버튼이 떠서 멈추지 않는다)
useEffect(() => {
for (const [i, p] of players.current) {
if (i === at) {
p.command('seekTo', [0, true]);
p.command(soundRef.current ? 'unMute' : 'mute');
p.command('playVideo');
} else p.command('mute');
}
}, [at]);
// FlatList 는 이 함수가 바뀌면 안 되어 처음 한 번만 만든다
const [onViewable] = useState(() => ({ viewableItems }: { viewableItems: ViewToken<ShortItem>[] }) => {
const i = viewableItems[0]?.index;
if (i == null || i === atRef.current) return;
atRef.current = i;
setAt(i);
const s = viewableItems[0].item;
track('shorts_view', { video_id: s.id, index: i });
});
const toggleSound = () => {
const on = !soundRef.current;
soundRef.current = on;
setSound(on);
track('shorts_sound', { on });
players.current.get(at)?.command(on ? 'unMute' : 'mute');
};
const close = () => (router.canGoBack() ? router.back() : router.replace('/'));
// 9:16 을 칸 안에 맞춘다
const w = Math.min(box.w, (box.h * 9) / 16);
const h = (w * 16) / 9;
return (
<View className="flex-1 bg-[#1d2233]" style={{ paddingTop: top, paddingBottom: bottom }}>
{!!items[at] && <Image source={{ uri: thumb(items[at].id) }} style={{ position: 'absolute', inset: 0, opacity: 0.7, transform: [{ scale: 1.25 }] }} blurRadius={40} contentFit="cover" />}
<View className="absolute inset-0 bg-black/35" />
<View className="flex-row items-center justify-between px-3" style={{ height: BAR }}>
<Pressable onPress={close} hitSlop={8} accessibilityRole="button" accessibilityLabel="닫기" className="size-9 items-center justify-center rounded-full bg-white/15">
<Svg viewBox="0 0 24 24" width={18} height={18} fill="none" stroke="#fff" strokeWidth={2.4} strokeLinecap="round">
<Path d="M6 6l12 12M18 6L6 18" />
</Svg>
</Pressable>
<Pressable onPress={toggleSound} accessibilityRole="button" accessibilityState={{ selected: sound }} className="h-9 justify-center rounded-full bg-white/15 px-3.5">
<Text className="text-[13px] font-bold text-white">{sound ? '소리 끄기' : '소리 켜기'}</Text>
</Pressable>
</View>
<View className="flex-1" onLayout={(e) => setBox({ w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height })}>
{box.h > 0 && items.length > 0 && (
<FlatList
data={items}
keyExtractor={(s) => s.id}
pagingEnabled
showsVerticalScrollIndicator={false}
initialScrollIndex={start}
getItemLayout={(_, i) => ({ length: box.h, offset: box.h * i, index: i })}
onViewableItemsChanged={onViewable}
viewabilityConfig={{ itemVisiblePercentThreshold: 60 }}
windowSize={3}
renderItem={({ item: s, index: i }) => (
<View style={{ height: box.h }} className="items-center justify-center">
<View style={{ width: w, height: h }}>
<Image source={{ uri: thumb(s.id) }} style={{ position: 'absolute', inset: 0 }} contentFit="cover" />
{/* 릴스처럼 앞뒤 영상을 소리 없이 미리 받아 둔다. 첫 장면 전엔 표지가 보이게 숨긴다 */}
{Math.abs(i - at) <= 1 && (
<View pointerEvents="none" style={{ position: 'absolute', inset: 0, opacity: ready.has(i) ? 1 : 0 }}>
<ShortPlayer
id={s.id}
ref={(p) => {
if (p) players.current.set(i, p);
else players.current.delete(i);
}}
onPlaying={() => setReady((r) => (r.has(i) ? r : new Set(r).add(i)))}
/>
</View>
)}
{/* 누르면 소리 켜기·끄기, 위아래로 밀면 목록이 넘어간다 */}
<Pressable onPress={toggleSound} accessibilityLabel={sound ? '소리 끄기' : '소리 켜기'} style={{ position: 'absolute', inset: 0 }} />
</View>
</View>
)}
/>
)}
</View>
</View>
);
}
-2
View File
@@ -1,2 +0,0 @@
// 아이콘 줄 '쇼츠'(/shorts)는 첫 영상부터
export { default } from './[id]';
-71
View File
@@ -1,71 +0,0 @@
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen';
import { router, useLocalSearchParams } from 'expo-router';
import { FlatList, Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { ScreenHeader } from '@/components/screen-header';
import { Composer, TalkCard } from '@/components/talk/talk';
import { Text } from '@/components/text';
import { Sec } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { useSheet } from '@/lib/sheet';
import { openTopics, TOPICS, useMyTalks, useTopicTalks } from '@/lib/talk';
type Tab = TalkTopic | 'all' | 'mine';
/** 주제별 사람 글: 위 주제 탭(한 줄 가로로 밀기, 끝에 '내 글'), 아래 글 목록. ?topic= · ?mine=1 로 연다 (웹 TalkPage) */
export default function TalkScreen() {
const params = useLocalSearchParams<{ topic?: string; mine?: string }>();
const { loggedIn } = useAuth();
const { open } = useSheet();
const raw = Number(params.topic);
const tab: Tab = params.mine ? 'mine' : TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : 'all';
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab);
const mineList = useMyTalks(tab === 'mine' && loggedIn);
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList;
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...openTopics(), ['mine', '내 글']];
const go = (k: Tab) => router.setParams(k === 'mine' ? { mine: '1', topic: undefined } : k === 'all' ? { mine: undefined, topic: undefined } : { mine: undefined, topic: String(k) });
const head = (
<View>
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<View accessibilityRole="tablist" accessibilityLabel="글 주제">
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerClassName="gap-1.5 px-4 pb-1">
{tabs.map(([k, label]) => (
<Pressable key={label} onPress={() => go(k)} accessibilityRole="tab" accessibilityState={{ selected: tab === k }} className={`rounded-full px-3 py-1.5 ${tab === k ? 'bg-ink-btn' : 'bg-card'}`}>
<Text className={`text-[13px] font-extrabold ${tab === k ? 'text-white' : 'text-ink2'}`}>{label}</Text>
</Pressable>
))}
</ScrollView>
</View>
<Composer />
{tab === 'mine' && !loggedIn ? (
<Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">
로그인하면 내가 쓴 글을 모아 볼 수 있어요.{' '}
<Text onPress={() => open({ type: 'login' })} className="font-extrabold text-orange">
로그인
</Text>
</Text>
) : (
loaded && !talks.length && <Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">{tab === 'mine' ? '아직 쓴 글이 없어요. 위 칸에서 첫 글을 써 주세요.' : '아직 이 주제 글이 없어요. 위 칸에서 첫 글을 써 주세요.'}</Text>
)}
</View>
);
return (
<View className="flex-1">
<ScreenHeader title="동네 이야기" />
<FlatList
data={talks}
keyExtractor={(t) => `${t.talk_id}:${t.liked}:${t.like_count}`}
renderItem={({ item }) => <TalkCard t={item} />}
ListHeaderComponent={head}
contentContainerClassName="pb-8"
keyboardShouldPersistTaps="handled"
// 목록 끝이 가까워지면 다음 쪽을 받는다 (글이 많아도 버튼 없이 이어서)
onEndReached={() => more && loadMore()}
onEndReachedThreshold={1}
refreshControl={tab !== 'mine' ? <RefreshControl refreshing={topicList.refetching} onRefresh={() => topicList.refetch()} /> : undefined}
/>
</View>
);
}
-29
View File
@@ -1,29 +0,0 @@
import { useEffect, type ReactNode } from 'react';
import type { ViewStyle } from 'react-native';
import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
/** 하늘에서 떨어진 뒤 둥둥 (웹 b-fall: b-drop 1.05초 뒤 b-float 무한). d·f 는 밀리초 */
export function Fall({ d, f, amp = 9, style, children }: { d: number; f: number; amp?: number; style?: ViewStyle; children: ReactNode }) {
const reduce = useReducedMotion();
const drop = useSharedValue(reduce ? 1 : 0);
const float = useSharedValue(0);
useEffect(() => {
if (reduce) return;
drop.value = withDelay(d, withTiming(1, { duration: 1050, easing: Easing.bezier(0.22, 0.9, 0.3, 1) }));
float.value = withDelay(d + 1050, withRepeat(withTiming(1, { duration: f / 2, easing: Easing.inOut(Easing.ease) }), -1, true));
return () => {
cancelAnimation(drop);
cancelAnimation(float);
};
}, [reduce, d, f, drop, float]);
const anim = useAnimatedStyle(() => {
const p = drop.value;
const y = interpolate(p, [0, 0.72, 0.86, 1], [-400, 0, -10, 0]) - amp * float.value;
const rot = interpolate(p, [0, 0.72, 1], [-10, 2, 0]) + 1.2 * float.value;
return {
opacity: interpolate(p, [0, 0.55, 1], [0, 1, 1]),
transform: [{ translateY: y }, { rotate: `${rot}deg` }, { scaleX: interpolate(p, [0, 0.72, 0.86, 1], [1, 1.04, 1, 1]) }, { scaleY: interpolate(p, [0, 0.72, 0.86, 1], [1, 0.96, 1, 1]) }],
};
});
return <Animated.View style={[style, anim]}>{children}</Animated.View>;
}
-76
View File
@@ -1,76 +0,0 @@
import type { TimeKind } from '@nalssigak/shared/lib';
import { useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { StyleSheet, View } from 'react-native';
import { Text } from '@/components/text';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withSequence, withTiming } from 'react-native-reanimated';
import { Ic } from '@/components/ui';
import { useSky } from '@/lib/sky';
// 덮개 색: 시간대별 하늘 맨 위 색을 반쯤 비치게
const COVER: Record<TimeKind, string> = {
morning: 'rgb(255 230 207 / 0.72)',
day: 'rgb(214 235 255 / 0.72)',
sunset: 'rgb(255 216 194 / 0.72)',
night: 'rgb(14 20 51 / 0.72)',
};
/** 캐릭터가 통통 뛴다 (웹 b-hop) */
function Hop({ name }: { name: string }) {
const reduce = useReducedMotion();
const t = useSharedValue(0);
useEffect(() => {
if (reduce) return;
const ease = Easing.bezier(0.3, 0, 0.4, 1);
t.value = withRepeat(withSequence(withTiming(1, { duration: 405, easing: ease }), withTiming(0, { duration: 495, easing: ease })), -1);
return () => cancelAnimation(t);
}, [reduce, t]);
const style = useAnimatedStyle(() => ({
transform: [{ translateY: -22 * t.value }, { scaleX: 1.06 - 0.09 * t.value }, { scaleY: 0.94 + 0.09 * t.value }],
transformOrigin: 'bottom',
}));
return (
<Animated.View style={style}>
<Ic name={name} size={88} />
</Animated.View>
);
}
/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */
export function FirstLoad() {
const queryClient = useQueryClient();
const { kind } = useSky();
const [done, setDone] = useState(false);
const [gone, setGone] = useState(false);
// 받기 시작했다가 받는 게 없어지면 끝. 느린 망에서도 10초 넘게 막지 않는다 (그 뒤는 화면 안 스켈레톤이 맡는다)
useEffect(() => {
let seen = false;
const unsubscribe = queryClient.getQueryCache().subscribe(() => {
if (queryClient.isFetching() > 0) seen = true;
else if (seen) setDone(true);
});
const id = setTimeout(() => setDone(true), 10000);
return () => {
unsubscribe();
clearTimeout(id);
};
}, [queryClient]);
const shown = useSharedValue(1);
useEffect(() => {
if (!done) return;
shown.value = withTiming(0, { duration: 400 });
const id = setTimeout(() => setGone(true), 400);
return () => clearTimeout(id);
}, [done, shown]);
const fade = useAnimatedStyle(() => ({ opacity: shown.value }));
if (gone) return null;
return (
<Animated.View pointerEvents={done ? 'none' : 'auto'} accessibilityRole="progressbar" accessibilityLabel="날씨 불러오는 중" style={[StyleSheet.absoluteFill, { zIndex: 50, backgroundColor: COVER[kind] }, fade]}>
<View className="flex-1 items-center justify-center gap-3">
<Hop name={kind === 'night' ? 'bear' : 'rabbit'} />
<Text className="font-jua text-[19px] text-ink">날씨 불러오는 중…</Text>
</View>
</Animated.View>
);
}
@@ -1,153 +0,0 @@
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen';
import { headline, ICON_R, labelBoxes, md, nearest, placeLabels, placeProvinces, PROVINCES, rankNow, spread } from '@nalssigak/shared/lib/foliage';
import { router } from 'expo-router';
import { useEffect, useMemo, useState } from 'react';
import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';
import { Label, Legend, MapImage, MAP_INK, MAP_INK3, Marker, PAPER, Province, useLabelSizes } from '@/components/foliage/parts';
import { Pager } from '@/components/post/pager';
import { PostFrame } from '@/components/post/post-frame';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useFoliage } from '@/lib/foliage';
const RANK_N = 7;
// 지도 아래 고른 명소 줄(범례 자리) 높이
const BAR_H = 60;
// 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다
const SHIFT = 0.07;
const goMap = (spot?: string) => router.push(spot ? { pathname: '/foliage', params: { spot } } : '/foliage');
/**
* 피드의 단풍 지도 카드 (웹 FoliageCard): 1장은 지금 절정인 곳만 잎으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위.
* '지도 크게 보기'로 단풍 지도 화면. 단풍철이 아니면 그리지 않는다
*/
export function FoliageCard({ post }: { post?: PostReaction | null }) {
const { today, spots, inSeason } = useFoliage();
const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots]);
const [size, measure] = useLabelSizes();
const [W, setW] = useState(0);
const [picked, setPicked] = useState<string | null>(null);
const [index, setIndex] = useState(0);
const pts = useMemo(() => spread(peak.map((m) => ({ m, x: m.x * W, y: m.y * W, r: ICON_R }))), [peak, W]);
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W]);
const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size]);
useEffect(() => {
if (picked) track('foliage_spot', { spot_name: picked, from: 'card' });
}, [picked]);
if (!inSeason) return null;
const toggle = (name: string) => setPicked(name === picked ? null : name);
// 잎이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
const tapMap = (e: GestureResponderEvent) => {
const best = nearest(pts, e.nativeEvent.locationX, e.nativeEvent.locationY);
setPicked(best && best !== picked ? best : null);
};
const onLayout = (e: LayoutChangeEvent) => setW(e.nativeEvent.layout.width);
const sel = peak.find((m) => m.name === picked);
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
const ranked = rankNow(spots).slice(0, RANK_N);
const caption = peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined;
const pageH = W + 8 + BAR_H;
const mapPage = (
<View className="overflow-hidden" style={{ width: W, height: pageH }}>
<Pressable onPress={tapMap} accessibilityLabel="단풍 지도, 지금 절정인 곳" style={{ width: W, height: W, transform: [{ translateX: W * SHIFT }], backgroundColor: PAPER }}>
<MapImage style={{ left: 0, top: 0, width: W, height: W }} />
{provs.map((v) => (
<Province key={v.name} name={v.name} x={v.x} y={v.y} />
))}
{pts.map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === picked} />
))}
{peak.map((m) => (
<Label key={m.name} m={m} at={labelAt[m.name]} onPress={() => toggle(m.name)} onLayout={measure(m.name)} accessibilityLabel={`${m.name} 정보 보기`} />
))}
</Pressable>
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 잎을 가리지 않게 */}
{sel ? (
<View className="mt-2 flex-row items-center gap-3 rounded-[16px] bg-white px-3" style={{ height: BAR_H, boxShadow: 'inset 0 -3px 0 rgba(40,48,74,0.08)' }}>
<Ic name={sel.kind} size={32} />
<View className="min-w-0 flex-1">
<Text numberOfLines={1} className="font-jua text-[18px] leading-tight" style={{ color: MAP_INK }}>
{sel.name}
</Text>
<Text numberOfLines={1} className="text-[12px] font-bold" style={{ color: MAP_INK3 }}>
{`${sel.region.split(' ')[0]} · 절정 예상 ${md(sel.peak)}`}
</Text>
</View>
<Pressable onPress={() => goMap(sel.name)} accessibilityRole="link" className="rounded-full px-3 py-1.5" style={{ backgroundColor: MAP_INK }}>
<Text className="text-[12.5px] font-extrabold text-white">지도에서 보기 ›</Text>
</Pressable>
</View>
) : (
<View className="mt-2 items-start" style={{ height: BAR_H }}>
<Legend color={MAP_INK} />
</View>
)}
</View>
);
const rankPage = (
<View className="pl-1" style={{ width: W, height: pageH }}>
<Text className="font-jua text-[20px] leading-tight" style={{ color: MAP_INK }}>
지금 가기 좋은 곳
</Text>
<Text className="mt-0.5 text-[12px] font-bold" style={{ color: MAP_INK3 }}>
절정 예상일이 오늘과 가까운 순서예요
</Text>
<View className="mt-2 flex-1 justify-between">
{ranked.map((m, i) => (
<Pressable key={m.name} onPress={() => goMap(m.name)} accessibilityRole="link" accessibilityLabel={`${i + 1}위 ${m.name}, 절정 예상 ${md(m.peak)}`} className="flex-row items-center gap-2.5 py-1.5">
<Text className="w-6 text-center font-jua text-[22px]" style={{ color: i < 3 ? '#b5321f' : '#9a8f80' }}>
{String(i + 1)}
</Text>
<Ic name={m.kind} size={28} />
<View className="min-w-0 flex-1">
<Text numberOfLines={1} className="text-[15px] font-extrabold" style={{ color: MAP_INK }}>
{m.name}
</Text>
<Text numberOfLines={1} className="text-[12px] font-semibold" style={{ color: MAP_INK3 }}>
{m.region}
</Text>
</View>
<Text className="text-[14px] font-extrabold" style={{ color: MAP_INK, fontVariant: ['tabular-nums'] }}>
{md(m.peak)}
</Text>
</Pressable>
))}
</View>
</View>
);
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" pinned={{ key: 'foliage_post', post }} caption={caption}>
{/* 밤에도 지도 카드는 밝은 종이 그대로 (웹 b-keep-bg) */}
<View className="px-4 pt-4 pb-3" style={{ backgroundColor: PAPER }}>
<Text className="text-[13px] font-extrabold opacity-75" style={{ color: MAP_INK }}>{`단풍 지도 · ${md(today)}`}</Text>
<Text className="mt-1 font-jua text-[24px] leading-tight" style={{ color: MAP_INK }}>
{headline(spots)}
</Text>
<View className="mt-1" onLayout={onLayout}>
{W > 0 ? (
<Pager width={W} height={pageH} onIndex={setIndex}>
{[mapPage, rankPage]}
</Pager>
) : null}
<View pointerEvents="none" className="absolute top-0 right-0 rounded-full px-[9px] py-[3px]" style={{ zIndex: 4, backgroundColor: 'rgba(30,36,56,0.55)' }} accessibilityElementsHidden>
<Text className="text-xs font-extrabold text-white">{`${index + 1}/2`}</Text>
</View>
</View>
<Pressable onPress={() => goMap()} accessibilityRole="link" className="mt-2 w-full items-center rounded-full bg-white py-2" style={{ boxShadow: 'inset 0 -3px 0 rgba(40,48,74,0.08)' }}>
<Text className="text-[14px] font-extrabold" style={{ color: MAP_INK }}>
지도 크게 보기 ›
</Text>
</Pressable>
</View>
</PostFrame>
);
}
@@ -1,272 +0,0 @@
import { ICON_R, LAND_CX, labelBoxes, nearest, placeLabels, placeProvinces, PROVINCES, spread, type Box, type Spot, type Stage } from '@nalssigak/shared/lib/foliage';
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type Ref } from 'react';
import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';
import { Label, MapImage, Marker, MAP_INK, PAPER, Province, useLabelSizes } from '@/components/foliage/parts';
import { Text } from '@/components/text';
type Cam = { s: number; tx: number; ty: number };
const DOT_R: Record<Stage, number> = { peak: ICON_R, first: 4, before: 3, gone: 3 };
const MAX_ZOOM = 5;
const FIT_TOP = 30;
const FIT_BOTTOM = 14;
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3);
const LABEL_FROM = [1, 1.6, 2.5, 3.5];
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 };
const ZOOM_BTNS = [
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const;
export type FoliageMapHandle = { focus: (m: Spot) => void };
type Props = { spots: Spot[]; sel: string | null; onSelect: (name: string | null) => void; height: number; ref?: Ref<FoliageMapHandle> };
/**
* 단풍 지도 페이지의 지도: 두 손가락으로 확대·이동, 한 손가락으로 이동, 누르면 가까운 명소 고르기, 두 번 누르면 확대 (웹 FoliagePage 지도).
* 앱은 지도를 스크롤 밖에 고정해 손짓이 페이지 스크롤과 다투지 않는다
*/
export function FoliageMap({ spots, sel, onSelect, height, ref }: Props) {
const vpRef = useRef<View>(null);
const origin = useRef({ x: 0, y: 0 });
const [box, setBox] = useState({ W: 0, H: 0 });
const [view, setView] = useState<Cam>({ s: 1, tx: 0, ty: 0 });
const viewRef = useRef(view);
useLayoutEffect(() => {
viewRef.current = view;
}, [view]);
const [size, measure] = useLabelSizes();
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<Cam>(() => {
const { W, H } = box;
if (!W || !spots.length) return { s: 1, tx: 0, ty: 0 };
const xs = spots.map((m) => m.x);
const ys = spots.map((m) => m.y);
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
const h = H - FIT_TOP - FIT_BOTTOM;
// 가로는 땅 가운데(LAND_CX)에 맞추되 동·서 끝 명소가 다 들어오게
const half = Math.max(LAND_CX - x0, x1 - LAND_CX) + 0.07;
const s = Math.min(W / (2 * half * W), h / ((y1 - y0) * W));
return { s, tx: W / 2 - LAND_CX * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s };
}, [box, spots]);
const clamp = useCallback(
(v: Cam): Cam => {
const { W, H } = box;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s));
const w = W * s;
// 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게
const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx));
const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty));
return { s, tx, ty };
},
[box, fit],
);
const anim = useRef(0);
const set = useCallback((v: Cam) => {
cancelAnimationFrame(anim.current);
setView(v);
}, []);
const animateTo = useCallback(
(to: Cam) => {
cancelAnimationFrame(anim.current);
const from = viewRef.current;
const target = clamp(to);
const start = performance.now();
const step = (now: number) => {
const k = Math.min(1, (now - start) / 280);
const e = 1 - (1 - k) ** 3;
setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e });
if (k < 1) anim.current = requestAnimationFrame(step);
};
anim.current = requestAnimationFrame(step);
},
[clamp],
);
const zoomAt = useCallback(
(f: number, cx: number, cy: number, smooth = false) => {
const v = viewRef.current;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f));
const k = s / v.s;
const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k });
if (smooth) animateTo(next);
else set(next);
},
[fit, clamp, animateTo, set],
);
const focus = useCallback(
(m: Spot) => {
const { W, H } = box;
const s = Math.max(viewRef.current.s, fit.s * 2.5);
animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s });
},
[box, fit, animateTo],
);
useImperativeHandle(ref, () => ({ focus }), [focus]);
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로. 그 뒤 크기가 바뀌면 지금 화면을 범위 안으로
const started = useRef(false);
const linked = useRef(sel);
useEffect(() => {
if (!box.W) return;
if (started.current) {
set(clamp(viewRef.current));
return;
}
started.current = true;
set(fit);
const m = spots.find((s) => s.name === linked.current);
if (m) focus(m);
}, [box, fit, spots, set, clamp, focus]);
useEffect(() => () => cancelAnimationFrame(anim.current), []);
const pts = useMemo(() => {
const ratio = view.s / fit.s;
const visible = spots.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01);
return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] })));
}, [spots, view, box.W, fit.s, sel]);
const ptsRef = useRef(pts);
useLayoutEffect(() => {
ptsRef.current = pts;
}, [pts]);
const labelAt = useMemo(() => {
const ratio = view.s / fit.s;
const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m));
// 오른쪽 위 +/− 단추 자리는 비운다
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }];
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel);
}, [pts, size, sel, view.s, fit.s, box]);
const provs = useMemo(
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
[view, box.W, pts, labelAt, size],
);
// 손짓 상태: 두 손가락 거리·가운데, 한 손가락 시작점과 움직였는지, 마지막으로 누른 때(두 번 누르기)
const gesture = useRef<{ pinch: { d: number; x: number; y: number } | null; one: { x: number; y: number; moved: boolean } | null; lastTap: number }>({ pinch: null, one: null, lastTap: 0 });
const local = (t: { pageX: number; pageY: number }) => ({ x: t.pageX - origin.current.x, y: t.pageY - origin.current.y });
const pickAt = (x: number, y: number) => {
const best = nearest(ptsRef.current, x, y);
onSelect(best && best !== sel ? best : null);
};
const begin = (e: GestureResponderEvent) => {
const g = gesture.current;
const ts = e.nativeEvent.touches;
if (ts.length >= 2) {
const [a, b] = [local(ts[0]), local(ts[1])];
g.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
g.one = null;
} else if (ts.length === 1) {
g.pinch = null;
g.one = { ...local(ts[0]), moved: false };
}
};
const onGrant = (e: GestureResponderEvent) => {
cancelAnimationFrame(anim.current);
// 지도 칸의 화면 위치: 손가락 좌표(pageX)를 지도 안 좌표로 바꾸는 데 쓴다
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
origin.current = { x: px, y: py };
});
begin(e);
};
const onMove = (e: GestureResponderEvent) => {
const g = gesture.current;
const ts = e.nativeEvent.touches;
if (ts.length >= 2) {
if (!g.pinch) return begin(e);
const [a, b] = [local(ts[0]), local(ts[1])];
const d = Math.hypot(a.x - b.x, a.y - b.y);
const x = (a.x + b.x) / 2;
const y = (a.y + b.y) / 2;
const v = viewRef.current;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / g.pinch.d));
const k = s / v.s;
set(clamp({ s, tx: x - (g.pinch.x - v.tx) * k, ty: y - (g.pinch.y - v.ty) * k }));
g.pinch = { d, x, y };
return;
}
// 두 손가락에서 한 손가락이 떨어지면 남은 손가락으로 이어서 이동 (누르기로는 안 친다)
if (!g.one || g.pinch) {
if (ts.length === 1) g.one = { ...local(ts[0]), moved: true };
g.pinch = null;
return;
}
const p = local(ts[0]);
if (Math.hypot(p.x - g.one.x, p.y - g.one.y) > 6) g.one.moved = true;
if (!g.one.moved) return;
const v = viewRef.current;
set(clamp({ s: v.s, tx: v.tx + p.x - g.one.x, ty: v.ty + p.y - g.one.y }));
g.one = { ...p, moved: true };
};
const onRelease = (e: GestureResponderEvent) => {
const g = gesture.current;
const tap = g.one && !g.one.moved ? g.one : null;
g.one = null;
g.pinch = null;
if (!tap) return;
// 두 번 누르기: 300ms 안에 또 누르면 확대
if (e.nativeEvent.timestamp - g.lastTap < 300) {
g.lastTap = 0;
zoomAt(2, tap.x, tap.y, true);
} else {
g.lastTap = e.nativeEvent.timestamp;
pickAt(tap.x, tap.y);
}
};
const onEnd = () => {
gesture.current.one = null;
gesture.current.pinch = null;
};
const onLayout = (e: LayoutChangeEvent) => {
const { width, height: h } = e.nativeEvent.layout;
setBox({ W: width, H: h });
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
origin.current = { x: px, y: py };
});
};
const markers = [...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak'));
return (
<View
ref={vpRef}
onLayout={onLayout}
onStartShouldSetResponder={() => true}
onMoveShouldSetResponder={() => true}
onResponderTerminationRequest={() => false}
onResponderGrant={onGrant}
onResponderMove={onMove}
onResponderRelease={onRelease}
onResponderTerminate={onEnd}
className="overflow-hidden"
style={{ height, backgroundColor: PAPER }}
accessibilityLabel="단풍 지도"
>
{box.W > 0 ? <MapImage style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} /> : null}
{provs.map((v) => (
<Province key={v.name} name={v.name} x={v.x} y={v.y} />
))}
{markers.map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<Label key={m.name} m={m} at={labelAt[m.name]} sel={m.name === sel} onPress={() => onSelect(m.name === sel ? null : m.name)} onLayout={measure(m.name)} accessibilityLabel={`${m.name} 고르기`} />
))}
<View className="absolute top-2.5 right-2.5 gap-2" style={{ zIndex: 4 }}>
{ZOOM_BTNS.map(([t, label, f]) => (
<Pressable key={t} onPress={() => zoomAt(f, box.W / 2, box.H / 2, true)} accessibilityRole="button" accessibilityLabel={label} className="size-9 items-center justify-center rounded-full bg-white" style={{ boxShadow: '0 2px 6px rgba(40,48,74,0.2)' }}>
<Text className="text-[20px] leading-6 font-bold" style={{ color: MAP_INK }}>
{t}
</Text>
</Pressable>
))}
</View>
</View>
);
}
-135
View File
@@ -1,135 +0,0 @@
import type { Kind, LabelSize, Pt, Spot, Stage } from '@nalssigak/shared/lib/foliage';
import { Image } from 'expo-image';
import { useCallback, useRef, useState, type ReactNode } from 'react';
import { Platform, Pressable, View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from 'react-native';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { MAP_IMAGE } from '@/lib/foliage';
// 지도는 밤에도 밝은 종이 그대로 (웹 b-keep-bg)
export const PAPER = '#fff6ea';
export const MAP_INK = '#28304a';
export const MAP_INK3 = '#6b7189';
const LABEL_INK: Record<Kind, string> = { maple: '#b5321f', ginkgo: '#8a6508' };
/**
* 지도 그림. 웹은 채도를 빼서(saturate .3) 잎 아이콘이 묻히지 않게 한다.
* 안드로이드는 같은 filter, iOS 는 filter 의 채도를 못 써서 종이색을 반쯤 덮어 옅게 한다
*/
export function MapImage({ style }: { style: StyleProp<ViewStyle> }) {
const android = Platform.OS === 'android';
return (
<View pointerEvents="none" style={[{ position: 'absolute' }, style, android ? { filter: [{ saturate: 0.3 }, { brightness: 1.08 }] } : null]}>
<Image source={MAP_IMAGE} style={{ width: '100%', height: '100%' }} contentFit="contain" accessibilityIgnoresInvertColors />
{!android && <View style={{ position: 'absolute', inset: 0, backgroundColor: PAPER, opacity: 0.5 }} />}
</View>
);
}
const DOT: Record<Exclude<Stage, 'peak'>, { size: number; color: string }> = {
first: { size: 7, color: 'rgba(217,119,46,0.85)' },
before: { size: 5, color: 'rgba(143,138,128,0.6)' },
gone: { size: 5, color: 'rgba(143,138,128,0.6)' },
};
/** 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(big 이면 점을 크게) */
export function StageMark({ m, big }: { m: Spot; big?: boolean }) {
if (m.stage === 'peak') return <Ic name={m.kind} size={big ? 32 : 20} />;
const dot = DOT[m.stage];
const size = big ? 14 : dot.size;
return <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: dot.color }} />;
}
/** 지도 위 점·잎. 고른 명소는 속이 빈 고리만 둘러 옆 명소를 가리지 않게 */
export function Marker({ p, sel }: { p: Pt; sel: boolean }) {
return (
<View pointerEvents="none" className="absolute size-8 items-center justify-center" style={{ left: p.x - 16, top: p.y - 16, zIndex: sel ? 3 : 1 }}>
{sel ? <View className="absolute size-8 rounded-full border-[2.5px]" style={{ borderColor: MAP_INK, backgroundColor: 'rgba(255,255,255,0.3)' }} /> : null}
<StageMark m={p.m} big={sel && p.m.stage !== 'peak'} />
</View>
);
}
/** 시·도 이름: 지도에 옅게 깔리는 글자. 산 무늬 위에서도 읽히게 종이색 번짐을 두른다 */
export function Province({ name, x, y }: { name: string; x: number; y: number }) {
return (
<View pointerEvents="none" className="absolute w-10 items-center" style={{ left: x - 20, top: y - 8 }} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
<Text className="font-jua text-[13px] leading-4" style={{ color: 'rgba(92,74,54,0.85)', textShadowColor: PAPER, textShadowRadius: 4 }}>
{name}
</Text>
</View>
);
}
/**
* 명소 이름표. 자리를 못 받았으면(at 없음) 숨긴 채 왼쪽 위에 두고 크기만 잰다 (웹 useLabelSize 대신 onLayout).
* tone: 고름(진한 바탕) · 절정(잎 색 글자) · 그 밖(회색 글자)
*/
export function Label({ m, at, sel, onPress, onLayout, accessibilityLabel }: { m: Spot; at?: { left: number; top: number }; sel?: boolean; onPress: () => void; onLayout: (e: LayoutChangeEvent) => void; accessibilityLabel: string }) {
const color = sel ? '#ffffff' : m.stage === 'peak' ? LABEL_INK[m.kind] : '#5b6075';
return (
<Pressable
onPress={onPress}
onLayout={onLayout}
disabled={!at}
hitSlop={{ top: 8, bottom: 8, left: 4, right: 4 }}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
accessibilityElementsHidden={!at}
importantForAccessibility={at ? 'auto' : 'no-hide-descendants'}
className="absolute rounded-[7px] px-[5px] py-px"
style={{
left: at?.left ?? 0,
top: at?.top ?? 0,
opacity: at ? 1 : 0,
zIndex: sel ? 3 : 2,
backgroundColor: sel ? MAP_INK : 'rgba(255,255,255,0.92)',
boxShadow: '0 1px 3px rgba(40,48,74,0.18)',
}}
>
<Text numberOfLines={1} className="text-[11.5px] leading-[15.5px] font-extrabold" style={{ color }}>
{m.name}
</Text>
</Pressable>
);
}
/** 이름표 크기 모으기: Label 의 onLayout 을 받아 이름별 폭·높이. 한 프레임에 한 번만 다시 그린다 */
export function useLabelSizes() {
const [size, setSize] = useState<LabelSize>({});
const acc = useRef<LabelSize>({});
const frame = useRef(0);
const measure = useCallback(
(name: string) => (e: LayoutChangeEvent) => {
const { width: w, height: h } = e.nativeEvent.layout;
const old = acc.current[name];
if (old && Math.abs(old.w - w) < 0.5 && Math.abs(old.h - h) < 0.5) return;
acc.current = { ...acc.current, [name]: { w, h } };
cancelAnimationFrame(frame.current);
frame.current = requestAnimationFrame(() => setSize(acc.current));
},
[],
);
return [size, measure] as const;
}
/** 범례: 절정 잎 둘, full 이면 첫 단풍·단풍 전 점까지 */
export function Legend({ full, color }: { full?: boolean; color: string }) {
const item = (mark: ReactNode, label: string) => (
<View key={label} className="flex-row items-center gap-1">
{mark}
<Text className="text-[12.5px] font-bold" style={{ color }}>
{label}
</Text>
</View>
);
return (
<View className="h-[52px] flex-row flex-wrap items-center justify-center gap-x-3 gap-y-1">
{item(<Ic name="maple" size={16} />, '단풍 절정')}
{item(<Ic name="ginkgo" size={16} />, '은행 절정')}
{full ? item(<View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: DOT.first.color }} />, '첫 단풍') : null}
{full ? item(<View style={{ width: 5, height: 5, borderRadius: 3, backgroundColor: DOT.before.color }} />, '단풍 전') : null}
</View>
);
}
@@ -1,93 +0,0 @@
import { md, STAGE, type Spot, type Stage } from '@nalssigak/shared/lib/foliage';
import { Pressable, View } from 'react-native';
import { Legend, StageMark } from '@/components/foliage/parts';
import { Text } from '@/components/text';
const GROUPS: [Stage, string][] = [
['peak', '지금 절정'],
['first', '곧 절정'],
['before', '아직'],
['gone', '절정 지남'],
];
const CHIP: Partial<Record<Stage, { bg: string; ink: string }>> = {
peak: { bg: '#ffe3db', ink: '#b5321f' },
first: { bg: '#ffe8d2', ink: '#a34f12' },
};
/** 지도 아래 한 줄: 고른 명소가 있으면 그 명소 정보, 없으면 범례 (지도 위를 가리지 않게 범례 자리에) */
export function ChosenBar({ chosen, legendColor }: { chosen?: Spot; legendColor: string }) {
if (!chosen)
return (
<View className="mx-3 mt-2 h-[60px] justify-center">
<Legend full color={legendColor} />
</View>
);
const chip = CHIP[chosen.stage];
return (
<View className="mx-3 mt-2 h-[60px] flex-row items-center gap-3 rounded-[18px] border-b-4 border-shade bg-card px-3.5">
<View className="size-8 items-center justify-center">
<StageMark m={chosen} big />
</View>
<View className="min-w-0 flex-1">
<View className="flex-row items-center gap-1.5">
<Text numberOfLines={1} className="shrink font-jua text-[18px] text-ink">
{chosen.name}
</Text>
<Text className={`overflow-hidden rounded-full px-1.5 py-px text-[11px] font-extrabold ${chip ? '' : 'bg-chip text-ink2'}`} style={chip ? { backgroundColor: chip.bg, color: chip.ink } : undefined}>
{STAGE[chosen.stage]}
</Text>
</View>
<Text numberOfLines={1} className="text-[12px] font-bold text-ink3">
{`${chosen.region} · 절정 예상 ${md(chosen.peak)}`}
</Text>
</View>
</View>
);
}
/** 단계별 명소 목록 (지금 절정 · 곧 절정 · 아직 · 절정 지남). 누르면 지도에서 그 명소로 */
export function SpotList({ spots, sel, onPick }: { spots: Spot[]; sel: string | null; onPick: (m: Spot) => void }) {
return (
<View className="px-4">
{GROUPS.map(([g, title]) => {
const rows = spots.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak));
if (!rows.length) return null;
return (
<View key={g} accessibilityLabel={title} className="pt-5">
<View className="flex-row items-baseline gap-1.5 px-1 pb-1.5">
<Text className="font-jua text-[19px] text-ink">{title}</Text>
<Text className="text-[13px] font-extrabold text-ink3">{`${rows.length}곳`}</Text>
</View>
<View className="border-t border-line">
{rows.map((m) => (
<Pressable
key={m.name}
onPress={() => onPick(m)}
accessibilityRole="button"
accessibilityState={{ selected: m.name === sel }}
className="flex-row items-center gap-3 border-b border-line py-2.5 pl-1"
style={m.name === sel ? { backgroundColor: 'rgba(255,122,69,0.08)' } : undefined}
>
<View className="size-7 items-center justify-center">
<StageMark m={m} big />
</View>
<View className="min-w-0 flex-1">
<Text numberOfLines={1} className="text-[15px] font-extrabold text-ink">
{m.name}
</Text>
<Text numberOfLines={1} className="text-[12px] font-semibold text-ink3">
{`${m.region} · ${m.own ? '절정 예상' : '가까운 지점 날짜'}`}
</Text>
</View>
<Text className={`pr-1 font-jua text-[18px] ${g === 'peak' ? 'text-orange' : 'text-ink2'}`}>{md(m.peak)}</Text>
</Pressable>
))}
</View>
</View>
);
})}
</View>
);
}
-52
View File
@@ -1,52 +0,0 @@
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Skel } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
const CELL = 'w-[32%] items-center rounded-[22px] border-b-[5px] border-shade bg-card px-1.5 pt-3 pb-2.5';
const SKELS = Array.from({ length: 9 }, (_, i) => i);
export function GridSkel() {
return (
<View className="flex-row flex-wrap justify-between gap-y-2 p-3">
{SKELS.map((i) => (
<View key={i} className={`${CELL} gap-1.5`}>
<View className="size-[50px] rounded-full bg-skel" />
<Skel className="w-14" />
<Skel className="h-5 w-8" />
</View>
))}
</View>
);
}
/** 3칸 바둑판. 지금 시간대가 아니거나 제철이 아닌 각은 흐리게 */
export function GakGrid({ items, dim }: { items: IndexSummary[]; dim: boolean }) {
const { open } = useSheet();
return (
<View className="flex-row flex-wrap gap-y-2 p-3" style={{ columnGap: '2%', opacity: dim ? 0.6 : 1 }}>
{items.map((g) => (
<Pressable
key={g.index_id}
onPress={() => open({ type: 'gak', indexId: g.index_id })}
accessibilityLabel={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, ${g.in_season === false ? '제철 아님' : '지금 시간대 아님'}`}
className={`${CELL} ${g.active ? '' : 'opacity-55'}`}
>
{g.active && <Text className="absolute top-[7px] left-[9px] font-jua text-[13px] text-ink3">{g.rank}</Text>}
{!!g.season && <Text className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</Text>}
<Ic name={g.icon} size={50} />
<Text numberOfLines={1} className="mt-1 font-jua text-[15px] text-ink">
{g.name}
</Text>
{g.active ? (
<Text className={`font-bagel text-[22px] leading-[24px] ${g.score < 50 ? 'text-ink3' : 'text-orange'}`}>{g.score}</Text>
) : (
<Text className="py-1 text-[12px] leading-[14px] font-extrabold text-ink3">{g.in_season === false ? '제철 아님' : '지금 아님'}</Text>
)}
</Pressable>
))}
</View>
);
}
-57
View File
@@ -1,57 +0,0 @@
import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen';
import { MEDALS } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Skel } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
// 가운데가 높은 3칸: 2위 · 1위 · 3위
const ORDER = [1, 0, 2] as const;
const FLEX = [1.15, 1, 1];
/** 1~3위 받침대와 같은 칸의 스켈레톤 */
export function PodiumSkel() {
return (
<View className="flex-row gap-1.5 px-3 pt-3">
{ORDER.map((k) => (
<View key={k} style={{ flex: FLEX[k] }} className={`items-center gap-1.5 rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
<View className={`aspect-square rounded-full bg-skel ${k === 0 ? 'w-20' : 'w-[62px]'}`} />
<Skel className="w-16" />
<Skel className="h-6 w-10" />
<Skel className="w-full" />
</View>
))}
</View>
);
}
export function Podium({ top, dim }: { top: IndexSummary[]; dim: boolean }) {
const { open } = useSheet();
const { kind } = useSky();
return (
<View className="flex-row gap-1.5 px-3 pt-3" style={{ opacity: dim ? 0.6 : 1 }}>
{ORDER.map((k) => {
const g = top[k];
return (
<Pressable key={g.index_id} style={{ flex: FLEX[k] }} onPress={() => open({ type: 'gak', indexId: g.index_id })} className={`items-center overflow-hidden rounded-3xl border-b-[6px] border-shade bg-card px-1.5 ${k === 0 ? 'py-4' : 'mt-6 py-3'}`}>
{k === 0 && kind !== 'night' && <LinearGradient colors={['#fff1c4', '#ffffff']} style={{ position: 'absolute', inset: 0 }} />}
<View>
<Ic name={g.icon} size={k === 0 ? 80 : 62} />
<Ic name={MEDALS[k]} size={28} style={{ position: 'absolute', top: -6, left: -12 }} />
</View>
<View className="mt-1.5 flex-1 justify-center">
<Text className="text-center font-jua text-base text-ink">
{k + 1}위 {g.name}
</Text>
</View>
<Text className="font-bagel text-[30px] leading-[32px] text-orange">{g.score}</Text>
{!!g.summary && <Text className="text-center text-[11.5px] font-semibold text-ink2">{g.summary}</Text>}
</Pressable>
);
})}
</View>
);
}
-79
View File
@@ -1,79 +0,0 @@
import { moonPath } from '@nalssigak/shared/lib/today';
import { useId } from 'react';
import Svg, { Circle, ClipPath, Defs, Ellipse, FeGaussianBlur, Filter, G, Path, RadialGradient, Stop } from 'react-native-svg';
// 앞면 바다(어두운 무늬) 자리: [x, y, 가로 반지름, 세로 반지름]. 실제 달 앞면 배치를 대강 따른다 (웹 frontend/src/b/moon.tsx 와 같다)
const MARIA: [number, number, number, number][] = [
[-0.32, -0.36, 0.3, 0.26],
[0.12, -0.36, 0.17, 0.15],
[0.3, -0.06, 0.2, 0.17],
[-0.56, 0.06, 0.26, 0.42],
[0.66, -0.26, 0.1, 0.12],
[0.52, 0.22, 0.13, 0.15],
[-0.14, 0.44, 0.18, 0.13],
[-0.46, 0.5, 0.1, 0.09],
];
// 작은 크레이터: [x, y, 반지름]
const CRATERS: [number, number, number][] = [
[0.1, 0.72, 0.07],
[0.42, 0.52, 0.05],
[-0.66, -0.5, 0.05],
[0.62, 0.52, 0.04],
[-0.2, 0.08, 0.04],
];
// 저녁(노을)엔 노을빛이 도는 달, 밤엔 하얀 달
const TONES = {
night: { body: ['#fffcf2', '#f6ebcb', '#e0cc98'], shade: '#1a2050' },
dusk: { body: ['#fff8ee', '#ffe2cc', '#f2b9a2'], shade: '#4a2a63' },
};
/** 오늘 밤 실제 모양대로 그린 달. pct 는 빛나는 면의 비율 0~100, 기우는 달은 왼쪽이 밝다. 빛 번짐까지 그려서 달 지름은 size 의 2/3 */
export function MoonArt({ pct, waxing, tone = 'night', size }: { pct: number; waxing: boolean; tone?: keyof typeof TONES; size: number }) {
const id = useId().replace(/[^a-zA-Z0-9]/g, '');
const t = TONES[tone];
const k = pct / 100;
const full = pct >= 99;
const hidden = pct <= 1;
return (
<Svg viewBox="-1.5 -1.5 3 3" width={size} height={size} pointerEvents="none">
<Defs>
<RadialGradient id={`${id}glow`} cx="0" cy="0" r="1.5" gradientUnits="userSpaceOnUse">
<Stop offset="0.6" stopColor="#fff4cf" stopOpacity={0.55} />
<Stop offset="0.8" stopColor="#ffe9a8" stopOpacity={0.16} />
<Stop offset="1" stopColor="#ffe9a8" stopOpacity={0} />
</RadialGradient>
<RadialGradient id={`${id}body`} cx="-0.2" cy="-0.28" r="1.44" gradientUnits="userSpaceOnUse">
<Stop offset="0" stopColor={t.body[0]} />
<Stop offset="0.6" stopColor={t.body[1]} />
<Stop offset="1" stopColor={t.body[2]} />
</RadialGradient>
<RadialGradient id={`${id}limb`} cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse">
<Stop offset="0.72" stopColor="#8a6f3c" stopOpacity={0} />
<Stop offset="1" stopColor="#8a6f3c" stopOpacity={0.28} />
</RadialGradient>
<ClipPath id={`${id}disc`}>
<Circle r="1" />
</ClipPath>
<Filter id={`${id}soft`} x="-0.2" y="-0.2" width="1.4" height="1.4">
<FeGaussianBlur stdDeviation="0.035" />
</Filter>
</Defs>
{!hidden && <Circle r="1.5" fill={`url(#${id}glow)`} opacity={full ? 1 : 0.12 + 0.8 * k} />}
<G clipPath={`url(#${id}disc)`}>
<Circle r="1" fill={`url(#${id}body)`} />
<G filter={`url(#${id}soft)`} fill="#c4b287" opacity={0.55}>
{MARIA.map(([x, y, rx, ry]) => (
<Ellipse key={`${x},${y}`} cx={x} cy={y} rx={rx} ry={ry} />
))}
</G>
{CRATERS.map(([x, y, r]) => (
<Circle key={`${x},${y}`} cx={x} cy={y} r={r} fill="#efe2bd" stroke="#cdbb8c" strokeWidth={0.018} opacity={0.8} />
))}
<Circle r="1" fill={`url(#${id}limb)`} />
{/* 안 보이는 쪽: 흐릿한 경계로 덮고, 땅빛(지구조) 정도만 비치게 */}
{!full && <Path d={moonPath(pct, 1.04, false)} fill={t.shade} opacity={0.94} filter={`url(#${id}soft)`} transform={waxing ? undefined : 'scale(-1,1)'} />}
</G>
{hidden && <Circle r="1" fill="none" stroke="#fff" strokeOpacity={0.18} strokeWidth={0.025} />}
</Svg>
);
}
-362
View File
@@ -1,362 +0,0 @@
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 <Text className={`ml-auto font-bagel ${big ? 'text-[36px] leading-[38px]' : 'text-[28px] leading-[30px]'} ${v == null || v < 50 ? 'text-ink3' : 'text-orange'}`}>{v ?? '–'}</Text>;
}
function Reasons({ s }: { s?: MyGakScore }) {
if (!s?.slot) return <Text className="text-[12.5px] font-semibold text-ink3">예보를 불러오는 중이에요</Text>;
return (
<Text className="text-[12.5px] leading-snug font-semibold text-ink2">
<Text className="font-extrabold text-ink">{SLOT_WORD[s.slot as Slot]} </Text>
{s.reasons?.join(' · ')}
</Text>
);
}
// 조건 이름. 점수 응답의 factors 와 reasons 는 같은 순서다
const AXIS_NAME: Record<string, string> = { 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 (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail>
{items.map((g, i) => {
const s = scores[i];
const miss = conditions(s)
.filter((c) => c.value < SHORT)
.slice(0, 2);
return (
<Pressable key={g.id ?? 'local'} onPress={() => 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">
<View className="flex-row items-start justify-between">
<Ic name={g.icon ?? MY_GAK_ICON} size={40} />
<Score s={s} big />
</View>
<View>
<Text className="font-jua text-[17px] leading-tight text-ink">{g.name}</Text>
<Text className="text-xs font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'}</Text>
</View>
{!!s?.slot && (
<View className="flex-row flex-wrap gap-1">
{miss.length ? (
miss.map((c) => (
<Text key={c.axis} className="overflow-hidden rounded-full bg-[#ffe8dc] px-2 py-0.5 text-[11.5px] font-extrabold text-[#c2471b]">
{c.short}
</Text>
))
) : (
<Text className="overflow-hidden rounded-full bg-[#dff5ea] px-2 py-0.5 text-[11.5px] font-extrabold text-[#1f7a4f]">조건 다 맞아요</Text>
)}
</View>
)}
</Pressable>
);
})}
<Pressable onPress={() => open({ type: 'mix' })} accessibilityRole="button" className="w-[120px] items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-line p-3">
<Text className="font-jua text-[26px] leading-[28px] text-ink2">+</Text>
<Text className="font-jua text-[15px] text-ink2">내 각 만들기</Text>
</Pressable>
</Rail>
</>
);
}
/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기·지우기 */
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<View>(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 (
<Body>
<View ref={shot} collapsable={false} className="bg-card">
<View className="flex-row items-center gap-3">
<Ic name={gak.icon ?? MY_GAK_ICON} size={56} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[22px] leading-tight text-ink">{gak.name}</Text>
<Text className="text-[12.5px] font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'}</Text>
</View>
<Score s={s} big />
</View>
<View className="mt-3 flex-row gap-1.5" accessibilityLabel="시간대별 점수">
{SLOTS.map(([k, word]) => {
const v = s?.slots?.[k];
return (
<View key={k} className="flex-1 items-center rounded-2xl px-1 py-2" style={{ backgroundColor: s?.slot === k ? soft.warm : soft.soft }}>
<Text className="text-xs font-extrabold text-ink2">{word}</Text>
<Text className={`font-bagel text-xl ${v != null ? 'text-orange' : 'text-ink3'}`}>{v ?? '–'}</Text>
</View>
);
})}
</View>
<View className="mt-3.5 gap-2.5">
{rows.map((c) => (
<View key={c.axis}>
<View className="flex-row items-center gap-2.5">
<Text className="w-16 text-[13.5px] font-bold text-ink">{c.label}</Text>
<View className="h-[9px] flex-1 overflow-hidden rounded-full" style={{ backgroundColor: soft.bar }}>
<LinearGradient colors={['#ffc86e', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${c.value}%` }} />
</View>
<Text className="w-8 text-right text-xs font-bold text-ink2">{c.value}</Text>
</View>
<Text className="ml-[74px] text-[12.5px] font-semibold text-ink2">{c.note}</Text>
</View>
))}
</View>
</View>
<View className="mt-4 flex-row gap-2">
<Pressable onPress={share} className="flex-1 rounded-2xl bg-orange py-3">
<Text className="text-center font-jua text-[16px] text-white">공유하기</Text>
</Pressable>
{confirm ? (
<>
<Pressable
onPress={() => {
remove(gak);
onDone();
}}
className="rounded-2xl bg-[#fdecec] px-4 py-3"
>
<Text className="font-jua text-[16px] text-heart">지우기</Text>
</Pressable>
<Pressable onPress={() => setConfirm(false)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
<Text className="font-jua text-[16px] text-[#5a6380]">취소</Text>
</Pressable>
</>
) : (
<Pressable onPress={() => setConfirm(true)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
<Text className="font-jua text-[16px] text-[#5a6380]">지우기</Text>
</Pressable>
)}
</View>
{confirm && <Text className="mt-1.5 text-right text-[12.5px] font-bold text-ink2">지울까요?</Text>}
</Body>
);
}
function Row({ label, on, onToggle, disabled, children }: { label: string; on: boolean; onToggle: () => void; disabled?: boolean; children: ReactNode }) {
return (
<View className={`min-h-[44px] flex-row flex-wrap items-center gap-2 border-b border-line py-2 ${on ? '' : 'opacity-60'}`}>
<Pressable onPress={onToggle} disabled={disabled} accessibilityRole="checkbox" accessibilityState={{ checked: on }} className="w-[84px] flex-row items-center gap-1.5">
<View className={`size-4 items-center justify-center rounded-[4px] border-2 ${on ? 'border-orange bg-orange' : 'border-ink3'}`}>{on && <Text className="text-[10px] leading-3 font-extrabold text-white">✓</Text>}</View>
<Text className="text-[14px] font-extrabold text-ink">{label}</Text>
</Pressable>
{on ? <View className="min-w-0 flex-1 flex-row flex-wrap items-center gap-1.5">{children}</View> : <Text className="text-[13px] font-semibold text-ink3">상관없음</Text>}
</View>
);
}
/** 숫자: 휴대폰 숫자 자판엔 '-'가 없을 때가 있어 −/+ 버튼으로 바꾼다 */
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 (
<View className="flex-row items-center overflow-hidden rounded-xl" style={{ backgroundColor: soft.soft }} accessibilityLabel={label}>
<Pressable onPress={() => set(value - step)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-2 py-1.5 disabled:opacity-30">
<Text className="text-[15px] font-extrabold text-ink2">−</Text>
</Pressable>
<Text className="min-w-[28px] text-center text-[13.5px] font-bold text-ink">{value}</Text>
<Pressable onPress={() => set(value + step)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-2 py-1.5 disabled:opacity-30">
<Text className="text-[15px] font-extrabold text-ink2">+</Text>
</Pressable>
</View>
);
}
function Choice<T extends string>({ value, options, onChange, label, disabled }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string; disabled?: boolean }) {
return (
<View className="flex-row gap-1" accessibilityRole="radiogroup" accessibilityLabel={label}>
{options.map(([k, word]) => (
<Pressable key={k} onPress={() => onChange(k)} disabled={disabled} accessibilityRole="radio" accessibilityState={{ checked: value === k }} className={`rounded-full px-3 py-1.5 ${value === k ? 'bg-orange' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[13.5px] font-bold ${value === k ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
</Pressable>
))}
</View>
);
}
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> };
const DEFAULT_RULE: Filled<MyGakRule> = { 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<Cond, boolean> => ({ 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 (
<View className="mt-3">
<Text className="font-jua text-[19px] text-ink">아이콘</Text>
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-1.5 px-4 pt-2 pb-1">
{icons.map((icon) => (
<Pressable key={icon} onPress={() => 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 }}>
<Ic name={icon} size={32} />
</Pressable>
))}
</ScrollView>
</View>
);
}
/** 있는 각을 골라 그 각 조건으로 채운다 */
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const soft = useSoft();
const items = usePresets().data ?? [];
if (!items.length) return null;
return (
<View className="mb-3">
<Text className="font-jua text-[19px] text-ink">있는 각에서 불러오기</Text>
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-2.5 px-4 pt-2 pb-1">
{items.map((p) => (
<Pressable key={p.code} onPress={() => 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 }}>
<Ic name={p.icon} size={36} />
<Text numberOfLines={1} className={`text-[12px] leading-tight font-extrabold ${picked === p.code ? 'text-white' : 'text-ink2'}`}>
{p.name}
</Text>
</Pressable>
))}
</ScrollView>
</View>
);
}
/** 내 각 만들기(이름과 조건)와 미리보기. 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<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false });
const [picked, setPicked] = useState<string | null>(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 extends keyof typeof vals>(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<MyGakRule>) };
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 (
<Body>
{shared ? (
<Text className="text-[13px] font-bold text-ink2">친구가 보낸 각이에요. {region.name} 기준 점수예요</Text>
) : (
<>
<PresetPicker picked={picked} onPick={pick} />
<Text className="font-jua text-[19px] text-ink">이름</Text>
<TextInput value={name} onChangeText={setName} maxLength={11} placeholder="소맥, 야독, 새우깡" placeholderTextColor={soft.placeholder} accessibilityLabel="이름" className="mt-1.5 rounded-2xl px-3.5 py-2.5 text-[15px] text-ink" style={{ backgroundColor: soft.soft }} />
<IconPicker value={icon} onPick={setIcon} />
</>
)}
<Text className="mt-3 font-jua text-[19px] text-ink">조건</Text>
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')} disabled={lock}>
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [v, vals.temp[1]])} />
<Text className="text-[13.5px] font-bold text-ink">~</Text>
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [vals.temp[0], v])} />
<Text className="text-[13.5px] font-bold text-ink">° 체감</Text>
</Row>
<Row label="비" on={on.rain} onToggle={() => toggle('rain')} disabled={lock}>
<Choice
label="비"
value={vals.rain}
disabled={lock}
onChange={(v) => set('rain', v)}
options={[
['dry', '안 와야'],
['wet', '와야'],
]}
/>
</Row>
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')} disabled={lock}>
<Text className="text-[13.5px] font-bold text-ink">초속</Text>
<Num label="바람 상한" value={vals.wind_max} min={1} max={20} disabled={lock} onChange={(v) => set('wind_max', v)} />
<Text className="text-[13.5px] font-bold text-ink">m 이하</Text>
</Row>
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')} disabled={lock}>
<Choice
label="미세먼지"
value={vals.air}
disabled={lock}
onChange={(v) => set('air', v)}
options={[
['good', '좋음만'],
['normal', '보통까지'],
]}
/>
</Row>
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')} disabled={lock}>
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />
<Text className="text-[13.5px] font-bold text-ink">~</Text>
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [vals.humidity[0], v])} />
<Text className="text-[13.5px] font-bold text-ink">%</Text>
</Row>
<View className="flex-row flex-wrap items-center gap-1.5 py-2.5">
<Text className="w-[84px] text-[14px] font-extrabold text-ink">시간대</Text>
{SLOTS.map(([k, word]) => (
<Pressable key={k} onPress={() => 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]'}`}>
<Text className={`text-[13.5px] font-bold ${vals.slots.includes(k) ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
</Pressable>
))}
</View>
<View className="mt-2 gap-1.5 rounded-[20px] p-3.5" style={{ backgroundColor: soft.soft }}>
<View className="flex-row items-center gap-2">
<Ic name={icon} size={32} />
<Text className="font-jua text-[20px] text-ink">{title}</Text>
<Score s={valid ? score : undefined} big />
</View>
{valid ? <Reasons s={score} /> : <Text className="text-[12.5px] font-semibold text-ink3">조건과 시간대를 하나 이상 골라요</Text>}
</View>
{failed && <Text className="mt-2 text-xs font-bold text-heart">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</Text>}
<Pressable disabled={!valid || !gakName(name) || pending} onPress={() => create({ name, icon, rule }, onDone)} className="mt-3.5 rounded-2xl bg-orange py-3 disabled:opacity-45">
<Text className="text-center font-jua text-[17px] text-white">{shared ? '내 각으로 가져오기' : '내 각으로 저장'}</Text>
</Pressable>
</Body>
);
}
-38
View File
@@ -1,38 +0,0 @@
import Svg, { Circle, Path } from 'react-native-svg';
export const HEART = 'M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z';
type P = { size: number; color: string };
export function HeartIcon({ size, color, filled }: P & { filled: boolean }) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill={filled ? color : 'none'} stroke={color} strokeWidth={1.9}>
<Path d={HEART} />
</Svg>
);
}
export function CommentIcon({ size, color }: P) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinejoin="round">
<Path d="M20.5 12a8.5 8.5 0 0 1-12.6 7.4L3.5 20.5l1.2-4.2A8.5 8.5 0 1 1 20.5 12z" />
</Svg>
);
}
export function SendIcon({ size, color }: P) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
<Path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
</Svg>
);
}
export function CameraIcon({ size, color }: P) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
<Path d="M4 8.5A1.5 1.5 0 0 1 5.5 7h2.2l1.5-2h5.6l1.5 2h2.2A1.5 1.5 0 0 1 20 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 17.5z" />
<Circle cx={12} cy={13} r={3.5} />
</Svg>
);
}
-64
View File
@@ -1,64 +0,0 @@
import { useEffect } from 'react';
import { View } from 'react-native';
import Animated, { Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withTiming } from 'react-native-reanimated';
import Svg, { Path } from 'react-native-svg';
import { HEART } from '@/components/post/icons';
// 튀어 나가는 작은 하트: x·y 이동, 회전, 색 (웹 BURST)
const BURST: [number, number, number, string][] = [
[-86, -60, -24, '#ff3b5c'],
[84, -66, 22, '#ff8e4e'],
[-104, 18, -40, '#ffc86e'],
[102, 24, 36, '#ff3b5c'],
[-48, -104, -8, '#ff8aa0'],
[52, -100, 12, '#ffc86e'],
];
function Bit({ dx, dy, rot, color }: { dx: number; dy: number; rot: number; color: string }) {
const p = useSharedValue(0);
useEffect(() => {
p.value = withDelay(80, withTiming(1, { duration: 900, easing: Easing.bezier(0.2, 0.8, 0.3, 1) }));
}, [p]);
const style = useAnimatedStyle(() => ({
opacity: interpolate(p.value, [0, 0.25, 1], [0, 1, 0]),
transform: [{ translateX: dx * p.value }, { translateY: dy * p.value }, { scale: interpolate(p.value, [0, 1], [0.4, 1.1]) }, { rotate: `${rot * p.value}deg` }],
}));
return (
<Animated.View style={[{ position: 'absolute' }, style]}>
<Svg viewBox="0 0 24 24" width={20} height={20} fill={color}>
<Path d={HEART} />
</Svg>
</Animated.View>
);
}
function Toast() {
const p = useSharedValue(0);
useEffect(() => {
p.value = withTiming(1, { duration: 1300, easing: Easing.bezier(0.2, 0.9, 0.3, 1) });
}, [p]);
const style = useAnimatedStyle(() => ({
opacity: interpolate(p.value, [0, 0.18, 0.78, 1], [0, 1, 1, 0]),
transform: [{ translateY: interpolate(p.value, [0, 0.18, 0.78, 1], [14, 0, 0, -8]) }, { scale: interpolate(p.value, [0, 0.18, 0.3, 1], [0.85, 1.06, 1, 1]) }],
}));
return (
<Animated.View className="absolute top-[58%] rounded-full bg-white px-4 py-2" style={[{ boxShadow: '0 8px 18px rgb(40 48 74 / 0.18)' }, style]}>
<Animated.Text className="font-jua text-[17px] text-heart">좋아요했어요!</Animated.Text>
</Animated.View>
);
}
/** 좋아요 때 하트 조각이 튀어 나가고 '좋아요했어요!' 가 떴다 사라진다 */
export function LikeBurst() {
const reduce = useReducedMotion();
if (reduce) return null;
return (
<View pointerEvents="none" className="absolute inset-0 items-center justify-center" accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
{BURST.map(([dx, dy, rot, color], k) => (
<Bit key={k} dx={dx} dy={dy} rot={rot} color={color} />
))}
<Toast />
</View>
);
}
-29
View File
@@ -1,29 +0,0 @@
import type { ReactNode } from 'react';
import { ScrollView, View, type NativeScrollEvent, type NativeSyntheticEvent } from 'react-native';
/** 옆으로 한 장씩 넘기는 슬라이드 (웹 Embla 캐러셀 대신 가로 paging ScrollView) */
export function Pager({ width, height, onIndex, children }: { width: number; height: number; onIndex: (i: number) => void; children: ReactNode[] }) {
const onEnd = (e: NativeSyntheticEvent<NativeScrollEvent>) => onIndex(Math.round(e.nativeEvent.contentOffset.x / width));
return (
<ScrollView horizontal pagingEnabled showsHorizontalScrollIndicator={false} scrollEnabled={children.length > 1} onMomentumScrollEnd={onEnd} style={{ width, height }}>
{children.map((c, i) => (
<View key={i} style={{ width, height }}>
{c}
</View>
))}
</ScrollView>
);
}
/** 슬라이드 위치 점 */
export function Dots({ n, index }: { n: number; index: number }) {
if (n < 2) return null;
const items = Array.from({ length: n }, (_, i) => i);
return (
<View className="flex-row justify-center gap-1.5 pt-2" accessibilityElementsHidden>
{items.map((i) => (
<View key={i} className={`h-1.5 rounded-full ${i === index ? 'w-4 bg-orange' : 'w-1.5 bg-ink3/40'}`} />
))}
</View>
);
}
-240
View File
@@ -1,240 +0,0 @@
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { PostType, type PostData, type ResFeed } from '@nalssigak/shared/api/client/types.gen';
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect, useRef, useState } from 'react';
import { Animated, Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import Svg, { Path } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
import { CommentIcon, HEART, HeartIcon, SendIcon } from '@/components/post/icons';
import { LikeBurst } from '@/components/post/like-burst';
import { Dots, Pager } from '@/components/post/pager';
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 { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
const ACCOUNTS: Partial<Record<PostType, readonly [string, string]>> = {
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
[PostType.GAK]: ['오늘의 각', 'rabbit'],
[PostType.SUNSET]: ['노을', 'sunset'],
[PostType.SEASON]: ['계절 소식', 'maple'],
[PostType.EVENT]: ['가까운 행사', 'fireworks'],
[PostType.TIP]: ['날씨 상식', 'bulb'],
[PostType.WEEK]: ['주말 예보', 'calendar'],
[PostType.ALERT]: ['생활 알림', 'umbrella'],
[PostType.TOMORROW]: ['내일 미리보기', 'moon'],
[PostType.QUOTE]: ['오늘의 한 문장', 'letter'],
[PostType.WEEKEND_PLAN]: ['주말 플랜', 'calendar'],
[PostType.AIR]: ['미세먼지', 'vent'],
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
[PostType.CARD]: ['날씨각 카드', 'stars'],
};
/** 앱이 그릴 줄 아는 글 종류만 (히어로·띠처럼 피드 반응 칸으로만 오는 종류는 뺀다) */
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS;
type PostProps = { post: PostData };
/** 받아 둔 피드 데이터에도 좋아요를 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */
function patchFeed(queryClient: QueryClient, postId: number, patch: Partial<PostData>) {
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
feed?.posts ? { ...feed, posts: feed.posts.map((p) => (p.post_id === postId ? { ...p, ...patch } : p)) } : feed,
);
}
/** 한 줄 카드 (흐린 날 노을처럼 큰 그림이 필요 없는 소식) */
function LineCard({ post }: PostProps) {
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
return (
<View className="mx-3 mt-3.5 flex-row items-center gap-3 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3" accessibilityLabel={post.title}>
<Ic name={post.icon || avatar} size={40} />
<View className="flex-1">
<Text className="text-xs font-bold text-ink3">{account}</Text>
<Text className="text-sm text-ink2">
<Text className="font-jua text-base text-ink">{post.title}</Text> {post.caption}
</Text>
</View>
</View>
);
}
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
export function PostCard({ post }: PostProps) {
return post.size === 'line' ? <LineCard post={post} /> : <FullCard post={post} />;
}
/** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */
export function PostCardSkel() {
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityElementsHidden>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full bg-skel" />
<View className="gap-1.5">
<Skel className="w-12" />
<Skel className="w-16" />
</View>
</View>
<View className="aspect-[4/5] bg-skel" />
<View className="flex-row gap-3.5 px-3 pt-2.5 pb-1">
<View className="size-7 rounded-full bg-skel" />
<View className="size-7 rounded-full bg-skel" />
<View className="size-7 rounded-full bg-skel" />
</View>
<View className="gap-2 px-3 pt-1 pb-3">
<Skel className="w-20" />
<Skel className="w-4/5" />
<Skel className="w-32" />
<Skel className="w-8" />
</View>
</View>
);
}
/** 좋아요 때 가운데에 커졌다 사라지는 하트 */
function HeartPop() {
const [v] = useState(() => new Animated.Value(0));
useEffect(() => {
Animated.timing(v, { toValue: 1, duration: 800, useNativeDriver: true }).start();
}, [v]);
const opacity = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0, 1, 1, 0] });
const scale = v.interpolate({ inputRange: [0, 0.25, 0.6, 1], outputRange: [0.3, 1.1, 1, 1] });
return (
<Animated.View pointerEvents="none" className="absolute inset-0 items-center justify-center" style={{ opacity, transform: [{ scale }] }}>
<Svg viewBox="0 0 24 24" width={112} height={112} fill="#ff3b5c">
<Path d={HEART} />
</Svg>
</Animated.View>
);
}
function FullCard({ post }: PostProps) {
const { open } = useSheet();
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const liked = !!post.liked;
const likeCount = post.like_count;
const queryClient = useQueryClient();
const like = useMutation(likePostMutation());
const unlike = useMutation(unlikePostMutation());
const [width, setWidth] = useState(0);
const [index, setIndex] = useState(0);
const [pop, setPop] = useState(0);
const [likeFailed, setLikeFailed] = useState(0);
const lastTap = useRef(0);
const [account, avatar] = ACCOUNTS[post.post_type] ?? ['날씨각', 'sun'];
const n = post.slides.length;
const patch = (values: Partial<PostData>) => patchFeed(queryClient, post.post_id, values);
const comments = () => open({ type: 'comments', postId: post.post_id });
const shot = useRef<View>(null);
// 지금 보고 있는 슬라이드를 이미지로
const shareView = useShare();
const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` });
useEffect(() => {
if (!likeFailed) return;
const t = setTimeout(() => setLikeFailed(0), 2500);
return () => clearTimeout(t);
}, [likeFailed]);
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
// 좋아요는 로그인 없이 된다 (웹과 같이)
const setLike = (on: boolean) => {
if (on === liked || like.isPending || unlike.isPending) return;
if (on) setPop((p) => p + 1);
setLikeFailed(0);
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) });
const revert = () => {
patch({ liked, like_count: likeCount });
setLikeFailed(Date.now());
};
(on ? like : unlike).mutate(
{ path: { post_id: post.post_id } },
{
onSuccess: (res) => {
if (!res.result?.success) return revert();
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) });
if (on) track('like', { content_type: 'post', item_id: post.post_id });
},
onError: revert,
},
);
};
const onTap = () => {
const now = Date.now();
if (now - lastTap.current < 320) {
if (liked) setPop((p) => p + 1);
else setLike(true);
}
lastTap.current = now;
};
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={post.title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full p-0.5">
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
<View className="flex-1 items-center justify-center rounded-full bg-card">
<Ic name={avatar} size={22} />
</View>
</View>
<View>
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
<Text className="text-xs font-semibold text-ink2">{account}</Text>
</View>
</View>
<Pressable onPress={onTap} onLayout={(e) => setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}>
<View ref={shot} collapsable={false}>
{width > 0 && (
<Pager width={width} height={(width * 5) / 4} onIndex={setIndex}>
{post.slides.map((s: Slide, i) => (
<SlideView key={i} slide={s} bg={slideBg(post, s)} />
))}
</Pager>
)}
</View>
{n > 1 && (
<View pointerEvents="none" className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px]">
<Text className="text-xs font-extrabold text-white">
{index + 1}/{n}
</Text>
</View>
)}
{pop > 0 && <HeartPop key={pop} />}
{pop > 0 && <LikeBurst key={`b${pop}`} />}
{likeFailed > 0 && (
<View pointerEvents="none" className="absolute inset-x-0 bottom-4 items-center px-4" accessibilityRole="alert">
<Text className="overflow-hidden rounded-full bg-[rgb(30_36_56/0.82)] px-3.5 py-2 text-[13px] font-bold text-white">{liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요.</Text>
</View>
)}
</Pressable>
<Dots n={n} index={index} />
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
<Pressable onPress={() => setLike(!liked)} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={liked ? heart : ink} filled={liked} />
</Pressable>
<Pressable onPress={comments} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
<CommentIcon size={26} color={ink} />
</Pressable>
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
<SendIcon size={26} color={ink} />
</Pressable>
</View>
<Text className="px-3 py-0.5 text-sm font-extrabold text-ink">좋아요 {likeCount.toLocaleString()}개</Text>
<Text className="px-3 py-0.5 text-sm text-ink">
<Text className="font-extrabold">날씨각 </Text>
{post.caption}
</Text>
<Pressable onPress={comments}>
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">오늘</Text>
</View>
);
}
-79
View File
@@ -1,79 +0,0 @@
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen';
import type { PinnedKey } from '@nalssigak/shared/lib/analytics';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, type ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { useCSSVariable } from 'uniwind';
import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { usePinnedLike } from '@/lib/pinned-like';
import { useSheet } from '@/lib/sheet';
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 };
/** 오늘의 각처럼 포스트 틀(머리줄·버튼줄·글 한 줄)만 빌려 쓰는 카드 (웹 PostFrame). 좋아요·댓글은 피드의 반응 칸(pinned)에 붙는다 */
export function PostFrame({ title, account, avatar, caption, more, pinned, children }: Props) {
const { open } = useSheet();
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post);
const postId = pinned?.post?.post_id;
const shot = useRef<View>(null);
const shareView = useShare();
const share = () => void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` });
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full p-0.5">
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
<View className="flex-1 items-center justify-center rounded-full bg-card">
<Ic name={avatar} size={22} />
</View>
</View>
<View>
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
<Text className="text-xs font-semibold text-ink2">{account}</Text>
</View>
</View>
<View ref={shot} collapsable={false}>
{children}
</View>
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
{postId != null && (
<>
<Pressable onPress={like.toggle} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={like.liked ? heart : ink} filled={like.liked} />
</Pressable>
<Pressable onPress={() => open({ type: 'comments', postId })} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
<CommentIcon size={26} color={ink} />
</Pressable>
</>
)}
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
<SendIcon size={26} color={ink} />
</Pressable>
{more != null && <View className="ml-auto">{more}</View>}
</View>
{postId != null && (
<Text className={`px-3 py-0.5 text-sm font-extrabold ${like.failed ? 'text-heart' : 'text-ink'}`} accessibilityRole={like.failed ? 'alert' : undefined}>
{like.failed ? '좋아요를 반영하지 못했어요. 다시 해 주세요.' : `좋아요 ${like.count.toLocaleString()}개`}
</Text>
)}
{!!caption && (
<Text className="px-3 pt-0.5 pb-3 text-sm text-ink">
<Text className="font-extrabold">날씨각 </Text>
{caption}
</Text>
)}
{postId != null && (
<Pressable onPress={() => open({ type: 'comments', postId })}>
<Text className="px-3 pb-3 text-sm font-semibold text-ink3">{pinned?.post?.comment_count ? `댓글 ${pinned.post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
)}
</View>
);
}
-285
View File
@@ -1,285 +0,0 @@
import type { GakSlide, HoursSlide, ImageSlide, PlanSlide, PostData, RowsSlide, SunsetSlide, WeekSlide } from '@nalssigak/shared/api/client/types.gen';
import { PostType, SlotTone } from '@nalssigak/shared/api/client/types.gen';
import { cardBg, clockShort } from '@nalssigak/shared/lib';
import type { SlideBg } from '@nalssigak/shared/lib/types';
import { deg } from '@nalssigak/shared/lib/weatherText';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { useState, type ReactNode } from 'react';
import { Pressable, StyleSheet, View } from 'react-native';
import { Text } from '@/components/text';
import Svg, { Polygon } from 'react-native-svg';
import { MoonArt } from '@/components/moon';
import { Credit, Ic, Rows, Thumb } from '@/components/ui';
import { CARD_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { apiUri, imageUri } from '@/lib/site';
import { useSky } from '@/lib/sky';
export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide | ImageSlide;
type Stops = readonly [string, string, ...string[]];
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac'];
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac', glasses: 'butter' };
const DARK = new Set<SlideBg>(['dusk', 'night']);
const chunk = <T,>(items: T[], n: number) => Array.from({ length: Math.ceil(items.length / n) }, (_, i) => items.slice(i * n, i * n + n));
// 노을 하늘 상황(1 가려짐 2 낮은 구름 3 물들 구름 적음 4 넓게 물듦 5 두꺼움)별 하늘, 시간 칸 색 (웹 .b-sit-*, .b-cut-*)
const SIT_BG: Record<number, { colors: Stops; locations: readonly [number, number, ...number[]] }> = {
1: { colors: ['#6f7690', '#9aa0b4', '#b9b4c0'], locations: [0, 0.55, 1] },
2: { colors: ['#7a7f9c', '#a7a3bb', '#c9b8b8'], locations: [0, 0.55, 1] },
3: { colors: ['#4b5aa8', '#7f86c6', '#e9b9a8', '#ffb27a', '#ff8a4c'], locations: [0, 0.38, 0.68, 0.86, 1] },
4: { colors: ['#5b3f9e', '#c2559a', '#ff7a6a', '#ffb35c'], locations: [0, 0.4, 0.68, 1] },
5: { colors: ['#6a6aa0', '#a98fb4', '#e3b1a0'], locations: [0, 0.55, 1] },
};
const CUT_BG: Stops[] = [
['#9fd0ff', '#ffd79a', '#ff9a5c'],
['#8f7cf0', '#ff6f8e', '#ff8a4c'],
['#34306e', '#7a5cc8'],
];
// 건물 실루엣 (웹 .b-skyline clip-path)
const SKYLINE = '0,55 8,55 8,30 15,30 15,50 22,50 22,10 28,10 28,45 36,45 36,25 44,25 44,55 52,55 52,35 60,35 60,5 66,5 66,40 74,40 74,20 82,20 82,50 90,50 90,30 100,30 100,100 0,100';
const HOUR_TONE: Record<string, { bg: string; edge: string }> = {
[SlotTone.NIGHT]: { bg: '#e3e7ff', edge: '#c7cff5' },
[SlotTone.SUNSET]: { bg: '#ffe3d2', edge: '#ffc19f' },
};
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
export function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'hours' || slide.kind === 'image') return 'sky';
if (slide.kind === 'sunset') return 'dusk';
if (slide.kind === 'week') return 'mint';
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter';
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length];
if (post.post_type === PostType.EVENT || post.post_type === PostType.MOON) return 'night';
if (post.post_type === PostType.TIP) return 'sky';
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac';
if (post.post_type === PostType.DAY_TRIP) return slide.image ? 'night' : 'mint';
return (ROW_ICON_BG[slide.icon] ?? cardBg(slide.icon, post.post_id)) as SlideBg;
}
function Base({ colors, locations, children }: { colors: Stops; locations?: readonly [number, number, ...number[]]; children: ReactNode }) {
return (
<View className="flex-1 px-5 py-[22px]">
<LinearGradient colors={colors} locations={locations} style={StyleSheet.absoluteFill} />
{children}
</View>
);
}
function Eyebrow({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) {
return <Text className={`text-[13px] font-extrabold opacity-75 ${light ? 'text-white' : 'text-ink'} ${className ?? ''}`}>{children}</Text>;
}
function Big({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) {
return <Text className={`mt-1.5 font-jua text-[29px] leading-tight ${light ? 'text-white' : 'text-ink'} ${className ?? ''}`}>{children}</Text>;
}
function Pic({ name, widthPct = 42 }: { name: string; widthPct?: number }) {
return (
<View pointerEvents="none" className="absolute top-[30%] right-3.5 aspect-square" style={{ width: `${widthPct}%` }}>
<Ic name={name} size={0} style={{ width: '100%', height: '100%' }} />
</View>
);
}
// 달 포스트 밤하늘 별: [left %, top %, 크기]
const STARS: [number, number, number][] = [
[8, 34, 2], [18, 52, 1.5], [30, 40, 2.5], [44, 30, 1.5], [52, 58, 2], [62, 22, 1.5], [90, 18, 2], [94, 44, 1.5], [12, 70, 1.5], [38, 66, 2], [76, 74, 1.5], [86, 64, 2], [24, 12, 1.5], [70, 10, 2.5],
];
/** 달 포스트 그림: 아이콘 대신 오늘 밤 실제 모양의 달과 별 */
function MoonPic({ pct, waxing }: { pct: number; waxing: boolean }) {
const [w, setW] = useState(0);
return (
<View pointerEvents="none" style={StyleSheet.absoluteFill} onLayout={(e) => setW(e.nativeEvent.layout.width)}>
{STARS.map(([x, y, s]) => (
<View key={`${x},${y}`} className="absolute rounded-full bg-white opacity-80" style={{ left: `${x}%`, top: `${y}%`, width: s, height: s }} />
))}
{w > 0 && (
<View className="absolute top-[22%] right-0">
<MoonArt pct={pct} waxing={waxing} size={w * 0.6} />
</View>
)}
</View>
);
}
export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
const { open } = useSheet();
const { kind } = useSky();
const palette = CARD_BG[kind === 'night' ? 'night' : 'day'];
const colors = palette[bg] ?? palette.sky;
const light = DARK.has(bg);
if (slide.kind === 'hours') {
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]));
const lo = Math.min(...temps);
const span = Math.max(...temps) - lo || 1;
return (
<Base colors={palette.sky}>
<Eyebrow>{slide.eyebrow}</Eyebrow>
<Big>{slide.line}</Big>
{/* 웹 grid-cols-4: 4칸씩 줄을 나눈다 */}
<View className="mt-3.5 flex-1 gap-2">
{chunk(slide.hours, 4).map((row) => (
<View key={row[0].label} className="flex-1 flex-row gap-2">
{row.map((h) => {
const tone = HOUR_TONE[h.tone ?? ''];
return (
<View key={h.label} className={`flex-1 items-center justify-between overflow-hidden rounded-[18px] px-1 pt-2.5 pb-[9px] ${tone ? '' : 'border-b-[5px] border-shade bg-card'}`} style={tone ? { backgroundColor: tone.bg, borderBottomWidth: 5, borderColor: tone.edge } : undefined}>
{h.temp_c != null && <LinearGradient colors={['rgba(255,122,69,0.1)', 'rgba(255,122,69,0.34)']} style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: `${20 + ((h.temp_c - lo) / span) * 70}%` }} />}
<Text className={`text-xs font-bold ${tone ? 'text-[#5a6380]' : 'text-ink2'}`}>{h.label}</Text>
<Ic name={h.icon} size={34} />
<Text className={`font-bagel text-[21px] ${tone ? 'text-[#28304a]' : 'text-ink'}`}>{deg(h.temp_c)}</Text>
</View>
);
})}
{/* 마지막 줄이 모자라면 빈 칸으로 너비를 맞춘다 */}
{Array.from({ length: 4 - row.length }, (_, i) => (
<View key={`pad${i}`} className="flex-1" />
))}
</View>
))}
</View>
</Base>
);
}
if (slide.kind === 'gak')
return (
<Base colors={colors}>
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
<Big>{slide.line}</Big>
<Pic name={slide.code} />
<Text className="mt-auto font-bagel text-[82px] leading-[82px] text-orange">{slide.score}</Text>
<Text className="font-jua text-[29px] leading-tight text-ink">{slide.name}</Text>
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
<Pressable onPress={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 self-start rounded-full border-b-[5px] border-orange-deep bg-orange px-4 py-[9px]">
<Text className="font-jua text-[15px] text-white">계산 근거 보기</Text>
</Pressable>
</Base>
);
if (slide.kind === 'sunset') {
const sit = slide.situation ? SIT_BG[slide.situation] : undefined;
return (
<Base colors={sit?.colors ?? palette.dusk} locations={sit?.locations}>
<Eyebrow light>{slide.eyebrow}</Eyebrow>
{/* 노을 탭 히어로와 같은 순서: 결론 → 가장 붉을 때 → 쉬운 이유 */}
<Big light>{slide.headline ?? slide.grade_label}</Big>
{!!slide.line && <Text className="mt-0.5 font-jua text-[18px] text-white">{slide.line}</Text>}
<View className="mt-3 flex-1 gap-2">
{slide.cuts.map((c, i) => (
<View key={c.kind} className="flex-1 overflow-hidden rounded-2xl px-3 py-2">
<LinearGradient colors={CUT_BG[Math.min(i, 2)]} style={StyleSheet.absoluteFill} />
<Svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: '32%' }}>
<Polygon points={SKYLINE} fill="#2d2440" />
</Svg>
<Text className="font-bagel text-[21px] text-white">
{clockShort(c.at)}
<Text className="font-jua text-sm"> {c.label}</Text>
</Text>
</View>
))}
</View>
</Base>
);
}
if (slide.kind === 'week')
return (
<Base colors={palette.mint}>
<Eyebrow>{slide.eyebrow}</Eyebrow>
<Big>{slide.line}</Big>
{/* 칸은 제목 바로 아래, 팁만 맨 아래로 */}
<View className="mt-4 flex-row flex-wrap gap-2.5">
{slide.days.map((d) => (
<View key={d.day} className="grow basis-[45%] gap-0.5 rounded-[18px] border-b-[5px] border-shade bg-card/85 px-3 py-2.5">
<Ic name={d.icon} size={34} />
<Text className="font-jua text-lg text-ink">
{d.weekday} {d.day.split('-').slice(1).map(Number).join('.')}
</Text>
<Text className="font-jua text-[22px] text-ink">
<Text className="text-rain">{deg(d.temp_min_c)}</Text> → <Text className="text-orange">{deg(d.temp_max_c)}</Text>
</Text>
<Text className="text-xs font-bold text-ink2">
비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`}
</Text>
{d.gaks && d.gaks.length > 0 && (
<View className="mt-2 gap-1.5 border-t border-shade pt-2" accessibilityLabel={`${d.weekday}요일 대표 각`}>
<Text className="text-[11px] font-extrabold text-ink2">이날 할 만한 각</Text>
{d.gaks.map((g) => (
<View key={g.index_id} className="flex-row items-center gap-1.5">
<Ic name={g.icon} size={26} />
<Text numberOfLines={1} className="flex-1 text-[14px] font-bold text-ink">
{g.name}
</Text>
<Text className="font-bagel text-[16px] text-orange">{g.score}</Text>
</View>
))}
</View>
)}
</View>
))}
</View>
{!!slide.tip && <Text className="mt-auto overflow-hidden rounded-[14px] bg-ink-btn px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</Text>}
</Base>
);
if (slide.kind === 'plan') {
const credits = [...new Set(slide.steps.flatMap((st) => (st.image && st.image_credit ? [st.image_credit] : [])))];
return (
<Base colors={colors}>
<Eyebrow>{slide.eyebrow}</Eyebrow>
<Big className="text-[24px]">{slide.line}</Big>
<View className="mt-auto gap-2">
{slide.steps.map((st, i) => (
<View key={i} className="flex-row items-center gap-1.5 rounded-[14px] bg-card/80 px-2 py-1.5">
<Text className="w-[52px] font-jua text-sm text-ink2">{st.time}</Text>
<Ic name={st.icon} size={22} />
<View className="ml-1 flex-1">
<Text numberOfLines={1} className="text-[13.5px] font-bold text-ink">
{st.title}
</Text>
<Text numberOfLines={1} className="text-[11.5px] font-semibold text-ink2">
{st.sub}
</Text>
</View>
{!!st.image && <Thumb image={st.image} icon={st.icon} iconSize={26} className="size-[46px] rounded-[10px]" />}
</View>
))}
</View>
{credits.length > 0 && <Text className="mt-1.5 text-right text-[10px] font-semibold text-ink2">사진 {credits.join(' · ')}</Text>}
</Base>
);
}
// 카드뉴스: 관리자가 만든 4:5 그림 한 장 (/v1/card/... 는 API 서버 경로)
if (slide.kind === 'image') return <Image source={{ uri: apiUri(slide.url) }} accessibilityLabel={slide.alt ?? undefined} style={{ flex: 1 }} contentFit="cover" />;
if (slide.kind === 'rows' && slide.image)
return (
<View className="flex-1 justify-end">
<Image source={{ uri: imageUri(slide.image) }} style={StyleSheet.absoluteFill} contentFit="cover" />
{!!slide.image_credit && <Credit text={slide.image_credit} className="top-2.5 right-2.5" />}
<View className="px-5 pt-20 pb-3.5">
<LinearGradient colors={['rgba(16,20,34,0)', 'rgba(16,20,34,0.55)', 'rgba(16,20,34,0.85)']} locations={[0, 0.35, 1]} style={StyleSheet.absoluteFill} />
<Eyebrow light>{slide.eyebrow}</Eyebrow>
<Big light>{slide.line}</Big>
<Rows rows={slide.rows ?? []} dark />
</View>
</View>
);
return (
<Base colors={colors}>
{slide.moon_pct != null && <MoonPic pct={slide.moon_pct} waxing={!!slide.moon_waxing} />}
<Eyebrow light={light} className={light ? 'opacity-85' : undefined}>
{slide.eyebrow}
</Eyebrow>
<Big light={light} className="z-[1]">
{slide.line}
</Big>
{slide.moon_pct == null && <Pic name={slide.icon} widthPct={36} />}
<Rows rows={slide.rows ?? []} dark={light} />
</Base>
);
}
-108
View File
@@ -1,108 +0,0 @@
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { BIRTH_PLACES, placeName, useSaveBirth, validBirth, type Birth } from '@/lib/saju-birth';
import { Box, ChipGrid, DatePick, Stepper, type Ymd } from './pick';
const HOURS: [number, string][] = [[-1, '모름'], ...Array.from({ length: 24 }, (_, i): [number, string] => [i, `${i}시`])];
const PLACES: [string, string][] = BIRTH_PLACES.map(([k, n]) => [k, n]);
function Label({ children }: { children: string }) {
return <Text className="mb-1.5 text-[13px] font-extrabold text-ink2">{children}</Text>;
}
/** 생년월일·태어난 시각·지역 넣기 (웹 SajuPage BirthForm) */
export function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) {
const { loggedIn } = useAuth();
const save = useSaveBirth();
const [date, setDate] = useState<Ymd>({ y: initial?.y ?? null, m: initial?.m ?? null, d: initial?.d ?? null });
const [hour, setHour] = useState<number | null>(initial?.hour ?? null);
const [minute, setMinute] = useState(initial?.minute ?? 0);
const [place, setPlace] = useState(initial?.place ?? 'seoul');
const [open, setOpen] = useState<'hour' | 'place' | null>(null);
const [error, setError] = useState('');
const toggle = (k: 'hour' | 'place') => setOpen((o) => (o === k ? null : k));
const submit = () => {
const { y, m, d } = date;
if (y == null || m == null || d == null) return setError('생년월일을 모두 넣어 주세요');
if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요');
void save({ y, m, d, hour, minute: hour == null ? null : minute, place, gender: initial?.gender ?? null });
track('saju_input', { with_time: hour != null });
onDone();
};
return (
<View className="mx-4 mt-4 gap-4 rounded-[24px] border-b-[5px] border-shade bg-card p-5">
<View className="items-center">
<Ic name="yin_yang" size={56} />
<Text className="mt-2 text-center font-jua text-[20px] leading-snug text-ink">{'내 사주와 오늘 날씨로\n오늘 하루를 봐요'}</Text>
</View>
<View>
<Label>생년월일 (양력)</Label>
<DatePick
value={date}
onChange={(v) => {
setDate(v);
setError('');
}}
/>
</View>
<View>
<Label>{"태어난 시각 (모르면 '모름')"}</Label>
<View className="flex-row gap-1.5">
<Box label="시" value={hour == null ? '모름' : `${hour}시`} placeholder="모름" open={open === 'hour'} onPress={() => toggle('hour')} />
<Stepper label="분" value={minute} onChange={setMinute} min={0} max={59} unit="분" disabled={hour == null} />
</View>
{open === 'hour' && (
<View className="mt-1.5">
<ChipGrid
label="태어난 시"
items={HOURS}
value={hour ?? -1}
onPick={(h) => {
setHour(h < 0 ? null : h);
setOpen(null);
}}
wide
/>
</View>
)}
</View>
<View>
<Label>태어난 지역</Label>
<Box label="태어난 지역" value={placeName(place)} placeholder="서울" open={open === 'place'} onPress={() => toggle('place')} />
{open === 'place' && (
<View className="mt-1.5">
<ChipGrid
label="태어난 지역"
items={PLACES}
value={place}
onPick={(p) => {
setPlace(p);
setOpen(null);
}}
wide
/>
</View>
)}
<Text className="mt-1.5 text-xs font-semibold text-ink3">지역마다 해가 뜨는 시각이 달라 태어난 시각을 그만큼 고쳐서 봐요.</Text>
</View>
{!!error && <Text className="text-center text-[13px] font-bold text-[#d9442f]">{error}</Text>}
<Pressable onPress={submit} accessibilityRole="button" className="rounded-full bg-orange py-3.5">
<Text className="text-center text-[15px] font-extrabold text-white">오늘 날씨 사주 보기</Text>
</Pressable>
{!!onCancel && (
<Pressable onPress={onCancel} accessibilityRole="button" className="-mt-2 py-1">
<Text className="text-center text-[13px] font-extrabold text-ink3">취소</Text>
</Pressable>
)}
<Text className="text-center text-xs font-semibold text-ink3">{loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'}</Text>
</View>
);
}
-81
View File
@@ -1,81 +0,0 @@
import { matchMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { ResSajuMatch } from '@nalssigak/shared/api/client/types.gen';
import { useMutation } from '@tanstack/react-query';
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { useRegion } from '@/lib/region';
import { toBody, validBirth, type Birth } from '@/lib/saju-birth';
import { dayWord, Panel } from './parts';
import { DatePick, type Ymd } from './pick';
const pad = (n: number) => String(n).padStart(2, '0');
/** 궁합 (Lv.5): 상대 생년월일로 두 사주가 맞는 정도와 같이 나가기 좋은 날. 상대 생년월일은 저장하지 않는다 */
export function Match({ birth }: { birth: Birth }) {
const { region } = useRegion();
const soft = useSoft();
const [date, setDate] = useState<Ymd>({ y: null, m: null, d: null });
const [error, setError] = useState('');
const run = useMutation({ ...matchMutation() });
const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined;
const go = () => {
const { y, m, d } = date;
if (y == null || m == null || d == null) return setError('상대 생년월일을 모두 넣어 주세요');
if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요');
setError('');
run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${y}-${pad(m)}-${pad(d)}`, longitude: 126.98 } } });
};
return (
<Panel id="saju_match" icon="two_hearts" title="궁합">
{res ? (
<>
<View className="mb-1 flex-row items-center justify-between">
<Text className="text-xs font-bold text-ink3">
상대 {date.y}.{date.m}.{date.d}생
</Text>
<Pressable onPress={() => run.reset()} hitSlop={8} accessibilityRole="button">
<Text className="text-xs font-extrabold text-orange">다른 사람 보기</Text>
</Pressable>
</View>
<Text className="font-jua text-[19px] text-ink">
{res.title ?? ''} <Text className="font-bagel text-[17px] text-orange">{res.score ?? ''}점</Text>
</Text>
{res.lines?.map((l) => (
<Text key={l} className="mt-1 text-[13.5px] font-semibold text-ink">
{l}
</Text>
))}
{!!res.day && (
<Text className="mt-2 overflow-hidden rounded-xl px-3 py-2 text-[13.5px] font-bold text-ink" style={{ backgroundColor: soft.warm }}>
앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)}
{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
</Text>
)}
<Text className="mt-1.5 text-xs font-semibold text-ink3">상대 기운: {res.friend_scene ?? ''}</Text>
</>
) : (
<>
<Text className="mb-2 text-[13px] font-semibold text-ink2">상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.</Text>
<DatePick
label="상대 "
value={date}
onChange={(v) => {
setDate(v);
setError('');
}}
/>
<Pressable onPress={go} disabled={run.isPending} accessibilityRole="button" className="mt-2 rounded-xl bg-orange py-3 disabled:opacity-45">
<Text className="text-center text-[14px] font-extrabold text-white">보기</Text>
</Pressable>
{!!error && <Text className="mt-1.5 text-xs font-bold text-[#d9442f]">{error}</Text>}
{(run.isError || (!!run.data && !run.data.result?.success)) && <Text className="mt-1.5 text-xs font-bold text-[#d9442f]">궁합을 불러오지 못했어요. 다시 눌러 주세요.</Text>}
<Text className="mt-1.5 text-xs font-semibold text-ink3">상대 생년월일은 저장하지 않아요.</Text>
</>
)}
</Panel>
);
}
-139
View File
@@ -1,139 +0,0 @@
import type { ResSaju } from '@nalssigak/shared/api/client/types.gen';
import { Image } from 'expo-image';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { EL_ART, EL_COLOR, EL_WORD, Panel } from './parts';
const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' };
const STRENGTH_WORD: Record<string, string> = {
신강: '나를 돕는 기운이 센 사주. 태어난 달(월령)의 힘을 먼저 봐요',
중화: '나를 돕는 기운과 다른 기운이 비슷한 사주',
신약: '나를 돕는 기운이 약한 사주',
};
const TEN_GOD_WORD: Record<string, string> = {
비견: '나와 같은 기운',
겁재: '나와 같지만 겨루는 기운',
식신: '내가 만들어 내는 기운',
상관: '내가 드러내는 기운',
편재: '내가 크게 굴리는 재물',
정재: '내가 차곡차곡 모으는 재물',
편관: '나를 세게 다잡는 기운',
정관: '나를 바르게 이끄는 기운',
편인: '나를 돕는 남다른 지혜',
정인: '나를 돕는 배움·도움',
};
function Art({ el, size }: { el: string; size: number }) {
const src = EL_ART[el];
return src != null ? <Image source={src} style={{ width: size, height: size }} contentFit="contain" /> : null;
}
function Char({ c, ko, el, me }: { c: string; ko: string; el: string; me?: boolean }) {
const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb'];
return (
<View className="items-center rounded-xl py-1.5" style={{ backgroundColor: bg, borderWidth: me ? 2 : 0, borderColor: '#ff7a45' }}>
<Text className="font-batang text-[22px] leading-tight" style={{ color: fg }}>
{c}
</Text>
<Text className="text-[10.5px] font-extrabold" style={{ color: fg }}>
{ko}
</Text>
</View>
);
}
function Note({ term, word }: { term: string; word: string }) {
return (
<Text className="text-[12.5px] leading-relaxed font-semibold text-ink2">
<Text className="font-extrabold text-ink">{term}</Text> = {word}
</Text>
);
}
/** 사주 명식: 가장 센 기운, 오행 막대, 네 기둥, 용어 풀이 */
export function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
const soft = useSoft();
const me = r.me!;
const cols = [...me.pillars].reverse();
const els = Object.entries(me.elements ?? {});
const total = els.reduce((a, [, v]) => a + v, 0);
const gods = [...new Set(me.pillars.flatMap((p) => [p.stem_ten_god, p.branch_ten_god]).filter((g): g is string => !!g && g in TEN_GOD_WORD))];
const strength = me.strength ?? (me.strong == null ? null : me.strong ? '신강' : '신약');
const top = me.top_element;
return (
<Panel
icon={me.scene_icon}
title="사주 명식"
right={
<Pressable onPress={onEdit} hitSlop={8} accessibilityRole="button">
<Text className="text-xs font-extrabold text-orange">생년월일 바꾸기</Text>
</Pressable>
}
>
{!!top && !!strength && (
<View className="flex-row items-center gap-3">
<Art el={top} size={64} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[18px] leading-snug text-ink">
{EL_WORD[top]}({top}) 기운이 가장 센 {strength} 사주
</Text>
<Text className="mt-0.5 text-[13px] font-semibold text-ink2">
나를 돕는 기운 {Math.round((me.support ?? 0) * 100)}% · {me.scene}
</Text>
</View>
</View>
)}
{total > 0 && (
<>
<View className="mt-2.5 h-2.5 flex-row overflow-hidden rounded-full" accessibilityRole="image" accessibilityLabel={els.map(([k, v]) => `${k} ${Math.round(v)}`).join(', ')}>
{els.map(([k, v]) => (
<View key={k} style={{ width: `${(v / total) * 100}%`, backgroundColor: EL_COLOR[k]?.[0] }} />
))}
</View>
<View className="mt-1.5 flex-row justify-between">
{els.map(([k, v]) => (
<View key={k} className="flex-row items-center gap-0.5">
<Art el={k} size={20} />
<Text className="text-[12px] font-extrabold" style={{ color: EL_COLOR[k]?.[0] }}>
{k} {Math.round(v)}
</Text>
</View>
))}
</View>
</>
)}
<View className="mt-3 flex-row gap-1.5">
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
<View key={p?.position ?? `none-${i}`} className="flex-1 gap-1">
<Text className="text-center text-[11px] font-extrabold text-ink3">{p ? `${POS_WORD[p.position]}주` : '시주'}</Text>
{p ? (
<>
<Text className={`text-center text-[11.5px] font-extrabold ${p.position === 'day' ? 'text-orange' : 'text-ink2'}`}>{p.position === 'day' ? '나' : (p.stem_ten_god ?? '')}</Text>
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} me={p.position === 'day'} />
<Char c={p.branch} ko={p.branch_ko} el={p.branch_element} />
<Text className="text-center text-[11.5px] font-extrabold text-ink2">{p.branch_ten_god}</Text>
{p.position === 'month' && <Text className="text-center text-[10.5px] font-extrabold text-ink3">월령</Text>}
</>
) : (
<View className="flex-1 items-center justify-center rounded-xl px-1" style={{ backgroundColor: soft.soft }}>
<Text className="text-center text-[12px] font-extrabold text-ink3">시각 모름</Text>
</View>
)}
</View>
))}
</View>
<View className="mt-3 border-t border-line pt-2.5">
{!!strength && <Note term={strength} word={STRENGTH_WORD[strength] ?? ''} />}
{gods.map((g) => (
<Note key={g} term={g} word={TEN_GOD_WORD[g]} />
))}
<Note term="월령" word="태어난 달의 계절 기운. 명식에서 가장 크게 봐요" />
</View>
{(me.need?.length ?? 0) > 0 && <Text className="mt-2 text-[13px] font-bold text-ink">내 기운에 좋은 날씨: {me.need!.join(' · ')}</Text>}
{me.jeol_warning && <Text className="mt-1 text-xs font-semibold text-warn">태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.</Text>}
</Panel>
);
}
-171
View File
@@ -1,171 +0,0 @@
import type { ResSaju, SajuLock } from '@nalssigak/shared/api/client/types.gen';
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { progress, useLevel } from '@/lib/level';
import { useSaveBirth, type Birth } from '@/lib/saju-birth';
import { useSheet } from '@/lib/sheet';
import { dayWord, Panel } from './parts';
/** 앞으로 7일 흐름 (Lv.2) */
export function Week({ days }: { days: NonNullable<ResSaju['week']> }) {
const soft = useSoft();
return (
<Panel id="saju_week" icon="spiral_calendar" title="앞으로 7일 흐름">
<View className="gap-1">
{days.map((d) => (
<View key={d.day} className="flex-row items-center gap-2 rounded-xl px-2 py-1.5" style={d.best ? { backgroundColor: soft.warm } : undefined}>
<Text numberOfLines={1} className="w-[66px] text-[13px] font-bold text-ink">
{dayWord(d.day, d.weekday)}
</Text>
{d.icon ? <Ic name={d.icon} size={24} /> : <View className="size-6" />}
<Text numberOfLines={1} className="w-[52px] text-[13px] font-bold text-ink2">
{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}
</Text>
<Text numberOfLines={1} className="min-w-0 flex-1 text-[12.5px] font-bold text-ink2">
{d.title}
</Text>
<Text className={`font-bagel text-[15px] ${d.best ? 'text-orange' : 'text-ink'}`}>{d.score}</Text>
</View>
))}
</View>
<Text className="mt-1.5 text-xs font-semibold text-ink3">점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.</Text>
</Panel>
);
}
/** 금전운·일운 (Lv.3) */
export function Money({ money, work }: { money: string[]; work: string[] }) {
const lines = [...money.map((l) => ['money_bag', l]), ...work.map((l) => ['briefcase', l])];
return (
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
<View className="gap-1.5">
{lines.map(([icon, l]) => (
<View key={l} className="flex-row gap-2">
<Ic name={icon} size={20} />
<Text className="min-w-0 flex-1 text-[14px] font-semibold text-ink">{l}</Text>
</View>
))}
</View>
</Panel>
);
}
/** 앞으로 7일 연애운 (Lv.4). 성별을 고르면 이성 인연까지 */
export function Love({ love, birth }: { love: NonNullable<ResSaju['love']>; birth: Birth }) {
const soft = useSoft();
const save = useSaveBirth();
const pick = (g: 'M' | 'F' | null) => void save({ ...birth, gender: g });
return (
<Panel id="saju_love" icon="red_heart" title="앞으로 7일 연애운">
{love.good ? (
<View className="rounded-xl px-3 py-2.5" style={{ backgroundColor: soft.warm }}>
<Text className="text-xs font-extrabold text-heart">연애 기운이 좋은 날</Text>
<Text className="font-jua text-[17px] text-ink">
{dayWord(love.good.day, love.good.weekday)}
{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
</Text>
<Text className="text-[13px] font-semibold text-ink">{love.good.body}</Text>
<Text className="text-[11.5px] font-semibold text-ink3">{love.good.why}</Text>
</View>
) : (
<Text className="text-[13px] font-semibold text-ink2">앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.</Text>
)}
{!!love.caution && (
<Text className="mt-2 text-[13px] font-semibold text-ink">
조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} <Text className="text-ink3">· {love.caution.why}</Text>
</Text>
)}
{love.gender_known ? (
<Text className="mt-2.5 text-xs font-bold text-ink3">
{birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '}
<Text onPress={() => pick(null)} accessibilityRole="button" className="font-extrabold text-orange">
빼고 보기
</Text>
</Text>
) : (
<View className="mt-2.5 flex-row flex-wrap items-center gap-1.5">
<Text className="text-xs font-bold text-ink2">성별을 고르면 이성 인연(재성·관성)까지 봐요</Text>
{(
[
['M', '남성'],
['F', '여성'],
] as const
).map(([g, word]) => (
<Pressable key={g} onPress={() => pick(g)} accessibilityRole="button" className="rounded-full px-2.5 py-1" style={{ backgroundColor: soft.soft }}>
<Text className="text-xs font-bold text-ink2">{word}</Text>
</Pressable>
))}
</View>
)}
</Panel>
);
}
/** 이달·올해 (Lv.6·7) */
export function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResSaju['month']> }) {
return (
<Panel id={id} icon={icon} title={p.label}>
<Text className="font-jua text-[17px] text-ink">
{p.title} <Text className="text-[13px] text-ink3">({p.ten_god})</Text>
</Text>
<Text className="mt-0.5 text-[13.5px] font-semibold text-ink">{p.body}</Text>
{(p.months?.length ?? 0) > 0 && (
<Text className="mt-1.5 text-[13.5px] font-bold text-ink">
{p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}
</Text>
)}
{p.notes?.map((n) => (
<Text key={n} className="mt-1 text-xs font-semibold text-ink3">
{n}
</Text>
))}
</Panel>
);
}
/** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */
export function Locked({ locks }: { locks: SajuLock[] }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const soft = useSoft();
const level = useLevel().data;
if (!locks.length) return null;
const [next, ...rest] = [...locks].sort((a, b) => a.level - b.level);
const close = loggedIn && !!level && level.next_points != null && level.level + 1 === next.level;
return (
<View className="mx-4 rounded-[22px] px-4 py-3.5" style={{ backgroundColor: soft.soft }}>
<View className="flex-row items-center gap-3">
<Ic name="locked" size={32} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] text-ink">{loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}</Text>
<Text className="text-xs font-bold text-ink2">
{loggedIn ? (close && level ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"}
</Text>
</View>
<Pressable onPress={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} accessibilityRole="button" className="rounded-full bg-ink-btn px-3 py-1.5">
<Text className="text-xs font-extrabold text-white">{loggedIn ? '각 모으는 법' : '로그인'}</Text>
</Pressable>
</View>
{close && !!level && (
<View className="mt-2.5 h-1.5 overflow-hidden rounded-full bg-card">
<LinearGradient colors={['#ffb27a', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${Math.round(progress(level) * 100)}%`, borderRadius: 999 }} />
</View>
)}
<View className="mt-2.5 flex-row flex-wrap gap-1.5">
{(loggedIn ? rest : [next, ...rest]).map((l) => (
<View key={l.key} className="rounded-full bg-card px-2.5 py-1">
<Text className="text-[11.5px] font-extrabold text-ink2">
Lv.{l.level} {l.name}
</Text>
</View>
))}
</View>
</View>
);
}
-38
View File
@@ -1,38 +0,0 @@
import { createContext, use, type ReactNode } from 'react';
import { View } from 'react-native';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
export const EL_COLOR: Record<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] };
export const EL_WORD: Record<string, string> = { 木: '나무', 火: '불', 土: '흙', 金: '쇠', 水: '물' };
// 오행 그림 (웹 public/saju). Metro 는 정적 require 만 묶을 수 있어 하나씩 적는다
export const EL_ART: Record<string, number> = {
木: require('../../../../frontend/public/saju/wood.webp'),
火: require('../../../../frontend/public/saju/fire.webp'),
土: require('../../../../frontend/public/saju/earth.webp'),
金: require('../../../../frontend/public/saju/metal.webp'),
水: require('../../../../frontend/public/saju/water.webp'),
};
/** 2026-11-04 + 수 → 11/4(수) */
export const dayWord = (iso: string, weekday: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}(${weekday})`;
/** ?open= 으로 연 칸: 그 칸이 자리를 잡으면 화면이 그 위치로 내려간다 (웹 #hash 스크롤) */
export const OpenTarget = createContext<{ id?: string; onLayout: (y: number) => void }>({ onLayout: () => {} });
/** 흰 판: 아이콘·제목·오른쪽 버튼 */
export function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) {
const target = use(OpenTarget);
const mine = !!id && target.id === id;
return (
<View onLayout={mine ? (e) => target.onLayout(e.nativeEvent.layout.y) : undefined} className="mx-4 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3.5">
<View className="mb-2 flex-row items-center gap-2">
<Ic name={icon} size={28} />
<Text className="font-jua text-[17px] text-ink">{title}</Text>
{right != null && <View className="ml-auto">{right}</View>}
</View>
{children}
</View>
);
}
-131
View File
@@ -1,131 +0,0 @@
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
/** 고르는 칸: 누르면 아래에 칩이 펼쳐진다 (웹 input·select 대신. 숫자 자판 없이 눌러서 고른다) */
export function Box({ label, value, placeholder, open, onPress, disabled, flex = 1 }: { label: string; value: string | null; placeholder: string; open: boolean; onPress: () => void; disabled?: boolean; flex?: number }) {
const soft = useSoft();
return (
<Pressable
onPress={onPress}
disabled={disabled}
accessibilityRole="button"
accessibilityLabel={`${label} ${value ?? placeholder}`}
accessibilityState={{ expanded: open, disabled }}
className={`min-h-[48px] min-w-0 flex-row items-center justify-center gap-1 rounded-2xl px-2 py-2.5 ${disabled ? 'opacity-45' : ''}`}
style={{ flex, backgroundColor: soft.field, borderWidth: 1.5, borderColor: open ? '#ff7a45' : soft.fieldBorder }}
>
<Text numberOfLines={1} className={`text-[17px] font-bold ${value != null ? 'text-ink' : 'text-ink3'}`}>
{value ?? placeholder}
</Text>
<Text className="text-[11px] text-ink3">{open ? '▲' : '▼'}</Text>
</Pressable>
);
}
/** 칩 여러 개 중 하나 고르기 */
export function ChipGrid<K extends string | number>({ items, value, onPick, label, wide }: { items: [K, string][]; value: K | null; onPick: (k: K) => void; label: string; wide?: boolean }) {
const soft = useSoft();
return (
<View accessibilityRole="radiogroup" accessibilityLabel={label} className="flex-row flex-wrap gap-1.5 rounded-2xl p-2" style={{ backgroundColor: soft.soft }}>
{items.map(([k, word]) => {
const on = value === k;
return (
<Pressable key={String(k)} onPress={() => onPick(k)} accessibilityRole="radio" accessibilityState={{ checked: on }} className={`min-h-[40px] items-center justify-center rounded-xl px-1 ${wide ? 'w-[64px]' : 'w-[44px]'} ${on ? 'bg-orange' : 'bg-card'}`}>
<Text className={`text-[14px] font-bold ${on ? 'text-white' : 'text-ink'}`}>{word}</Text>
</Pressable>
);
})}
</View>
);
}
/** 연도: 먼저 10년 단위를 고르고 그 안에서 연도 */
function YearGrid({ value, onPick, label }: { value: number | null; onPick: (y: number) => void; label: string }) {
const thisYear = new Date().getFullYear();
const [decade, setDecade] = useState(value != null ? Math.floor(value / 10) * 10 : 1990);
const decades: [number, string][] = [];
for (let d = 1900; d <= thisYear; d += 10) decades.push([d, `${String(d).slice(2)}년대`]);
const years: [number, string][] = [];
for (let y = decade; y < decade + 10 && y <= thisYear; y++) years.push([y, String(y)]);
return (
<View className="gap-1.5">
<ChipGrid label={`${label} 10년 단위`} items={decades} value={decade} onPick={setDecade} wide />
<ChipGrid label={label} items={years} value={value} onPick={onPick} wide />
</View>
);
}
const MONTHS: [number, string][] = Array.from({ length: 12 }, (_, i) => [i + 1, `${i + 1}월`]);
const daysIn = (y: number | null, m: number | null) => (m == null ? 31 : new Date(y ?? 2000, m, 0).getDate());
export type Ymd = { y: number | null; m: number | null; d: number | null };
/** 생년월일(양력) 고르기: 연도 → 월 → 일 순서로 이어서 펼친다 */
export function DatePick({ value, onChange, label = '' }: { value: Ymd; onChange: (v: Ymd) => void; label?: string }) {
const [open, setOpen] = useState<'y' | 'm' | 'd' | null>(null);
const toggle = (k: 'y' | 'm' | 'd') => setOpen((o) => (o === k ? null : k));
const days: [number, string][] = Array.from({ length: daysIn(value.y, value.m) }, (_, i) => [i + 1, String(i + 1)]);
return (
<View className="gap-1.5">
<View className="flex-row gap-1.5">
<Box label={`${label}년`} value={value.y != null ? `${value.y}년` : null} placeholder="연도" open={open === 'y'} onPress={() => toggle('y')} flex={1.5} />
<Box label={`${label}월`} value={value.m != null ? `${value.m}월` : null} placeholder="월" open={open === 'm'} onPress={() => toggle('m')} />
<Box label={`${label}일`} value={value.d != null ? `${value.d}일` : null} placeholder="일" open={open === 'd'} onPress={() => toggle('d')} />
</View>
{open === 'y' ? (
<YearGrid
label={`${label}년`}
value={value.y}
onPick={(y) => {
onChange({ ...value, y });
setOpen(value.m == null ? 'm' : null);
}}
/>
) : open === 'm' ? (
<ChipGrid
label={`${label}월`}
items={MONTHS}
value={value.m}
onPick={(m) => {
onChange({ ...value, m });
setOpen(value.d == null ? 'd' : null);
}}
wide
/>
) : open === 'd' ? (
<ChipGrid
label={`${label}일`}
items={days}
value={value.d}
onPick={(d) => {
onChange({ ...value, d });
setOpen(null);
}}
/>
) : null}
</View>
);
}
/** 숫자: −/+ 버튼 (분) */
export function Stepper({ value, onChange, min, max, label, unit, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string; unit: string; disabled?: boolean }) {
const soft = useSoft();
const set = (v: number) => onChange(Math.min(max, Math.max(min, v)));
return (
<View className={`min-h-[48px] flex-1 flex-row items-center justify-between rounded-2xl ${disabled ? 'opacity-45' : ''}`} style={{ backgroundColor: soft.field, borderWidth: 1.5, borderColor: soft.fieldBorder }} accessibilityLabel={label}>
<Pressable onPress={() => set(value - 1)} onLongPress={() => set(value - 10)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-3.5 py-2">
<Text className="text-[18px] font-extrabold text-ink2">−</Text>
</Pressable>
<Text className="text-[17px] font-bold text-ink">
{value}
{unit}
</Text>
<Pressable onPress={() => set(value + 1)} onLongPress={() => set(value + 10)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-3.5 py-2">
<Text className="text-[18px] font-extrabold text-ink2">+</Text>
</Pressable>
</View>
);
}
-172
View File
@@ -1,172 +0,0 @@
import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { reading } from '@nalssigak/shared/api/client/sdk.gen';
import type { SajuCard } from '@nalssigak/shared/api/client/types.gen';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef } from 'react';
import { Pressable, View } from 'react-native';
import Svg, { Circle } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useLevel } from '@/lib/level';
import { useRegion } from '@/lib/region';
import { markSajuSeen, toBody, type Birth } from '@/lib/saju-birth';
import { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
import { Match } from './match';
import { MeCard } from './me-card';
import { Locked, Love, Money, Period, Week } from './panels';
const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' };
function DecisionCard({ c }: { c: SajuCard }) {
return (
<View className="flex-row gap-3 rounded-[20px] border-b-4 border-shade bg-card px-4 py-3">
<Ic name={CARD_ICON[c.kind] ?? 'sparkles'} size={32} />
<View className="min-w-0 flex-1">
<Text className="text-[12px] font-extrabold text-orange">{c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}</Text>
<Text className="font-jua text-[17px] leading-snug text-ink">{c.kind === 'when' ? `${c.title} · ${c.sub ?? ''}` : c.body}</Text>
<Text className="mt-0.5 text-[12px] leading-snug font-semibold text-ink3">{(c.kind === 'when' ? c.body : c.sub) ?? ''}</Text>
</View>
</View>
);
}
const RING_R = 46;
const RING_LEN = 2 * Math.PI * RING_R;
function ScoreRing({ score }: { score: number }) {
const soft = useSoft();
return (
<View className="size-[116px] items-center justify-center" accessibilityLabel={`오늘의 점수 ${score}점`}>
<Svg viewBox="0 0 116 116" width={116} height={116} style={{ position: 'absolute', transform: [{ rotate: '-90deg' }] }}>
<Circle cx={58} cy={58} r={RING_R} fill="none" stroke={soft.bar} strokeWidth={11} />
<Circle cx={58} cy={58} r={RING_R} fill="none" stroke="#ff7a45" strokeWidth={11} strokeLinecap="round" strokeDasharray={`${(RING_LEN * score) / 100} ${RING_LEN}`} />
</Svg>
<Text className="font-bagel text-[40px] leading-[44px] text-ink">{score}</Text>
<Text className="text-[11px] font-extrabold text-ink3">오늘의 점수</Text>
</View>
);
}
function ScoreBar({ label, value, width, color, signed }: { label: string; value: number; width: number; color: string; signed?: boolean }) {
const soft = useSoft();
return (
<View className="mt-2">
<View className="flex-row justify-between">
<Text className="text-[12.5px] font-extrabold" style={{ color }}>
{label}
</Text>
<Text className="text-[12.5px] font-extrabold" style={{ color }}>
{`${signed ? (value >= 0 ? '+' : '−') : ''}${Math.abs(value)}점`}
</Text>
</View>
<View className="mt-1 h-2 overflow-hidden rounded-full" style={{ backgroundColor: soft.bar }}>
<View className="h-full rounded-full" style={{ width: `${width}%`, backgroundColor: color }} />
</View>
</View>
);
}
/** 오늘 점수와 할 일, 내 기운, 레벨로 열리는 이번 주·금전·연애·궁합·이달·올해 (웹 SajuPage Reading) */
export function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
const { region } = useRegion();
const { loggedIn } = useAuth();
const queryClient = useQueryClient();
const soft = useSoft();
const ink = String(useCSSVariable('--color-ink'));
const share = useShare();
const level = useLevel().data?.level;
const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined };
// 레벨이 오르면 키가 바뀌어 새로 열린 칸까지 다시 받는다. 사주를 보면 각이 쌓이니 레벨도 새로 받는다
const q = useQuery({
queryKey: ['saju', body, loggedIn, level],
staleTime: 10 * 60_000,
queryFn: async () => {
const { data } = await reading({ body });
if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju');
if (loggedIn) void queryClient.invalidateQueries({ queryKey: myLevelQueryKey() });
return data;
},
});
const shot = useRef<View>(null);
const r = q.data;
useEffect(() => {
if (!r?.today) return;
markSajuSeen();
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score, strength: r.me?.strength ?? '', top_element: r.me?.top_element ?? '' });
}, [r]);
if (q.isPending) return <Text className="px-4 py-16 text-center font-semibold text-ink2">사주를 풀고 있어요…</Text>;
if (!r?.today || !r.me)
return (
<View className="items-center px-4 py-16">
<Text className="text-center font-semibold text-ink2">결과를 불러오지 못했어요.</Text>
<Pressable onPress={() => void q.refetch()} accessibilityRole="button" className="mt-3 rounded-full bg-ink-btn px-4 py-2">
<Text className="text-[13px] font-extrabold text-white">다시 시도</Text>
</Pressable>
</View>
);
const t = r.today;
const matchOpen = !!r.locks?.find((l) => l.key === 'saju_match')?.unlocked;
const title = `오늘 내 날씨 사주 ${t.score}점 · ${t.title}`;
return (
<View className="gap-3">
<View ref={shot} collapsable={false} className="mx-4 mt-3 rounded-[26px] border-b-[5px] border-shade bg-card p-4">
<Text className="text-[12.5px] font-extrabold text-ink3">
{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수
</Text>
<View className="mt-2 flex-row items-center gap-4">
<ScoreRing score={t.score} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[21px] leading-tight text-ink">{t.title}</Text>
<ScoreBar label="사주" value={t.saju_score} width={t.saju_score} color={ink} />
{t.weather_points != null && <ScoreBar label="날씨 영향" value={t.weather_points} width={Math.min(100, Math.abs(t.weather_points) * 3)} color={t.weather_points >= 0 ? '#1f7a4f' : '#e8663a'} signed />}
</View>
</View>
{(t.why?.length ?? 0) > 0 && (
<View className="mt-3 gap-1.5">
{t.why!.map((w) => {
const down = w.startsWith('↓');
return (
<Text key={w} className={`overflow-hidden rounded-xl px-3 py-2 text-[13px] leading-snug font-bold ${down ? 'text-warn' : 'text-ink'}`} style={{ backgroundColor: down ? soft.warm : soft.soft }}>
{w}
</Text>
);
})}
</View>
)}
</View>
<View className="mx-4 gap-2">
{t.cards.map((c) => (
<DecisionCard key={c.kind} c={c} />
))}
</View>
<MeCard r={r} onEdit={onEdit} />
{!!r.week && <Week days={r.week} />}
{!!r.money && <Money money={r.money} work={r.work ?? []} />}
{!!r.love && <Love love={r.love} birth={birth} />}
{matchOpen && <Match birth={birth} />}
{!!r.month && <Period id="saju_month" icon="spiral_calendar" p={r.month} />}
{!!r.year && <Period id="saju_year" icon="sunrise" p={r.year} />}
<Locked locks={(r.locks ?? []).filter((l) => !l.unlocked)} />
<View className="mx-4 flex-row items-center justify-between">
<Text className="text-xs font-semibold text-ink3">재미로 보는 날씨 사주</Text>
<Pressable onPress={() => void share(shot, { title, message: `${title} ${SITE_URL}/saju` })} accessibilityRole="button" className="rounded-full bg-ink-btn px-4 py-2">
<Text className="text-[13px] font-extrabold text-white">공유</Text>
</Pressable>
</View>
</View>
);
}
-31
View File
@@ -1,31 +0,0 @@
import { router } from 'expo-router';
import { Pressable, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
import { Text } from '@/components/text';
import { useSky } from '@/lib/sky';
/** 탭 밖 화면(사주·이야기·게임 등) 머리줄: 뒤로 가기와 제목. 뒤로 갈 곳이 없으면(링크로 바로 열림) 오늘 탭으로 */
export function ScreenHeader({ title, right }: { title: string; right?: React.ReactNode }) {
const { top } = useSafeAreaInsets();
const { kind } = useSky();
const ink = String(useCSSVariable('--color-ink'));
const back = () => (router.canGoBack() ? router.back() : router.replace('/'));
return (
<View style={{ paddingTop: top, backgroundColor: kind === 'night' ? 'rgb(14 20 51 / 0.35)' : 'rgb(255 255 255 / 0.18)' }}>
<View className="h-[54px] flex-row items-center gap-1 px-2">
<Pressable onPress={back} hitSlop={8} accessibilityRole="button" accessibilityLabel="뒤로" className="size-10 items-center justify-center">
<Svg viewBox="0 0 24 24" width={24} height={24} fill="none" stroke={ink} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round">
<Path d="M15 5l-7 7 7 7" />
</Svg>
</Pressable>
<Text numberOfLines={1} className="flex-1 font-jua text-[21px] text-ink">
{title}
</Text>
{right}
</View>
</View>
);
}
-105
View File
@@ -1,105 +0,0 @@
import type { ArticleSummary, ResSeasonWeek } from '@nalssigak/shared/api/client/types.gen';
import { ARTICLE_LABEL, cardBg, dateRange, shortDay } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Fall } from '@/components/fall';
import { Credit, Ic, Skel, Thumb } from '@/components/ui';
import { CARD_BG } from '@/lib/colors';
import { useSky } from '@/lib/sky';
const HEAD_BOX = 'mx-3 mt-3 min-h-[250px] overflow-hidden rounded-[28px] p-5';
const ROW = 'flex-row items-center gap-3 border-b-[1.5px] border-line px-4 py-3.5';
const ROW_SKELS = [0, 1, 2, 3];
// 분류 글자색 (웹 ARTICLE_CAT). 밤엔 밝게
const CAT_COLOR: Record<number, [string, string]> = { 1: ['#1f9d62', '#4fd39a'], 2: ['#7a5cd6', '#b9a6ff'], 3: ['#ff7a45', '#ff8a57'] };
/** 특집 상자와 같은 틀: 머리말 · 제목 두 줄 · 시 한 줄 · 절기 막대 */
export function HeadSkel() {
return (
<View className={`${HEAD_BOX} gap-1.5 bg-card`}>
<Skel className="w-36" />
<Skel className="mt-1 h-7 w-[62%]" />
<Skel className="h-7 w-[40%]" />
<Skel className="mt-auto h-5 w-[72%]" />
<Skel className="mt-2.5 w-[70%]" />
<View className="h-[7px] w-[70%] rounded-full bg-skel" />
</View>
);
}
export function RowsSkel() {
return (
<>
{ROW_SKELS.map((i) => (
<View key={i} className={ROW}>
<View className="flex-1 gap-1.5">
<Skel className="w-12" />
<Skel className="h-4 w-48" />
<Skel className="w-14" />
</View>
<View className="h-[84px] w-[84px] rounded-[18px] bg-skel" />
</View>
))}
</>
);
}
/** 이번 주 특집: 제목·시·절기 막대. 누르면 이번 주 절기 창 */
export function SeasonHead({ week: w, onPress }: { week: ResSeasonWeek; onPress: () => void }) {
const { kind } = useSky();
const night = kind === 'night';
const progress = Math.round((w.progress ?? 0) * 100);
const poem = w.poem_lines ?? [];
return (
<Pressable onPress={onPress} className={HEAD_BOX}>
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'].peach} style={{ position: 'absolute', inset: 0 }} />
<Fall d={100} f={4800} style={{ position: 'absolute', top: '18%', right: 14, width: '38%', alignItems: 'center' }}>
<Ic name="maple" size={140} />
</Fall>
<Text className="text-[13px] font-extrabold text-ink opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</Text>
<Text className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight text-ink">{w.headline}</Text>
{poem.length > 0 && <Text className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[37px] text-ink">{poem.join('\n')}</Text>}
{!!w.term_now && !!w.term_next && (
<View className={`max-w-[70%] ${poem.length ? 'mt-2.5' : 'mt-auto'}`}>
<View className="flex-row justify-between">
<Text className="text-xs font-extrabold text-ink2">
{w.term_now.name} {shortDay(w.term_now.day)}
</Text>
<Text className="text-xs font-extrabold text-ink2">
{w.term_next.name} {shortDay(w.term_next.day)}
</Text>
</View>
<View className="mt-1 h-[7px] overflow-hidden rounded-full bg-[rgb(40_48_74/0.1)]" accessibilityRole="image" accessibilityLabel={`다음 절기까지 ${progress}% 지났어요`}>
<View className="h-full bg-orange" style={{ width: `${progress}%` }} />
</View>
</View>
)}
</Pressable>
);
}
export function ArticleRow({ article: a, onPress }: { article: ArticleSummary; onPress: () => void }) {
const { kind } = useSky();
const night = kind === 'night';
const color = CAT_COLOR[a.category]?.[night ? 1 : 0];
return (
<Pressable onPress={onPress} className={ROW}>
<View className="flex-1">
{!!ARTICLE_LABEL[a.category] && (
<Text className="text-xs font-extrabold" style={{ color }}>
{ARTICLE_LABEL[a.category]}
</Text>
)}
<Text className="mt-0.5 font-jua text-[17.5px] leading-snug text-ink">{a.title}</Text>
<Text className="mt-1 text-xs font-semibold text-ink3">{a.read_minutes}분 읽기</Text>
</View>
<Thumb image={a.image} icon={a.icon} iconSize={54} className="h-[84px] w-[84px] rounded-[18px]">
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
{!!a.image && !!a.image_credit && <Credit text={a.image_credit} />}
</Thumb>
</Pressable>
);
}
-88
View File
@@ -1,88 +0,0 @@
import { getArticleOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { ARTICLE_LABEL, articleMeta, cardBg, dateRange, loadOf, shortDay } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect, useRef } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Credit, Ic, StateBox, Thumb } from '@/components/ui';
import { track } from '@/lib/analytics';
import { CARD_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
import { ArticleSkel, Body } from './parts';
export function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t: string) => void }) {
const q = useQuery(getArticleOptions({ path: { article_id: articleId } }));
const a = q.data?.article;
const night = useSky().kind === 'night';
useEffect(() => {
onTitle(a ? (ARTICLE_LABEL[a.category] ?? '') : '');
}, [a, onTitle]);
const tracked = useRef(0);
useEffect(() => {
if (!a || tracked.current === a.article_id) return;
tracked.current = a.article_id;
track('select_content', { content_type: 'article', item_id: a.article_id, category: ARTICLE_LABEL[a.category] ?? a.category });
}, [a]);
const load = loadOf(q);
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} boxClassName="inset-0" />}</Body>;
return (
<Body>
<Thumb image={a.image} icon={a.icon} iconSize={96} className="mb-3.5 h-[150px] rounded-[20px]">
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
{!!a.image && !!a.image_credit && <Credit text={a.image_credit} />}
</Thumb>
<Text className="text-[13px] font-extrabold text-ink2">{articleMeta(a)}</Text>
<Text className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight text-ink">{a.title}</Text>
{(q.data?.body ?? []).map((t) => (
<Text key={t} className="mb-2.5 text-[15px] leading-[1.7] text-ink">
{t}
</Text>
))}
</Body>
);
}
export function SeasonWeekSheet() {
const { open } = useSheet();
const night = useSky().kind === 'night';
const q = useQuery(getSeasonWeekOptions());
const w = q.data;
const load = loadOf(q);
if (!w?.headline) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." hold={<ArticleSkel />} boxClassName="inset-0" />}</Body>;
return (
<Body>
<View className="mb-3.5 h-[150px] items-center justify-center overflow-hidden rounded-[20px]">
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'].peach} style={{ position: 'absolute', inset: 0 }} />
<Ic name="maple" size={96} />
</View>
<Text className="text-[13px] font-extrabold text-ink2">{w.start && w.end ? dateRange(w.start, w.end) : '이번 주'}</Text>
<Text className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight text-ink">{w.headline}</Text>
{(w.poem_lines ?? []).length > 0 && (
<View className="mb-2.5">
<Text className="font-batang text-[17px] leading-[29px] text-ink">
{w.poem_lines?.join(' ')}
</Text>
{!!w.author && <Text className="text-xs font-semibold text-ink3">{w.author}</Text>}
</View>
)}
{!!w.term_now && !!w.term_next && (
<Text className="mb-2.5 text-[15px] leading-[1.7] text-ink">
지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요.
</Text>
)}
{(w.news ?? []).map((n) => (
<Pressable key={n.code} onPress={() => open({ type: 'article', articleId: n.article_id })} className="flex-row items-center gap-2.5 border-b-[1.5px] border-line py-2.5">
<Ic name={n.icon} size={32} />
<Text className="flex-1 font-jua text-base text-ink">{n.title}</Text>
</Pressable>
))}
</Body>
);
}
-393
View File
@@ -1,393 +0,0 @@
import {
addCommentMutation,
addTalkCommentMutation,
agreeTermsMutation,
blockAuthorMutation,
deleteCommentMutation,
getFeedQueryKey,
likeCommentMutation,
listBlockedQueryKey,
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listTalkCommentsInfiniteOptions,
listTalkCommentsInfiniteQueryKey,
meQueryKey,
reportCommentMutation,
unlikeCommentMutation,
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { ReportReason, type CommentData, type ResCommentList } from '@nalssigak/shared/api/client/types.gen';
import { ago, loadOf } from '@nalssigak/shared/lib';
import { useInfiniteQuery, useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query';
import { useEffect, useRef, useState } from 'react';
import { Linking, Pressable, TextInput, View } from 'react-native';
import { Text } from '@/components/text';
import { useCSSVariable } from 'uniwind';
import { Avatar, Skel, StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet, type CommentTarget } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { Body, ErrorLine, Field, HeartIcon, useSoft } from './parts';
const NOT_FOUND = 3001; // 서버 ErrorType.NOT_FOUND
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍'];
const N3 = [0, 1, 2];
const REPORT_REASONS = [
[ReportReason.ABUSE, '욕설·비하'],
[ReportReason.AD, '광고'],
[ReportReason.PRIVACY, '개인정보 노출'],
[ReportReason.OTHER, '기타'],
] as const;
export const isCommentList = (q: { queryKey: readonly unknown[] }) => ['listComments', 'listTalkComments'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '');
const isTalkList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listTalks';
/** 댓글 목록 캐시 키: 지우기·신고 뒤 다시 받을 때 쓴다 */
function commentListKey(to: CommentTarget) {
return 'talkId' in to ? listTalkCommentsInfiniteQueryKey({ path: { talk_id: to.talkId } }) : listCommentsInfiniteQueryKey({ path: { post_id: to.postId } });
}
function Chip({ label, onPress, disabled, danger }: { label: string; onPress: () => void; disabled?: boolean; danger?: boolean }) {
const s = useSoft();
return (
<Pressable onPress={onPress} disabled={disabled} className={`rounded-[12px] px-3 py-2 disabled:opacity-50 ${danger ? 'bg-heart' : ''}`} style={danger ? undefined : { backgroundColor: s.soft }}>
<Text className={`text-[13px] font-extrabold ${danger ? 'text-white' : 'text-ink'}`}>{label}</Text>
</Pressable>
);
}
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
function CommentMenu({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed');
const [failed, setFailed] = useState(false);
const report = useMutation(reportCommentMutation());
const block = useMutation(blockAuthorMutation());
const pending = report.isPending || block.isPending;
const finish = (notice: string, done: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true);
done();
setStep('closed');
onNotice(notice);
queryClient.invalidateQueries({ predicate: isCommentList });
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() });
},
onError: () => setFailed(true),
});
const go = (next: typeof step) => {
setFailed(false);
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', ...to } });
setStep(next);
};
return (
<>
<Pressable onPress={() => go(step === 'closed' ? 'menu' : 'closed')} hitSlop={10} accessibilityRole="button" accessibilityState={{ expanded: step !== 'closed' }} accessibilityLabel="댓글 메뉴" className="px-1">
<Text className="text-sm font-extrabold text-ink3">⋯</Text>
</Pressable>
{step !== 'closed' && (
<View className="mt-2 w-full flex-row flex-wrap items-center gap-1.5" accessibilityLabel="댓글 메뉴">
{step === 'menu' && (
<>
<Chip label="신고하기" onPress={() => go('report')} />
<Chip label="이 사람 차단하기" onPress={() => go('block')} />
</>
)}
{step === 'report' &&
REPORT_REASONS.map(([reason, label]) => (
<Chip key={reason} label={label} disabled={pending} onPress={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.', () => track('report', { content_type: 'comment', reason })))} />
))}
{step === 'block' && (
<>
<Text className="w-full text-[13px] font-bold text-ink">{c.nickname}님 댓글을 더는 안 볼까요?</Text>
<Chip label="차단하기" danger disabled={pending} onPress={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.', () => track('block', { content_type: 'comment' })))} />
<Chip label="취소" disabled={pending} onPress={() => go('closed')} />
</>
)}
{failed && (
<Text className="w-full text-[13px] font-bold text-heart" accessibilityRole="alert">
잠시 뒤에 다시 해 주세요.
</Text>
)}
</View>
)}
</>
);
}
function CommentsSkel() {
return (
<View>
{N3.map((i) => (
<View key={i} className="flex-row items-start gap-2.5 py-2">
<View className="size-[34px] rounded-full bg-skel" />
<View className="flex-1 gap-1.5">
<Skel className="w-3/4" />
<Skel className="w-24" />
</View>
</View>
))}
</View>
);
}
function CommentRow({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
const { region } = useRegion();
const queryClient = useQueryClient();
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
const [liked, setLiked] = useState(c.liked);
const [count, setCount] = useState(c.like_count);
const like = useMutation(likeCommentMutation());
const unlike = useMutation(unlikeCommentMutation());
const remove = useMutation(deleteCommentMutation());
const [removeFailed, setRemoveFailed] = useState(false);
const [likeFailed, setLikeFailed] = useState(false);
// 좋아요는 로그인 없이 된다 (웹과 같이)
const toggle = () => {
if (like.isPending || unlike.isPending) return;
const next = !liked;
setLikeFailed(false);
setLiked(next);
setCount((n) => n + (next ? 1 : -1));
const revert = () => {
setLiked(!next);
setCount(c.like_count);
};
(next ? like : unlike).mutate(
{ path: { comment_id: c.comment_id } },
{
onSuccess: (res) => {
if (res.result?.success) {
setLiked(!!res.liked);
if (res.like_count != null) setCount(res.like_count);
if (next) track('like', { content_type: 'comment', item_id: c.comment_id });
return;
}
revert();
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: commentListKey(to) });
else setLikeFailed(true);
},
onError: () => {
revert();
setLikeFailed(true);
},
},
);
};
// 지우는 동안은 흐리게 두고, 성공하면 다시 받기 전에 목록 캐시에서 바로 뺀다
const del = () => {
setRemoveFailed(false);
remove.mutate(
{ path: { comment_id: c.comment_id } },
{
onSuccess: async (res) => {
if (!res.result?.success) return setRemoveFailed(true);
const key = commentListKey(to);
await queryClient.cancelQueries({ queryKey: key });
queryClient.setQueryData<InfiniteData<ResCommentList>>(key, (data) =>
data ? { ...data, pages: data.pages.map((p) => ({ ...p, comments: p.comments?.filter((x) => x.comment_id !== c.comment_id) })) } : data,
);
queryClient.invalidateQueries({ queryKey: key });
if ('talkId' in to) queryClient.invalidateQueries({ predicate: isTalkList });
else queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
},
onError: () => setRemoveFailed(true),
},
);
};
return (
<View className={`flex-row items-start gap-2.5 py-2 ${remove.isPending ? 'opacity-50' : ''}`}>
<Avatar character={c.character} color={c.color} mood={c.mood} />
<View className="flex-1">
<Text className="text-sm text-ink">
<Text className="font-extrabold">{c.nickname} </Text>
{c.official && (
<>
<Text className="bg-orange text-[10.5px] font-extrabold text-white">{' 날씨각 '}</Text>{' '}
</>
)}
{c.body}
</Text>
<View className="mt-0.5 flex-row flex-wrap items-center">
<Text className="text-xs font-bold text-ink3">
{ago(c.created_at)} · {likeFailed ? <Text className="text-heart">좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요</Text> : `좋아요 ${count}개`}
{c.mine && (
<>
{' · '}
<Text onPress={remove.isPending ? undefined : del} className={removeFailed && !remove.isPending ? 'text-heart' : 'text-ink3'}>
{remove.isPending ? '지우는 중…' : removeFailed ? '못 지웠어요 · 다시' : '지우기'}
</Text>
</>
)}
</Text>
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} to={to} onNotice={onNotice} />}
</View>
</View>
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
<HeartIcon size={16} fill={liked ? heart : 'none'} stroke={liked ? heart : ink3} />
</Pressable>
</View>
);
}
/** 포스트 댓글, 또는 사람 글 댓글(로그인한 사람만 쓴다) */
export function CommentsSheet({ to, draft }: { to: CommentTarget; draft?: string }) {
const { region } = useRegion();
const { me } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
const talkId = 'talkId' in to ? to.talkId : undefined;
const postId = 'postId' in to ? to.postId : undefined;
// 둘 중 하나만 받는다
const postList = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId ?? 0 } }),
initialPageParam: { path: { post_id: postId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: postId != null,
});
const talkList = useInfiniteQuery({
...listTalkCommentsInfiniteOptions({ path: { talk_id: talkId ?? 0 } }),
initialPageParam: { path: { talk_id: talkId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: talkId != null,
});
const list = talkId != null ? talkList : postList;
const addPost = useMutation(addCommentMutation());
const addTalk = useMutation(addTalkCommentMutation());
const add = { isPending: addPost.isPending || addTalk.isPending };
const agree = useMutation(agreeTermsMutation());
const s = useSoft();
const [addFailed, setAddFailed] = useState(false);
const [askTerms, setAskTerms] = useState(false);
const [notice, setNotice] = useState('');
const [text, setText] = useState(draft ?? '');
const inputRef = useRef<TextInput>(null);
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? [];
useEffect(() => {
if (!notice) return;
const t = setTimeout(() => setNotice(''), 3000);
return () => clearTimeout(t);
}, [notice]);
const send = () => {
const body = text.trim();
if (!body || add.isPending) return;
setAddFailed(false);
const handlers = {
onSuccess: (res: { result?: { success?: boolean; desc?: string } }) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
setAddFailed(!res.result?.success);
if (!res.result?.success) return;
setText('');
queryClient.invalidateQueries({ queryKey: commentListKey(to) });
if (talkId != null) {
track('talk_comment', { talk_id: talkId });
queryClient.invalidateQueries({ predicate: isTalkList });
} else if (postId != null) {
track('comment', { post_id: postId });
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
}
},
onError: () => setAddFailed(true),
};
if (talkId != null) addTalk.mutate({ path: { talk_id: talkId }, body: { body } }, handlers);
else if (postId != null) addPost.mutate({ path: { post_id: postId }, body: { body, region: region.code } }, handlers);
};
// 댓글은 로그인 없이 '○○구 익명'으로 쓴다. 로그인했으면 약관에 동의해야 쓸 수 있고, 동의하면 쓰던 댓글을 바로 올린다
const submit = () => {
if (talkId != null && !me) return open({ type: 'login', then: { type: 'comments', ...to, draft: text } });
if (me && !me.terms_agreed) return setAskTerms(true);
send();
};
const agreeAndSend = () => {
setAddFailed(false);
agree.mutate(
{},
{
onSuccess: (res) => {
if (!res.result?.success) return setAddFailed(true);
queryClient.setQueryData(meQueryKey(), res);
track('terms_agree', {});
setAskTerms(false);
send();
},
onError: () => setAddFailed(true),
},
);
};
return (
<>
<Body>
{comments.length ? (
<>
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
{comments.map((c) => (
<CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} to={to} onNotice={setNotice} />
))}
{list.hasNextPage && (
<Pressable onPress={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50">
<Text className="text-center text-sm font-bold text-ink3">{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}</Text>
</Pressable>
)}
</>
) : loadOf(list) === 'loading' ? (
<CommentsSkel />
) : (
<StateBox load={loadOf(list)} onRetry={() => list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={<CommentsSkel />} boxClassName="inset-0" />
)}
</Body>
{askTerms ? (
<View className="mx-3 gap-2 rounded-[16px] p-3" style={{ backgroundColor: s.soft }} accessibilityLabel="이용약관 동의">
<Text className="text-[13px] font-bold text-ink">댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.</Text>
<View className="flex-row gap-2">
<Pressable onPress={() => void Linking.openURL(`${SITE_URL}/terms.html`)} accessibilityRole="link" className="flex-1 rounded-[12px] bg-card p-2.5">
<Text className="text-center text-[13px] font-extrabold text-ink">이용약관 보기</Text>
</Pressable>
<Pressable onPress={agreeAndSend} disabled={agree.isPending || add.isPending} className="flex-1 rounded-[12px] bg-orange p-2.5 disabled:opacity-60">
<Text className="text-center text-[13px] font-extrabold text-white">동의하고 쓰기</Text>
</Pressable>
</View>
</View>
) : (
<View className="flex-row justify-around pt-1" accessibilityLabel="빠른 이모지">
{EMOJIS.map((e) => (
<Pressable
key={e}
disabled={add.isPending}
className="disabled:opacity-40"
onPress={() => {
setText((t) => (t + e).slice(0, 60));
inputRef.current?.focus();
}}
>
<Text className="text-[22px]">{e}</Text>
</Pressable>
))}
</View>
)}
{addFailed ? <ErrorLine className="h-4 text-xs leading-4" text="댓글을 올리지 못했어요. 다시 해 주세요." /> : <Text className="h-4 text-center text-xs leading-4 font-bold text-ink2">{notice}</Text>}
<View className="flex-row items-center gap-2.5 border-t border-line px-3 py-2.5">
<View className="flex-1">
<Field ref={inputRef} round value={text} onChangeText={setText} editable={!add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : talkId != null ? '로그인하고 댓글 달기…' : '댓글 달기…'} accessibilityLabel="댓글" returnKeyType="send" onSubmitEditing={submit} />
</View>
<Pressable onPress={submit} disabled={add.isPending || !text.trim()} className="disabled:opacity-40">
<Text className="font-extrabold text-rain">{add.isPending ? '올리는 중…' : '게시'}</Text>
</Pressable>
</View>
</>
);
}
-229
View File
@@ -1,229 +0,0 @@
import { getIndexOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { Factor, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen';
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect, useRef } from 'react';
import { View } from 'react-native';
import { Text } from '@/components/text';
import Svg, { Circle, Line, Polygon, Text as SvgText, TSpan } from 'react-native-svg';
import { Ic, Skel, StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useRegion } from '@/lib/region';
import { useSky } from '@/lib/sky';
import { Body, useSoft } from './parts';
const SLOT_KEYS = ['morning', 'day', 'evening', 'night'] as const;
const SLOT_NAMES = { morning: '아침', day: '낮', evening: '저녁', night: '밤' } as const;
const N4 = [0, 1, 2, 3];
const N6 = [0, 1, 2, 3, 4, 5];
const labelLines = (label: string) => {
const cut = label.indexOf(' ');
return cut < 0 ? [label] : [label.slice(0, cut), label.slice(cut + 1)];
};
function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) {
const night = useSky().kind === 'night';
const c = size / 2;
const r = size / 2 - 40;
const n = factors.length;
const pt = (i: number, v: number) => {
const a = -Math.PI / 2 + (i * 2 * Math.PI) / n;
return [c + Math.cos(a) * r * v, c + Math.sin(a) * r * v] as const;
};
const ring = (v: number) => factors.map((_, i) => pt(i, v).join(',')).join(' ');
return (
<View className="mt-2 items-center" accessibilityRole="image" accessibilityLabel={`${name} 요소별 점수`}>
<Svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
{[0.25, 0.5, 0.75, 1].map((v) => (
<Polygon key={v} points={ring(v)} fill={v === 1 ? (night ? '#222a5c' : '#f7f9fc') : 'none'} stroke={night ? 'rgba(255,255,255,0.18)' : '#d9e2ef'} strokeWidth={1.5} />
))}
{factors.map((f, i) => (
<Line key={f.axis} x1={c} y1={c} x2={pt(i, 1)[0]} y2={pt(i, 1)[1]} stroke={night ? 'rgba(255,255,255,0.12)' : '#e3e9f2'} strokeWidth={1.5} />
))}
<Polygon points={factors.map((f, i) => pt(i, f.value / 100).join(',')).join(' ')} fill="rgba(255,122,69,0.38)" stroke="#ff7a45" strokeWidth={3} strokeLinejoin="round" />
{factors.map((f, i) => (
<Circle key={f.axis} cx={pt(i, f.value / 100)[0]} cy={pt(i, f.value / 100)[1]} r={4.5} fill="#fff" stroke="#ff7a45" strokeWidth={2.5} />
))}
{factors.map((f, i) => {
const lines = labelLines(f.label);
const [x, y] = pt(i, 1.24);
return (
<SvgText key={f.axis} x={x} y={y - (lines.length - 1) * 7} textAnchor="middle" fontFamily="Jua_400Regular" fontSize={13} fill={night ? '#eef1ff' : '#28304a'}>
{lines.map((line, k) => (
<TSpan key={k} x={x} dy={k === 0 ? 4 : 14}>
{line}
</TSpan>
))}
</SvgText>
);
})}
</Svg>
</View>
);
}
function GakSkel() {
const s = useSoft();
return (
<View>
<View className="flex-row items-center gap-3">
<View className="size-[58px] rounded-full bg-skel" />
<View className="flex-1 gap-1.5">
<Skel className="h-6 w-28" />
<Skel className="w-4/5" />
</View>
<Skel className="h-10 w-14" />
</View>
<View className="mt-2 aspect-square w-full max-w-[250px] self-center rounded-full bg-skel" />
<View className="mt-2.5 flex-row gap-1.5">
{N4.map((i) => (
<View key={i} className="flex-1 items-center gap-1.5 rounded-2xl px-1 py-2.5" style={{ backgroundColor: s.soft }}>
<Skel className="w-8" />
<Skel className="h-6 w-9" />
</View>
))}
</View>
<View className="mt-3.5 gap-3">
{N6.map((i) => (
<View key={i} className="flex-row items-center gap-2.5">
<Skel className="w-[70px]" />
<View className="h-[9px] flex-1 rounded-full bg-skel" />
<Skel className="w-10" />
</View>
))}
</View>
</View>
);
}
export function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) {
const { region } = useRegion();
const s = useSoft();
const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } }));
const d: ResIndexDetail | undefined = q.data;
const g = d?.index;
useEffect(() => {
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거');
}, [g, onTitle]);
// 지역이 바뀌어 다시 받아도 한 번만 보낸다
const tracked = useRef(0);
useEffect(() => {
if (!g || tracked.current === g.index_id) return;
tracked.current = g.index_id;
track('view_gak', { index_id: g.index_id, gak_name: g.name, score: g.score, rank: g.rank });
}, [g]);
const load = loadOf(q);
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} boxClassName="inset-0" />}</Body>;
const factors = d.factors ?? [];
const bands = d.bands ?? [];
const now = bands.find((b) => b.current);
return (
<Body>
<View className="flex-row items-center gap-3">
<Ic name={g.icon} size={58} />
<View className="flex-1">
<Text className="font-jua text-[22px] text-ink">{g.name}</Text>
{!!d.description && <Text className="mt-0.5 text-[13.5px] font-semibold text-ink2">{d.description}</Text>}
</View>
<Text className={`font-bagel text-[42px] ${g.active ? 'text-orange' : 'text-ink3'}`}>{g.score}</Text>
</View>
{!g.active && <Text className="mt-2 text-[13px] font-bold text-ink2">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</Text>}
{now && (
<Text className="mt-3 overflow-hidden rounded-2xl px-3.5 py-2.5 text-[14.5px] font-bold text-ink" style={{ backgroundColor: s.warm }}>
<Text className="font-jua text-orange">
{now.low}~{now.high}점{' '}
</Text>
{now.text}
</Text>
)}
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
{g.slots && g.slots.length > 0 && (
<View className="mt-2.5 flex-row gap-1.5" accessibilityLabel="오늘 시간대별 점수">
{SLOT_KEYS.map((k) => {
const sl = g.slots?.find((x) => x.slot === k);
const cur = g.active && g.slot === k;
return (
<View key={k} className="flex-1 items-center rounded-2xl px-1 py-2" style={{ backgroundColor: cur ? s.warm : s.soft }}>
<Text className="text-xs font-extrabold text-ink2">
{SLOT_NAMES[k]}
{cur && ' · 지금'}
</Text>
<Text className={`font-bagel text-xl ${sl ? 'text-orange' : 'text-ink3'}`}>{sl ? sl.score : '–'}</Text>
</View>
);
})}
</View>
)}
{g.trend && g.trend.length > 0 && (
<View className="mt-2.5 flex-row gap-1.5">
{g.trend.map((t) => (
<View key={t.day} className="flex-1 items-center rounded-2xl px-1 py-2.5" style={{ backgroundColor: s.soft }}>
<Text numberOfLines={1} className="text-xs font-extrabold text-ink2">
{t.label}
</Text>
<Text className="font-bagel text-2xl text-orange">{t.score}</Text>
<Text className={`text-[11px] leading-4 font-extrabold text-ink2 ${t.estimated ? '' : 'opacity-0'}`}>예상</Text>
</View>
))}
</View>
)}
{bands.length > 0 && (
<View className="mt-3.5 gap-1.5" accessibilityLabel="점수 구간별 설명">
{bands.map((b) => (
<View key={b.low} className={`flex-row items-start gap-2 ${b.current ? '' : 'opacity-45'}`}>
<View className={`w-[62px] items-center rounded-full py-px ${b.current ? 'bg-orange' : 'bg-ink3'}`}>
<Text className="font-jua text-xs text-white">
{b.low}~{b.high}
</Text>
</View>
<Text className="flex-1 text-[13px] font-semibold text-ink">{b.text}</Text>
</View>
))}
</View>
)}
<View className="mt-3.5 gap-2.5">
{factors.map((f) => (
<View key={f.axis}>
<View className="flex-row items-center gap-2.5">
<Text className="w-[84px] text-[13.5px] font-bold text-ink">{f.label}</Text>
<View className="h-[9px] flex-1 overflow-hidden rounded-full" style={{ backgroundColor: s.bar }}>
<LinearGradient colors={['#ffc86e', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${f.value}%` }} />
</View>
<Text className="w-[52px] text-right text-xs text-ink2">비중 {f.weight}%</Text>
</View>
<Text className="mt-0.5 ml-[94px] text-[12.5px] font-semibold text-ink2">{f.note}</Text>
</View>
))}
</View>
<View className="mt-3.5 gap-1.5">
{!!d.zero_reason && (
<Text className="text-[13px] font-semibold text-ink2">
<Text className="font-bold text-heart">오늘 걸린 조건:</Text> {d.zero_reason}
</Text>
)}
{factors.length > 0 && (
<Text className="text-[13px] font-semibold text-ink2">
<Text className="font-bold text-ink">계산 방법:</Text> 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요
</Text>
)}
{!!d.zero_rules && (
<Text className="text-[13px] font-semibold text-ink2">
<Text className="font-bold text-ink">점수 깎이는 조건:</Text> {d.zero_rules}
</Text>
)}
{!!d.limit && (
<Text className="text-[13px] font-semibold text-ink2">
<Text className="font-bold text-ink">반영 못 한 것:</Text> {d.limit}
</Text>
)}
</View>
</Body>
);
}
-47
View File
@@ -1,47 +0,0 @@
import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen';
import { GoogleSignin, isErrorWithCode, isSuccessResponse, statusCodes } from '@react-native-google-signin/google-signin';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { Platform, Pressable, View } from 'react-native';
import { Text } from '@/components/text';
/** 구글로 계속하기. 서버에 클라이언트 ID가 없거나 안드로이드가 아니면 그리지 않는다 */
export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) {
const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity, enabled: Platform.OS === 'android' }).data?.google_client_id;
const login = useMutation(googleLoginMutation());
const [busy, setBusy] = useState(false);
const [broken, setBroken] = useState(false);
const press = async () => {
if (!clientId) return;
setBroken(false);
setBusy(true);
try {
GoogleSignin.configure({ webClientId: clientId });
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
const res = await GoogleSignin.signIn();
if (!isSuccessResponse(res)) return;
const token = res.data.idToken;
if (!token) return onFail();
login.mutate({ body: { credential: token } }, { onSuccess: onResult, onError: onFail });
} catch (e) {
if (isErrorWithCode(e) && e.code === statusCodes.IN_PROGRESS) return;
console.error('[google] sign in', e);
setBroken(true);
} finally {
setBusy(false);
}
};
if (Platform.OS !== 'android' || !clientId) return null;
const pending = busy || login.isPending;
return (
<View className="gap-2">
<Pressable onPress={press} disabled={pending} className="rounded-full border-[1.5px] border-line bg-white p-3 disabled:opacity-60" accessibilityRole="button">
<Text className="text-center text-[15px] font-extrabold text-[#28304a]">{pending ? '구글로 로그인 중…' : '구글로 계속하기'}</Text>
</Pressable>
{broken && <Text className="text-center text-[13px] font-bold text-ink3">구글 로그인을 하지 못했어요. 잠시 뒤에 다시 해 주세요.</Text>}
</View>
);
}
-109
View File
@@ -1,109 +0,0 @@
import { subscribeAuth } from '@nalssigak/shared/api/auth';
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
import { KeyboardAvoidingView, Modal, Pressable, View } from 'react-native';
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 { RegionSheet } from './region';
import { WeatherWhySheet } from './weather-why';
export function SheetProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<SheetState>(null);
const open = useCallback((s: Exclude<SheetState, null>) => {
track('sheet_open', { sheet: s.type });
setState(s);
}, []);
const close = useCallback(() => setState(null), []);
const api = useMemo(() => ({ open, close }), [open, close]);
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
useEffect(() => subscribeAuth((reason) => reason === 'required' && open({ type: 'login' })), [open]);
return (
<SheetContext value={api}>
{children}
<SheetHost state={state} onClose={close} />
</SheetContext>
);
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', weatherWhy: '날씨 점수는 이렇게 나와요', level: '내 레벨', levelUp: '레벨이 올랐어요' } as const;
/** 판만 아래에서 올라온다 (웹 b-sheet: 0.26초, 40px 아래·흐릿하게에서) */
function Rise({ children }: { children: ReactNode }) {
const reduce = useReducedMotion();
const p = useSharedValue(reduce ? 1 : 0);
useEffect(() => {
p.value = withTiming(1, { duration: 260, easing: Easing.bezier(0.2, 0.9, 0.3, 1) });
}, [p]);
const anim = useAnimatedStyle(() => ({ opacity: 0.4 + 0.6 * p.value, transform: [{ translateY: 40 * (1 - p.value) }] }));
return <Animated.View style={[{ width: '100%', maxHeight: '86%', alignItems: 'center' }, anim]}>{children}</Animated.View>;
}
/** 아래에서 올라오는 창. 배경은 제자리에서 서서히. 바깥을 누르거나 뒤로 가기(안드로이드)로 닫는다 */
function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () => void }) {
// 닫는 동안(배경이 사라지는 동안)에도 마지막 내용을 그대로 보여 준다. 열 때마다 판을 새로 올린다
const [last, setLast] = useState<SheetState>(next);
const [isOpen, setIsOpen] = useState(next != null);
const [opens, setOpens] = useState(0);
if (next && next !== last) setLast(next);
if ((next != null) !== isOpen) {
setIsOpen(next != null);
if (next) setOpens((n) => n + 1);
}
const state = next ?? last;
const { open } = useSheet();
const { bottom } = useSafeAreaInsets();
const [gakTitle, setGakTitle] = useState('');
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 : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : state.type === 'myGak' ? '내 각' : TITLES[state.type];
return (
<Modal visible={next != null} transparent animationType="fade" onRequestClose={onClose} statusBarTranslucent>
{/* 안드로이드도 화면 끝까지 그려(edge-to-edge) 창이 줄지 않으니 양쪽 모두 키보드 높이만큼 밀어 올린다 */}
<KeyboardAvoidingView behavior="padding" className="flex-1 justify-end">
<Pressable onPress={onClose} accessibilityLabel="닫기" className="absolute inset-0 bg-[rgb(20_26_45/0.45)]" />
{state && (
<Rise key={opens}>
<View accessibilityViewIsModal accessibilityLabel={title} className="w-full max-w-[440px] shrink rounded-t-[22px] bg-card" style={{ paddingBottom: bottom }}>
<View className="border-b border-line px-4 pt-2 pb-2.5">
<View className="mb-2.5 h-1 w-10 self-center rounded-full bg-line" />
<Text numberOfLines={1} className="px-10 text-center text-[15px] font-extrabold text-ink">
{title}
</Text>
<Pressable onPress={onClose} hitSlop={10} accessibilityRole="button" accessibilityLabel="닫기" className="absolute right-3 bottom-2 size-[30px] items-center justify-center">
<Text className="text-xl text-ink2">×</Text>
</Pressable>
</View>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'comments' && <CommentsSheet to={'talkId' in state ? { talkId: state.talkId } : { postId: state.postId }} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={state.why} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
{state.type === 'level' && <LevelSheet />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'myGak' && <MyGakSheet gak={state.gak} onDone={onClose} />}
{state.type === 'levelUp' && <LevelUpSheet level={state.level} />}
</View>
</Rise>
)}
</KeyboardAvoidingView>
</Modal>
);
}
-138
View File
@@ -1,138 +0,0 @@
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<string, string> = { saju: '/saju', react: '/', talk: '/talk' };
const ACTION_FEATURE: Record<string, string> = { tarot: 'tarot', checkin: 'tarot' };
function Bar({ value }: { value: number }) {
const s = useSoft();
return (
<View className="h-2 overflow-hidden rounded-full" style={{ backgroundColor: s.bar }}>
<LinearGradient colors={['#ffb27a', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${Math.round(value * 100)}%`, borderRadius: 999 }} />
</View>
);
}
/** 내 정보 위쪽: 레벨·모은 각·다음 레벨에서 열리는 것. 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 (
<View accessibilityLabel="내 레벨" className="rounded-2xl px-3.5 py-3" style={{ backgroundColor: s.warm }}>
<View className="flex-row items-center gap-2">
<Ic name={levelIcon(level.level)} size={28} />
<Text className="font-jua text-[16px] text-ink">
Lv.{level.level} {level.name}
</Text>
<Text className="ml-auto font-bagel text-[15px] text-ink">{level.points}각</Text>
</View>
<View className="mt-2">
<Bar value={progress(level)} />
</View>
<View className="mt-1.5 flex-row items-center justify-between gap-2">
<Text className="shrink text-xs font-bold text-ink2">
{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}`}
</Text>
{link && (
<Pressable onPress={() => open({ type: 'level' })} hitSlop={8} accessibilityRole="button">
<Text className="text-xs font-bold text-orange">각 모으는 법 ›</Text>
</Pressable>
)}
</View>
</View>
);
}
/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */
export function LevelSheet() {
const level = useLevel().data;
const go = useCloseAndGo();
const s = useSoft();
if (!level) return null;
const steps = (level.unlocks ?? []).reduce<Record<number, string[]>>((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 (
<Body className="gap-4">
<LevelCard link={false} />
<View>
<Text className="mb-2 text-sm font-extrabold text-ink">오늘 받을 수 있는 각</Text>
<View className="rounded-2xl border-b-4 border-shade bg-card">
{actions.map((a, i) => {
const done = a.earned >= a.cap;
const to = ACTION_TO[a.action];
return (
<Pressable key={a.action} disabled={!to || done} onPress={() => 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' : ''}`}>
<View className={`size-5 items-center justify-center rounded-full ${done ? 'bg-[#1f9d62]' : 'bg-[#dfe5ef]'}`}>{done && <Text className="text-[11px] text-white">✓</Text>}</View>
<Text className={`text-[13.5px] font-bold ${done ? 'text-ink3 line-through' : 'text-ink'}`}>{a.name}</Text>
<Text className="ml-auto font-bagel text-[13px] text-orange">{done ? `오늘 ${a.earned}각 받음` : a.earned > 0 ? `${a.earned}/${a.cap}각` : `+${a.points}각`}</Text>
{!!to && !done && <Text className="text-ink3">›</Text>}
</Pressable>
);
})}
</View>
<Text className="mt-1.5 text-xs font-semibold text-ink3">{level.streak > 0 ? `${level.streak}일째 연속 출석 중 · 7일 연속이면 +50각` : '7일 연속 출석하면 +50각을 더 받아요'}</Text>
</View>
<View>
<Text className="mb-2 text-sm font-extrabold text-ink">레벨이 오르면 열려요</Text>
<View className="gap-1.5">
{(level.levels ?? []).map(({ level: lv, name, points }) => {
const reached = level.level >= lv;
return (
<View key={lv} className="flex-row items-center gap-2.5 rounded-xl px-2.5 py-2" style={lv === level.level ? { backgroundColor: s.warm } : undefined}>
<Ic name={levelIcon(lv)} size={28} style={reached ? undefined : { opacity: 0.4 }} />
<View className="min-w-0 flex-1">
<Text className="text-[13.5px] font-extrabold text-ink">
Lv.{lv} {name} <Text className="font-semibold text-ink3">· {points}각</Text>
</Text>
<Text className="text-xs font-semibold text-ink2">{lv === 1 ? '날씨각의 기본 기능 모두' : (steps[lv] ?? []).join(', ')}</Text>
</View>
</View>
);
})}
</View>
</View>
</Body>
);
}
/** 레벨이 오른 순간 */
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 (
<Body className="items-center gap-2 px-6 pb-6">
<Ic name={levelIcon(lv)} size={96} />
<Text className="font-jua text-[28px] text-ink">
Lv.{lv} {name}
</Text>
{opened.length > 0 && <Text className="text-center text-[15px] font-bold text-ink2">이제 {josa(opened.join(', '), '을', '를')} 볼 수 있어요</Text>}
{unlocks.length > 0 && (
<Pressable onPress={() => go(`/saju?open=${unlocks[0].key}`)} className="mt-3 w-full rounded-full bg-orange py-3">
<Text className="text-center text-[15px] font-extrabold text-white">{opened[0]} 보러 가기</Text>
</Pressable>
)}
<Pressable onPress={() => open({ type: 'level' })} className={`w-full py-2 ${unlocks.length ? '' : 'mt-3 rounded-full bg-orange py-3'}`}>
<Text className={`text-center text-[14px] font-extrabold ${unlocks.length ? 'text-ink2' : 'text-white'}`}>내 레벨 보기</Text>
</Pressable>
</Body>
);
}
-47
View File
@@ -1,47 +0,0 @@
import { setTokens } from '@nalssigak/shared/api/auth';
import type { ResAuth } from '@nalssigak/shared/api/client/types.gen';
import { useState } from 'react';
import { Pressable } from 'react-native';
import { Text } from '@/components/text';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { GoogleButton } from './google';
import { MeSheet } from './me';
import { Body, ErrorLine } from './parts';
export function LoginSheet({ onDone, onLoggedIn, why }: { onDone: () => void; onLoggedIn: () => void; why?: 'level' }) {
const { me } = useAuth();
const [error, setError] = useState('');
const done = (res: ResAuth) => {
if (!res.result?.success || !res.access_token) {
setError('구글로 로그인하지 못했어요. 다시 해 주세요.');
return;
}
setTokens(res.access_token, res.refresh_token ?? null);
track(res.is_new ? 'sign_up' : 'login', { method: 'google' });
onLoggedIn();
};
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.');
if (me) return <MeSheet onDone={onDone} />;
return (
<Body className="gap-2.5">
<Text className="text-center text-sm font-semibold text-ink2">{why === 'level' ? '로그인하면 출석·사주·좋아요로 각이 쌓여 레벨이 올라요.' : '글쓰기는 로그인한 뒤에 할 수 있어요.'}</Text>
<GoogleButton
onResult={(res) => {
setError('');
done(res);
}}
onFail={fail}
/>
<ErrorLine text={error} />
<Pressable onPress={onDone} className="rounded-[14px] p-[13px]">
<Text className="text-center text-[15px] font-extrabold text-ink2">나중에 할게요</Text>
</Pressable>
</Body>
);
}
-221
View File
@@ -1,221 +0,0 @@
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';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Avatar, Ic } from '@/components/ui';
import { MyTalks } from '@/components/talk/talk';
import { useAuth } from '@/lib/auth';
import { isCommentList } from './comments';
import { LevelCard } from './level';
import { Body, Field, useSoft } from './parts';
/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */
function Withdraw({ onDone }: { onDone: () => void }) {
const withdraw = useMutation(withdrawMutation());
const [asking, setAsking] = useState(false);
const [failed, setFailed] = useState(false);
if (!asking)
return (
<Pressable onPress={() => setAsking(true)} hitSlop={8} className="self-center p-1">
<Text className="text-[13px] font-semibold text-ink3">탈퇴하기</Text>
</Pressable>
);
const run = () => {
setFailed(false);
withdraw.mutate(
{},
{
onSuccess: (res) => {
if (!res.result?.success) return setFailed(true);
clearTokens();
onDone();
},
onError: () => setFailed(true),
},
);
};
return (
<View className="gap-2.5 rounded-[18px] p-3.5" style={{ backgroundColor: 'rgb(255 59 92 / 0.08)' }} accessibilityRole="alert">
<Text className="text-center text-sm font-bold text-ink">{'탈퇴하면 계정과 남긴 댓글·좋아요가\n모두 지워져요. 되돌릴 수 없어요.'}</Text>
<View className="flex-row gap-2">
<Pressable onPress={() => setAsking(false)} disabled={withdraw.isPending} className="flex-1 rounded-[14px] bg-card p-3">
<Text className="text-center text-sm font-extrabold text-ink">그만둘게요</Text>
</Pressable>
<Pressable onPress={run} disabled={withdraw.isPending} className="flex-1 rounded-[14px] bg-heart p-3 disabled:opacity-60">
<Text className="text-center text-sm font-extrabold text-white">탈퇴할게요</Text>
</Pressable>
</View>
{failed && <Text className="text-center text-[13px] font-bold text-heart">탈퇴하지 못했어요. 잠시 뒤에 다시 해 주세요.</Text>}
</View>
);
}
/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */
function Blocked() {
const s = useSoft();
const queryClient = useQueryClient();
const list = useQuery(listBlockedOptions());
const unblock = useMutation(unblockMutation());
const [failed, setFailed] = useState(false);
const users = list.data?.users ?? [];
if (!users.length) return null;
const release = (user_id: string) => {
setFailed(false);
unblock.mutate(
{ path: { user_id } },
{
onSuccess: (res) => {
if (!res.result?.success) return setFailed(true);
queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() });
queryClient.invalidateQueries({ predicate: isCommentList });
},
onError: () => setFailed(true),
},
);
};
return (
<View accessibilityLabel="차단한 사람">
<Text className="mb-2 text-sm font-extrabold text-ink">차단한 사람</Text>
<View className="gap-2">
{users.map((u) => (
<View key={u.user_id} className="flex-row items-center gap-2.5">
<Avatar character={u.character} color={u.color} />
<Text className="flex-1 text-sm font-bold text-ink">{u.nickname}</Text>
<Pressable onPress={() => release(u.user_id)} disabled={unblock.isPending} className="rounded-[12px] px-3 py-2 disabled:opacity-50" style={{ backgroundColor: s.soft }}>
<Text className="text-[13px] font-extrabold text-ink">풀기</Text>
</Pressable>
</View>
))}
</View>
{failed && <Text className="mt-1.5 text-[13px] font-bold text-heart">잠시 뒤에 다시 해 주세요.</Text>}
</View>
);
}
/** 내 정보: 캐릭터·배경색·기분·닉네임·로그아웃·차단한 사람·탈퇴 */
export function MeSheet({ onDone }: { onDone: () => void }) {
const { me, logout } = useAuth();
const s = useSoft();
const queryClient = useQueryClient();
const update = useMutation(updateMeMutation());
const [nickname, setNickname] = useState(me?.nickname ?? '');
const [error, setError] = useState('');
if (!me) return null;
const save = (body: { nickname?: string; character?: string; color?: string; mood?: string }) => {
setError('');
update.mutate(
{ body },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(res.result?.desc === 'INVALID_INPUT' ? '닉네임은 2~12자로 써 주세요.' : '잠시 뒤에 다시 해 주세요.');
queryClient.setQueryData(meQueryKey(), res);
// 댓글에 보이는 내 캐릭터·닉네임도 바뀐다
queryClient.invalidateQueries({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments' });
},
onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'),
},
);
};
// 저장하는 동안은 고른 값을 바로 선택으로 보여 준다. 실패하면 me 값으로 돌아간다
const saving = update.isPending ? update.variables?.body : undefined;
const character = saving?.character ?? me.character;
const color = saving?.color ?? me.color;
const mood = saving?.mood ?? me.mood;
const nick = nickname.trim();
return (
<Body className="gap-3">
<View className="items-center gap-1.5">
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
<Text className="text-center text-sm font-semibold text-ink2">{me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</Text>
</View>
<LevelCard />
<View accessibilityLabel="내 캐릭터">
<Text className="mb-2 text-sm font-extrabold text-ink">내 캐릭터</Text>
<View className="flex-row flex-wrap gap-2">
{CHARACTERS.map(([key, label]) => (
<Pressable
key={key}
accessibilityRole="radio"
accessibilityState={{ checked: character === key }}
disabled={update.isPending}
onPress={() => save({ character: key })}
className={`items-center gap-1 rounded-[18px] border-2 py-2.5 ${character === key ? 'border-orange' : 'border-transparent'}`}
style={{ width: '31.5%', backgroundColor: s.field }}
>
<Ic name={key} size={48} />
<Text className={`font-jua text-[15px] ${character === key ? 'text-orange' : 'text-ink'}`}>{label}</Text>
</Pressable>
))}
</View>
</View>
<View accessibilityLabel="배경색">
<Text className="mb-2 text-sm font-extrabold text-ink">배경색</Text>
<View className="flex-row flex-wrap gap-2.5">
{Object.entries(AVATAR_COLORS).map(([key, hex]) => (
<Pressable
key={key}
accessibilityRole="radio"
accessibilityState={{ checked: color === key }}
accessibilityLabel={key}
disabled={update.isPending}
onPress={() => save({ color: key })}
className={`size-9 rounded-full border-[3px] ${color === key ? 'border-ink' : 'border-white'}`}
style={{ backgroundColor: hex }}
/>
))}
</View>
</View>
<View accessibilityLabel="오늘 기분">
<Text className="mb-2 text-sm font-extrabold text-ink">오늘 기분</Text>
<View className="flex-row flex-wrap gap-2">
{MOODS.map(([key, emoji, label]) => (
<Pressable
key={key}
accessibilityRole="radio"
accessibilityState={{ checked: mood === key }}
disabled={update.isPending}
onPress={() => save({ mood: mood === key ? '' : key })}
className={`items-center gap-0.5 rounded-[14px] border-2 py-2 ${mood === key ? 'border-orange' : 'border-transparent'}`}
style={{ width: '23%', backgroundColor: s.field }}
>
<Text className="text-[22px] leading-[26px]">{emoji}</Text>
<Text className={`text-xs font-bold ${mood === key ? 'text-orange' : 'text-ink2'}`}>{label}</Text>
</Pressable>
))}
</View>
<Text className="mt-1.5 text-xs font-semibold text-ink3">한 번 더 누르면 지워져요</Text>
</View>
<View className="flex-row items-center gap-2">
<View className="flex-1">
<Field value={nickname} onChangeText={setNickname} maxLength={12} accessibilityLabel="닉네임" placeholder="닉네임 (2~12자)" onSubmitEditing={() => nick.length >= 2 && save({ nickname: nick })} />
</View>
<Pressable onPress={() => save({ nickname: nick })} disabled={update.isPending || nick === me.nickname || nick.length < 2} className="rounded-[14px] bg-ink-btn px-4 py-3 disabled:opacity-40">
<Text className="text-sm font-extrabold text-white">{saving?.nickname != null ? '저장 중…' : '바꾸기'}</Text>
</Pressable>
</View>
<Text className={`min-h-5 text-center text-[13px] font-bold ${saving ? 'text-ink2' : 'text-heart'}`}>{saving ? (saving.nickname == null ? '저장 중…' : '') : error}</Text>
<MyTalks />
<Pressable
onPress={() => {
logout();
onDone();
}}
className="rounded-[14px] p-[13px]"
style={{ backgroundColor: s.soft }}
>
<Text className="text-center text-[15px] font-extrabold text-ink">로그아웃</Text>
</Pressable>
<Blocked />
<Withdraw onDone={onDone} />
</Body>
);
}
-73
View File
@@ -1,73 +0,0 @@
import type { ReactNode, Ref } from 'react';
import { ScrollView, TextInput, View, type TextInputProps } from 'react-native';
import { Text } from '@/components/text';
import Svg, { Path } from 'react-native-svg';
import { Skel } from '@/components/ui';
import { useSky } from '@/lib/sky';
/** 웹의 연한 판(#f3f6fb)·입력칸·따뜻한 판(#fff4ec)을 밤엔 어두운 판으로 */
export function useSoft() {
const night = useSky().kind === 'night';
return {
soft: night ? '#2b3470' : '#f3f6fb',
field: night ? '#2b3470' : '#f7f9fc',
fieldBorder: night ? 'rgba(255,255,255,0.12)' : '#dfe5ee',
warm: night ? 'rgba(255,138,87,0.16)' : '#fff4ec',
bar: night ? 'rgba(255,255,255,0.12)' : '#e3eaf4',
placeholder: night ? '#a1a9db' : '#8a92aa',
};
}
export function Body({ children, className }: { children: ReactNode; className?: string }) {
return (
<ScrollView className="shrink" contentContainerClassName={`px-4 pt-3.5 pb-[18px] ${className ?? ''}`} keyboardShouldPersistTaps="handled">
{children}
</ScrollView>
);
}
/** 입력칸: 둥근 연한 판 */
export function Field({ round = false, style, ...props }: TextInputProps & { round?: boolean; ref?: Ref<TextInput> }) {
const s = useSoft();
return (
<TextInput
placeholderTextColor={s.placeholder}
className={`px-3.5 text-[16px] text-ink ${round ? 'rounded-full py-2.5' : 'rounded-[14px] py-3'}`}
style={[{ backgroundColor: s.field, borderWidth: 1, borderColor: s.fieldBorder }, style]}
{...props}
/>
);
}
export function HeartIcon({ size, fill, stroke }: { size: number; fill: string; stroke: string }) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill={fill} stroke={stroke} strokeWidth={2}>
<Path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
</Svg>
);
}
const N3 = [0, 1, 2];
/** 읽을거리·이번 주 특집: 그림 150px · 머리말 · 제목 · 본문 */
export function ArticleSkel() {
return (
<View className="gap-2.5">
<View className="h-[150px] rounded-[20px] bg-skel" />
<Skel className="w-24" />
<Skel className="h-6 w-4/5" />
{N3.map((k) => (
<View key={k} className="gap-1.5">
<Skel className="w-full" />
<Skel className="w-2/3" />
</View>
))}
</View>
);
}
/** 빨간 안내 한 줄 (자리 높이는 그대로) */
export function ErrorLine({ text, className }: { text?: string; className?: string }) {
return <Text className={`min-h-5 text-center text-[13px] font-bold text-heart ${className ?? ''}`}>{text ?? ''}</Text>;
}
-89
View File
@@ -1,89 +0,0 @@
import { listRegionsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { useDeferredValue, useEffect, useRef, useState } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Skel, StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { Body, Field } from './parts';
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const;
const N14 = Array.from({ length: 14 }, (_, i) => i);
function RegionsSkel() {
return (
<View className="mt-2">
{N14.map((i) => (
<View key={i} className="border-b-[1.5px] border-line px-1 py-3.5">
<Skel className="w-28" />
</View>
))}
</View>
);
}
/** 지역 바꾸기: 지금 위치로 찾기 + 구 이름으로 찾기 + 목록 */
export function RegionSheet({ onDone }: { onDone: () => void }) {
const { region, setRegion, locate, locateStatus } = useRegion();
const alive = useRef(true);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
};
}, []);
const { me, logout } = useAuth();
const { open } = useSheet();
const [q, setQ] = useState('');
const deferred = useDeferredValue(q.trim());
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined));
const regions = list.data?.regions ?? [];
const listLoad = loadOf(list);
return (
<Body>
<Pressable onPress={() => locate(() => alive.current && onDone())} disabled={locateStatus === 'locating'} className="items-center rounded-full border-b-[5px] border-orange-deep bg-orange p-3 disabled:opacity-60">
<Text className="font-jua text-[17px] text-white">지금 위치로 찾기</Text>
</Pressable>
<Text className="mt-2 min-h-5 text-center text-[13px] font-bold text-ink2" accessibilityLiveRegion="polite">
{LOCATE_TEXT[locateStatus]}
</Text>
<Field round value={q} onChangeText={setQ} placeholder="구 이름으로 찾기 (예: 마포)" accessibilityLabel="구 이름으로 찾기" />
{listLoad === 'loading' && <RegionsSkel />}
{listLoad !== 'loading' && !regions.length && (listLoad === 'ready' ? <StateBox load={listLoad} empty="찾는 구가 없어요." /> : <StateBox load={listLoad} onRetry={() => list.refetch()} hold={<RegionsSkel />} boxClassName="inset-x-0 top-2 bottom-0" />)}
<View className={`mt-2 ${list.isPlaceholderData ? 'opacity-60' : ''}`}>
{regions.map((r) => {
const here = r.code === region.code;
return (
<Pressable
key={r.code}
accessibilityState={{ selected: here }}
onPress={() => {
setRegion(r);
track('region_change', { region_name: r.name, method: 'list' });
onDone();
}}
className="flex-row items-center justify-between border-b-[1.5px] border-line px-1 py-3"
>
<Text className={`font-jua text-[17px] ${here ? 'text-orange' : 'text-ink'}`}>{r.name}</Text>
{here && <Text className="text-xs font-extrabold text-orange">지금 보는 곳</Text>}
</Pressable>
);
})}
</View>
<View className="mt-4 flex-row items-center justify-center gap-2">
<Text className="text-[13px] font-bold text-ink2">{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'}</Text>
<Pressable onPress={me ? logout : () => open({ type: 'login' })} hitSlop={8}>
<Text className="text-[13px] font-extrabold text-rain">{me ? '로그아웃' : '로그인'}</Text>
</Pressable>
</View>
</Body>
);
}
@@ -1,86 +0,0 @@
import type { WeatherWhy } from '@nalssigak/shared/api/client/types.gen';
import { View } from 'react-native';
import { Text } from '@/components/text';
import { Body, useSoft } from './parts';
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[]; status?: { label: string; value: string; tone?: string; detail?: string | null }[] };
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게 (웹 weatherWhy.tsx)
const COLOR: Record<string, string> = { 기온: '#ff7a45', 비: '#4f97e3', 햇볕: '#ffb02e', 바람: '#5fb8b0', 습도: '#8e8cf0', 미세먼지: '#b59a86' };
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8';
// 상태 줄 항목마다 단계를 나누는 기준 (backend/services/hero_stats.py 와 같은 값)
const RULE: Record<string, string> = {
습도: '30% 아래는 건조, 60% 넘으면 습함이에요',
불쾌지수: '68 아래는 쾌적, 75부터 불쾌예요',
자외선: '3 아래는 낮음, 6부터 높음이에요',
미세먼지: '에어코리아 기준 등급이에요',
};
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
const s = useSoft();
return (
<Body>
<View className="flex-row items-baseline gap-2">
<Text className="font-bagel text-[44px] leading-[48px] text-ink">{d.score}</Text>
<Text className="font-jua text-[17px] text-ink2">{d.label} 날씨 점수</Text>
</View>
<View className="mt-3 h-7 flex-row gap-[3px] overflow-hidden rounded-[10px]" accessibilityRole="image" accessibilityLabel={d.why.map((w) => `${w.label} 비중 ${w.weight}% 중 ${w.score}점`).join(', ')}>
{d.why.map((w) => (
<View key={w.label} className="h-full" style={{ width: `${w.weight}%`, backgroundColor: s.bar }}>
<View className="absolute inset-y-0 left-0" style={{ width: `${w.score}%`, backgroundColor: colorOf(w.label) }} />
</View>
))}
</View>
<Text className="mt-1.5 text-[12.5px] font-semibold text-ink3">칸 넓이는 비중, 채운 만큼이 얻은 점수예요</Text>
<View className="mt-3 gap-1.5">
{d.why.map((w) => (
<View key={w.label} className="flex-row items-center gap-3 rounded-2xl px-3.5 py-2.5" style={{ backgroundColor: s.soft }}>
<View className="size-3 rounded-full" style={{ backgroundColor: colorOf(w.label) }} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">
{w.label} <Text className="font-sans text-[12px] font-bold text-ink3">비중 {w.weight}%</Text>
</Text>
<Text className="text-[13px] font-semibold text-ink2">{w.note}</Text>
</View>
<Text className="font-jua text-[20px] text-ink">{w.score}</Text>
</View>
))}
</View>
{!!d.status?.length && (
<>
<Text className="mt-5 font-jua text-[17px] text-ink">지금 상태</Text>
<View className="mt-2 gap-1.5">
{d.status.map((x) => (
<View key={x.label} className="flex-row items-center gap-3 rounded-2xl px-3.5 py-2.5" style={{ backgroundColor: s.soft }}>
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">{x.label}</Text>
{!!RULE[x.label] && <Text className="text-[12.5px] font-semibold text-ink3">{RULE[x.label]}</Text>}
</View>
<View className="items-end">
<Text className={`font-jua text-[18px] leading-tight ${x.tone === 'warn' ? 'text-[#d4552a]' : 'text-ink'}`}>
{x.value}
</Text>
{x.detail?.split(' · ').map((v) => (
<Text key={v} className="text-[12px] font-bold text-ink2">
{v}
</Text>
))}
</View>
</View>
))}
</View>
</>
)}
<Text className="mt-3 text-[13px] leading-relaxed font-semibold text-ink2">조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.</Text>
</Body>
);
}
-53
View File
@@ -1,53 +0,0 @@
import { useImperativeHandle, useRef, type Ref } from 'react';
import { WebView } from 'react-native-webview';
import { SITE_URL } from '@/lib/site';
const YT_ORIGIN = 'https://www.youtube-nocookie.com';
export type PlayerFunc = 'playVideo' | 'seekTo' | 'mute' | 'unMute';
export type PlayerHandle = { command: (func: PlayerFunc, args?: unknown[]) => void };
function embed(id: string) {
const q = new URLSearchParams({ autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1', enablejsapi: '1', origin: SITE_URL });
return `${YT_ORIGIN}/embed/${id}?${q}`;
}
/**
* 유튜브 플레이어를 날씨각 주소를 기준으로 한 작은 문서 안 iframe 으로 띄운다.
* 앱 웹뷰에서 embed 주소를 바로 열면 보낸 곳(Referer)이 없어 유튜브가 막는다. 웹과 같이 IFrame API 메시지로 재생 상태를 받고 명령한다
*/
function html(id: string) {
return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:transparent;overflow:hidden}iframe{border:0;width:100%;height:100%}</style></head>
<body><iframe id="f" src="${embed(id)}" allow="autoplay; encrypted-media"></iframe>
<script>
var f = document.getElementById('f');
f.addEventListener('load', function () { f.contentWindow.postMessage(JSON.stringify({ event: 'listening', id: ${JSON.stringify(id)} }), '${YT_ORIGIN}'); });
window.addEventListener('message', function (e) {
if (e.origin !== '${YT_ORIGIN}') return;
try { var m = JSON.parse(e.data); if (m.info && m.info.playerState === 1) window.ReactNativeWebView.postMessage('playing'); } catch (x) {}
});
window.cmd = function (func, args) { f.contentWindow.postMessage(JSON.stringify({ event: 'command', func: func, args: args || [] }), '${YT_ORIGIN}'); };
</script></body></html>`;
}
/** 소리 없이 자동재생하는 쇼츠 플레이어. 첫 장면이 나오면 onPlaying (그 전엔 위에 표지를 덮어 둔다) */
export function ShortPlayer({ id, onPlaying, ref }: { id: string; onPlaying: () => void; ref?: Ref<PlayerHandle> }) {
const view = useRef<WebView>(null);
useImperativeHandle(ref, () => ({
command: (func, args = []) => view.current?.injectJavaScript(`window.cmd && window.cmd(${JSON.stringify(func)}, ${JSON.stringify(args)}); true;`),
}));
return (
<WebView
ref={view}
source={{ html: html(id), baseUrl: SITE_URL }}
originWhitelist={['*']}
onMessage={(e) => e.nativeEvent.data === 'playing' && onPlaying()}
mediaPlaybackRequiresUserAction={false}
allowsInlineMediaPlayback
scrollEnabled={false}
setSupportMultipleWindows={false}
style={{ backgroundColor: 'transparent' }}
/>
);
}
-45
View File
@@ -1,45 +0,0 @@
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { useQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { Link } from 'expo-router';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Rail } from '@/components/ui';
const SKELS = [0, 1, 2, 3];
export const thumb = (id: string) => `https://i.ytimg.com/vi/${id}/hqdefault.jpg`;
/** 오늘 화면 히어로 아래 쇼츠 줄. 누르면 쇼츠 화면에서 위아래로 넘겨 본다. 앱은 데이터를 아끼려고 줄에서는 표지만 (웹은 첫 카드를 소리 없이 재생) */
export function ShortsRail() {
const q = useQuery(listShortsOptions());
const items = q.data?.items ?? [];
if (q.isPending)
return (
<Rail>
{SKELS.map((i) => (
<View key={i} className="aspect-[9/16] w-[120px] rounded-xl bg-skel" />
))}
</Rail>
);
if (!items.length) return null;
return (
<View accessibilityLabel="날씨각 쇼츠">
<Rail>
{items.map((s) => (
<Link key={s.id} href={{ pathname: '/shorts/[id]', params: { id: s.id } }} asChild>
<Pressable accessibilityLabel={`${s.title} 보기`} className="aspect-[9/16] w-[120px] overflow-hidden rounded-xl bg-[#1d2233]">
<Image source={{ uri: thumb(s.id) }} style={{ position: 'absolute', inset: 0 }} contentFit="cover" />
<LinearGradient colors={['transparent', 'rgba(0,0,0,0.65)']} locations={[0.55, 1]} style={{ position: 'absolute', inset: 0 }} />
<Text numberOfLines={3} className="absolute inset-x-2 bottom-2 text-[12px] leading-[16px] font-bold text-white">
{s.title}
</Text>
</Pressable>
</Link>
))}
</Rail>
</View>
);
}
-121
View File
@@ -1,121 +0,0 @@
import type { TimeKind } from '@nalssigak/shared/lib';
import { holidayOn, type Holiday } from '@nalssigak/shared/lib/holiday';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect, useState } from 'react';
import { StyleSheet, useWindowDimensions, View, type DimensionValue } from 'react-native';
import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
import { useSky } from '@/lib/sky';
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night'];
const SKY: Record<TimeKind, { colors: readonly [string, string, string]; locations: readonly [number, number, number] }> = {
morning: { colors: ['#ffe0c4', '#fff0e2', '#e4f2ff'], locations: [0, 0.38, 1] },
day: { colors: ['#cde7ff', '#e9f5ff', '#f7fbff'], locations: [0, 0.45, 1] },
sunset: { colors: ['#ffd0b5', '#f9c3cf', '#ddd2f6'], locations: [0, 0.42, 1] },
night: { colors: ['#0e1433', '#1b2356', '#2a2e6e'], locations: [0, 0.5, 1] },
};
const STARS = Array.from({ length: 46 }, (_, i) => ({ left: `${(i * 41 + 7) % 100}%`, top: `${(i * 67 + 3) % 96}%`, size: 1 + (i % 3) * 0.8, period: (3 + (i % 5)) * 1000, delay: ((i * 0.7) % 6) * 1000 }) as const);
/** 시간대 하나의 하늘 판. 고른 시간대만 1.4초 동안 서서히 드러난다 */
function Layer({ kind, on, reduce }: { kind: TimeKind; on: boolean; reduce: boolean }) {
const shown = useSharedValue(on ? 1 : 0);
useEffect(() => {
shown.value = reduce ? (on ? 1 : 0) : withTiming(on ? 1 : 0, { duration: 1400, easing: Easing.ease });
}, [on, reduce, shown]);
const style = useAnimatedStyle(() => ({ opacity: shown.value }));
return (
<Animated.View style={[StyleSheet.absoluteFill, style]}>
<LinearGradient {...SKY[kind]} style={StyleSheet.absoluteFill} />
</Animated.View>
);
}
/** 밤 별: 제각각 주기로 반짝인다 */
function Star({ star, reduce }: { star: (typeof STARS)[number]; reduce: boolean }) {
const glow = useSharedValue(0);
useEffect(() => {
if (reduce) return;
glow.value = withDelay(star.delay, withRepeat(withTiming(1, { duration: star.period / 2, easing: Easing.inOut(Easing.ease) }), -1, true));
return () => cancelAnimation(glow);
}, [reduce, glow, star]);
const style = useAnimatedStyle(() => ({ opacity: reduce ? 0.7 : 0.25 + glow.value * 0.75 }));
return <Animated.View style={[{ position: 'absolute', left: star.left, top: star.top, width: star.size, height: star.size, borderRadius: star.size, backgroundColor: '#fff', boxShadow: '0 0 6px rgb(255 255 255 / 0.8)' }, style]} />;
}
export type ShootSpec = { top: DimensionValue; left: DimensionValue; len: number; dur: number; dl: number };
// 별똥별: 위치·길이·주기를 엇갈려 몇 초마다 하나씩 떨어지게 (웹 BLayout SHOOTS, 밀리초)
const SHOOTS: ShootSpec[] = [
{ top: '8%', left: '78%', len: 110, dur: 7000, dl: 1000 },
{ top: '22%', left: '46%', len: 80, dur: 9000, dl: 3500 },
{ top: '5%', left: '30%', len: 95, dur: 8000, dl: 5500 },
{ top: '36%', left: '88%', len: 70, dur: 10000, dl: 2200 },
{ top: '52%', left: '62%', len: 90, dur: 11000, dl: 7000 },
{ top: '14%', left: '96%', len: 120, dur: 12000, dl: 9000 },
];
/** 별똥별 하나: 주기 끝 14% 동안만 비스듬히 240px 미끄러지며 반짝 (웹 .b-shoot). 동작 줄이기면 그리지 않는다 */
export function Shoot({ top, left, len, dur, dl }: ShootSpec) {
const reduce = useReducedMotion();
const p = useSharedValue(0);
useEffect(() => {
if (reduce) return;
p.value = withDelay(dl, withRepeat(withTiming(1, { duration: dur, easing: Easing.in(Easing.ease) }), -1, false));
return () => cancelAnimation(p);
}, [reduce, dur, dl, p]);
const style = useAnimatedStyle(() => ({
opacity: interpolate(p.value, [0, 0.86, 0.89, 1], [0, 0, 1, 0]),
transform: [{ rotate: '-24deg' }, { translateX: interpolate(p.value, [0, 0.86, 1], [0, 0, -240]) }],
}));
if (reduce) return null;
return (
<Animated.View style={[{ position: 'absolute', top, left, width: len, height: 1.5 }, style]}>
<LinearGradient colors={['rgba(255,255,255,0)', '#ffffff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ flex: 1, borderRadius: 2 }} />
</Animated.View>
);
}
/** 화면 전체 하늘: 시간대별 색이 서서히 바뀌고, 밤에는 별이 반짝이고 별똥별이 떨어진다 */
// 기념일 소품: 투명 배경 그림을 화면 네 귀퉁이에 (웹 b.css .b-sky-holiday, frontend/public/b/holiday, 4:5 그림)
const PROPS: Record<Holiday['key'], [number, number, number, number]> = {
halloween: [require('../../../frontend/public/b/holiday/halloween-tl.webp'), require('../../../frontend/public/b/holiday/halloween-tr.webp'), require('../../../frontend/public/b/holiday/halloween-bl.webp'), require('../../../frontend/public/b/holiday/halloween-br.webp')],
pepero: [require('../../../frontend/public/b/holiday/pepero-tl.webp'), require('../../../frontend/public/b/holiday/pepero-tr.webp'), require('../../../frontend/public/b/holiday/pepero-bl.webp'), require('../../../frontend/public/b/holiday/pepero-br.webp')],
christmas: [require('../../../frontend/public/b/holiday/christmas-tl.webp'), require('../../../frontend/public/b/holiday/christmas-tr.webp'), require('../../../frontend/public/b/holiday/christmas-bl.webp'), require('../../../frontend/public/b/holiday/christmas-br.webp')],
chuseok: [require('../../../frontend/public/b/holiday/chuseok-tl.webp'), require('../../../frontend/public/b/holiday/chuseok-tr.webp'), require('../../../frontend/public/b/holiday/chuseok-bl.webp'), require('../../../frontend/public/b/holiday/chuseok-br.webp')],
suneung: [require('../../../frontend/public/b/holiday/suneung-tl.webp'), require('../../../frontend/public/b/holiday/suneung-tr.webp'), require('../../../frontend/public/b/holiday/suneung-bl.webp'), require('../../../frontend/public/b/holiday/suneung-br.webp')],
newyear: [require('../../../frontend/public/b/holiday/newyear-tl.webp'), require('../../../frontend/public/b/holiday/newyear-tr.webp'), require('../../../frontend/public/b/holiday/newyear-bl.webp'), require('../../../frontend/public/b/holiday/newyear-br.webp')],
};
const CORNERS = [{ top: 0, left: 0 }, { top: 0, right: 0 }, { bottom: 0, left: 0 }, { bottom: 0, right: 0 }] as const;
/** 기념일 기간에만 네 귀퉁이 소품. 폰은 반씩 나눠 폭을 채우고 넓은 화면은 300 으로. 밤엔 조금 어둡게 */
function HolidayProps({ night }: { night: boolean }) {
const [holiday] = useState(holidayOn);
const { width } = useWindowDimensions();
if (!holiday) return null;
const w = Math.min(width / 2, 300);
return (
<>
{PROPS[holiday.key].map((src, i) => (
<Image key={i} source={src} style={{ position: 'absolute', ...CORNERS[i], width: w, aspectRatio: 4 / 5, opacity: night ? 0.8 : 1 }} contentFit="contain" />
))}
</>
);
}
export function SkyBg() {
const { kind } = useSky();
const reduce = useReducedMotion();
return (
<View style={StyleSheet.absoluteFill} pointerEvents="none">
{KINDS.map((k) => (
<Layer key={k} kind={k} on={k === kind} reduce={reduce} />
))}
<HolidayProps night={kind === 'night'} />
{kind === 'night' && STARS.map((s, i) => <Star key={i} star={s} reduce={reduce} />)}
{kind === 'night' && SHOOTS.map((s, i) => <Shoot key={i} {...s} />)}
</View>
);
}
-16
View File
@@ -1,16 +0,0 @@
// 웹 b.css 노을 탭 그라데이션. 등급별 하늘색(히어로·3일 타일)과 시간표 막대
type Grad = { colors: readonly [string, string, ...string[]]; locations?: readonly [number, number, ...number[]] };
export const GRADE_SKY: Record<string, { hero: Grad; tile: Grad }> = {
잿빛: { hero: { colors: ['#6f7690', '#9aa0b4', '#b9b4c0'], locations: [0, 0.55, 1] }, tile: { colors: ['#8f8aa5', '#b9b0bf'] } },
은은함: { hero: { colors: ['#4b5aa8', '#7f86c6', '#e9b9a8', '#ffb27a'], locations: [0, 0.4, 0.78, 1] }, tile: { colors: ['#7f86c6', '#e9b9a8', '#f6b07a'], locations: [0, 0.7, 1] } },
고움: { hero: { colors: ['#5b3f9e', '#c2559a', '#ff7a6a', '#ffb35c'], locations: [0, 0.45, 0.78, 1] }, tile: { colors: ['#5b3f9e', '#c2559a', '#ff7a6a'], locations: [0, 0.55, 1] } },
붉음: { hero: { colors: ['#4a2a8a', '#b0306a', '#ff4a3a', '#ff9a3c'], locations: [0, 0.4, 0.72, 1] }, tile: { colors: ['#4a2a8a', '#b0306a', '#ff4a3a'], locations: [0, 0.5, 1] } },
};
export const skyOf = (grade?: string | null) => GRADE_SKY[grade ?? ''] ?? GRADE_SKY['은은함'];
export const RAIL = {
sunset: { colors: ['#f2b84b', '#f6844e', '#e8506a', '#8c5aa6', '#2d3f8f'], locations: [0, 0.45, 0.62, 0.82, 1] },
sunrise: { colors: ['#2d3f8f', '#8c5aa6', '#e8506a', '#f6844e', '#f2b84b'], locations: [0, 0.25, 0.45, 0.6, 1] },
} satisfies Record<string, Grad>;
-190
View File
@@ -1,190 +0,0 @@
import type { BestTime, SkyPlanData } from '@nalssigak/shared/api/client/types.gen';
import { clockShort } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import { useState, type ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { useCSSVariable } from 'uniwind';
import { RAIL, skyOf } from '@/components/sky/colors';
import { SitSun, Skyline } from '@/components/sky/skyline';
import { MapLink, Skel } from '@/components/ui';
const SHADOW = { textShadowColor: 'rgb(50 25 70 / 0.35)', textShadowOffset: { width: 0, height: 2 }, textShadowRadius: 10 };
const FOUR = [0, 1, 2, 3];
/** 히어로엔 답만: 노을 피크 시각과 어떻게 물드는지. 상자는 불러오는 중·실패·빈 값 모두 같은 크기 */
export function SkyHero({ plan, children }: { plan?: SkyPlanData; children?: ReactNode }) {
const g = skyOf(plan?.grade_label).hero;
return (
<View className="mx-3 mt-1 min-h-[230px] overflow-hidden rounded-[32px] px-5 pt-5 pb-14">
<LinearGradient colors={g.colors} locations={g.locations} style={{ position: 'absolute', inset: 0 }} />
<SitSun />
<Skyline />
{children ?? (
<View>
{plan ? (
<Text className="font-jua text-[28px] leading-tight text-white" style={SHADOW}>
{plan.title}
</Text>
) : (
<Skel className="h-7 w-[230px]" />
)}
{!plan ? (
<Skel className="mt-2 w-[180px]" />
) : plan.situation_label ? (
<Text className="mt-1.5 text-[15px] font-bold text-white" style={SHADOW}>
{plan.situation_label}
</Text>
) : null}
</View>
)}
</View>
);
}
/** 오늘·내일·모레를 그날 예상 하늘색 타일로. 누르면 그날로 */
export function DayTiles({ plans, day, onPick }: { plans: SkyPlanData[]; day?: string; onPick: (day: string) => void }) {
const ink = String(useCSSVariable('--color-ink'));
return (
<View className="mx-3 mt-2.5 flex-row gap-2">
{plans.map((p) => {
const g = skyOf(p.grade_label).tile;
const on = p.day === day;
return (
<Pressable key={p.day} accessibilityState={{ selected: on }} onPress={() => onPick(p.day)} className="flex-1 rounded-[18px] p-[2px]" style={{ borderWidth: 3, borderColor: on ? ink : 'transparent' }}>
<View className="overflow-hidden rounded-2xl px-2.5 pt-2 pb-2.5">
<LinearGradient colors={g.colors} locations={g.locations} start={{ x: 0.2, y: 0 }} end={{ x: 0.8, y: 1 }} style={{ position: 'absolute', inset: 0 }} />
<Text className="text-[11.5px] font-extrabold text-white">{p.when}</Text>
<Text className="font-jua text-lg leading-tight text-white">{p.best_at ? clockShort(p.best_at) : '–'}</Text>
<Text className="text-[11.5px] font-bold text-white">
{p.grade_label} {p.score}
</Text>
</View>
</Pressable>
);
})}
</View>
);
}
function Toggle({ label, children, end }: { label: ReactNode; children: ReactNode; end?: boolean }) {
const [open, setOpen] = useState(false);
return (
<View>
<Pressable onPress={() => setOpen(!open)} accessibilityState={{ expanded: open }} className={`flex-row items-center gap-1.5 ${end ? 'justify-between' : ''}`}>
{label}
</Pressable>
{open && children}
</View>
);
}
const Q = ({ className = 'bg-card/80' }: { className?: string }) => (
<View className={`size-[18px] items-center justify-center rounded-full ${className}`}>
<Text className="text-[11px] font-extrabold text-ink">?</Text>
</View>
);
/** 노을 점수 뜻. 지금 하늘이 아니라 해 질(뜰) 무렵 예보라는 것도 */
export function ScoreHelp({ plan }: { plan: SkyPlanData }) {
const sunAt = plan.timeline?.find((t) => t.kind === 'sun')?.at;
const rise = plan.kind === 'sunrise';
return (
<View className="mx-3 mt-1.5 px-1">
<Toggle
end
label={
<>
<Text className="text-[12px] font-bold text-ink2">노을 점수 100점 만점 · 높을수록 붉어요</Text>
<Q />
</>
}
>
<Text className="mt-1.5 rounded-xl bg-card/70 px-2.5 py-2 text-[12px] leading-snug font-semibold text-ink2">
80점 넘으면 붉게, 60점 넘으면 곱게, 40점 넘으면 은은하게 물들어요.
{sunAt && ` 해 ${rise ? '뜰' : '질'} 무렵(${new Date(sunAt).getHours()}시) 날씨 예보로 계산했고, 노을 피크 시각은 해 ${rise ? '뜨기 10~20분 전' : '지고 10~20분 뒤'}로 어림한 거라 실제와 다를 수 있어요.`}
</Text>
</Toggle>
</View>
);
}
/** 언제 보면 좋을까: 왼쪽 세로 줄 색이 그 시각 하늘색, 노을 피크만 강조 */
export function Timeline({ rows, kind = 'sunset' }: { rows?: BestTime[]; kind?: SkyPlanData['kind'] }) {
const rail = RAIL[kind === 'sunrise' ? 'sunrise' : 'sunset'];
const list = rows ?? FOUR.map(() => undefined);
return (
<View className="mx-3 mt-3 rounded-[22px] border-b-[5px] border-shade bg-card px-4 pt-3.5 pb-3">
<View className="flex-row gap-3">
<LinearGradient colors={rail.colors} locations={rail.locations} style={{ width: 12, borderRadius: 6 }} />
<View className="flex-1">
{list.map((t, i) => {
const peak = t?.kind === 'peak';
return (
<View key={t?.kind ?? i} className={`flex-row items-baseline gap-2.5 ${peak ? '-mx-1.5 my-0.5 rounded-xl bg-[#fff1f2] px-2.5 py-2' : 'py-1.5'}`} style={!peak && i < list.length - 1 ? { borderBottomWidth: 1 } : undefined}>
<View className="min-w-[96px]">
{t ? <Text className={`font-jua ${peak ? 'text-[20px] text-[#d23d5a]' : 'text-[17px] text-ink'}`}>{t.end ? `${clockShort(t.at)}~${clockShort(t.end)}` : clockShort(t.at)}</Text> : <Skel className="w-11" />}
</View>
{t ? <Text className={`flex-1 ${peak ? 'font-jua text-base text-[#d23d5a]' : 'text-[13.5px] font-bold text-ink2'}`}>{t.label}</Text> : <Skel className="w-20" />}
</View>
);
})}
</View>
</View>
{rows && (
<View className="mt-2">
<Toggle
label={
<>
<Q className="bg-[#f1ebe3]" />
<Text className="text-[12px] font-bold text-ink2">골든아워·블루아워가 뭐예요</Text>
</>
}
>
<Text className="mt-1.5 rounded-xl bg-[#faf6f1] px-2.5 py-2 text-[12px] leading-snug text-[#5a6380]">
<Text className="font-bold text-[#28304a]">골든아워</Text> 해가 {kind === 'sunrise' ? '뜬 뒤' : '지기 전'}, 햇빛이 금빛으로 물드는 시간{'\n'}
<Text className="font-bold text-[#28304a]">블루아워</Text> 해가 {kind === 'sunrise' ? '뜨기 전' : '진 뒤'}, 하늘이 짙은 파랑으로 남는 시간
</Text>
</Toggle>
</View>
)}
</View>
);
}
const ROW = 'flex-row items-center gap-2.5 px-1 py-3';
export function LiSkel({ ghost = false, last = false }: { ghost?: boolean; last?: boolean }) {
return (
<View className={`${ROW} border-line ${ghost ? 'opacity-0' : ''}`} style={last ? undefined : { borderBottomWidth: 1.5 }}>
<View className="w-[34px] items-center">
<Skel className="w-5" />
</View>
<View className="flex-1 gap-1.5">
<Skel className="h-4 w-24" />
<Skel className="w-40" />
</View>
<Skel className="w-9" />
</View>
);
}
/** 번호 · 이름(+설명) · 오른쪽 값 한 줄 */
export function Li({ no, title, sub, right, mine = false, place, last = false }: { no: number; title: string; sub?: string | null; right: string; mine?: boolean; place?: string; last?: boolean }) {
return (
<View className={`${ROW} border-line ${mine ? 'rounded-2xl bg-card' : ''}`} style={last ? undefined : { borderBottomWidth: 1.5 }}>
<Text className="w-[34px] text-center font-bagel text-xl text-orange">{no}</Text>
<View className="min-w-0 flex-1">
<Text className="font-jua text-[17px] text-ink">
{place ? <MapLink place={place}>{title}</MapLink> : title}
{mine && <Text className="text-xs font-extrabold text-rain"> 내 지역</Text>}
</Text>
<Text numberOfLines={1} className="text-[12.5px] font-semibold text-ink2">
{sub || ' '}
</Text>
</View>
<Text className="font-jua text-base text-ink">{right}</Text>
</View>
);
}
-34
View File
@@ -1,34 +0,0 @@
import { View } from 'react-native';
import Svg, { Defs, Polygon, RadialGradient, Rect, Stop } from 'react-native-svg';
// 웹 .b-skyline::after 의 clip-path 를 그대로 (0~100 비율)
const POINTS = '0,55 8,55 8,30 15,30 15,50 22,50 22,10 28,10 28,45 36,45 36,25 44,25 44,55 52,55 52,35 60,35 60,5 66,5 66,40 74,40 74,20 82,20 82,50 90,50 90,30 100,30 100,100 0,100';
/** 아래에 깔리는 동네 건물 실루엣. height 는 상자 높이 대비 비율 */
export function Skyline({ height = '22%' }: { height?: `${number}%` }) {
return (
<View pointerEvents="none" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height }}>
<Svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none">
<Polygon points={POINTS} fill="#2d2440" />
</Svg>
</View>
);
}
/** 건물 뒤로 지는 해 (.b-sit-sun) */
export function SitSun({ size = 112, bottom = 24, opacity = 1 }: { size?: number; bottom?: number; opacity?: number }) {
return (
<View pointerEvents="none" style={{ position: 'absolute', bottom, left: '50%', marginLeft: -size / 2, width: size, height: size, opacity }}>
<Svg width={size} height={size} viewBox="0 0 2 2">
<Defs>
<RadialGradient id="sitsun" cx="1" cy="1" r="1" gradientUnits="userSpaceOnUse">
<Stop offset="0" stopColor="#fff6dd" />
<Stop offset="0.38" stopColor="#ffd08f" />
<Stop offset="0.7" stopColor="#ffa05a" stopOpacity={0} />
</RadialGradient>
</Defs>
<Rect x="0" y="0" width="2" height="2" fill="url(#sitsun)" />
</Svg>
</View>
);
}
-39
View File
@@ -1,39 +0,0 @@
import Svg, { Circle, Path, Rect } from 'react-native-svg';
export type TabName = 'today' | 'gak' | 'sky' | 'week' | 'season';
const line = { fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' } as const;
export function PinIcon({ size, color }: { size: number; color: string }) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} {...line} stroke={color} strokeWidth={2.2}>
<Path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z" />
<Circle cx="12" cy="9.5" r="2.5" />
</Svg>
);
}
export function TabIcon({ name, size, color, strokeWidth }: { name: TabName; size: number; color: string; strokeWidth: number }) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} {...line} stroke={color} strokeWidth={strokeWidth}>
{name === 'today' && <Path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
{name === 'gak' && (
<>
<Rect x="3.5" y="3.5" width="7" height="7" rx="2" />
<Rect x="13.5" y="3.5" width="7" height="7" rx="2" />
<Rect x="3.5" y="13.5" width="7" height="7" rx="2" />
<Rect x="13.5" y="13.5" width="7" height="7" rx="2" />
</>
)}
{name === 'sky' && <Path d="M3 18h18M6 14a6 6 0 0 1 12 0M12 4v3M4.9 7.9l2 2M19.1 7.9l-2 2M8 21h8" />}
{name === 'week' && (
<>
<Rect x="3.5" y="5" width="17" height="15.5" rx="2.5" />
<Path d="M3.5 10h17M8 3v4M16 3v4" />
<Circle cx="12" cy="15" r="1.6" />
</>
)}
{name === 'season' && <Path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
</Svg>
);
}
-61
View File
@@ -1,61 +0,0 @@
import type { BottomTabBarProps } from 'expo-router/tabs';
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useCSSVariable } from 'uniwind';
import { TabIcon, type TabName } from '@/components/svg';
import { useSky } from '@/lib/sky';
const LABELS: Record<string, [TabName, string]> = {
sky: ['sky', '노을'],
gak: ['gak', '각'],
index: ['today', '오늘'],
week: ['week', '주말·행사'],
season: ['season', '계절·상식'],
};
/** 아래 탭 막대. 가운데 오늘 탭은 막대 위로 솟은 큰 주황 동그라미 */
export function TabBar({ state, navigation }: BottomTabBarProps) {
const { bottom } = useSafeAreaInsets();
const { kind } = useSky();
const [ink, ink3, orange] = useCSSVariable(['--color-ink', '--color-ink3', '--color-orange']).map(String);
const night = kind === 'night';
return (
<View
className="flex-row border-t px-1 pt-[7px]"
style={{ paddingBottom: 8 + bottom, backgroundColor: night ? 'rgb(18 24 60 / 0.92)' : 'rgb(255 255 255 / 0.85)', borderColor: night ? 'rgb(255 255 255 / 0.08)' : 'rgb(255 255 255 / 0.4)' }}
>
{state.routes.map((route, i) => {
const [icon, label] = LABELS[route.name] ?? ['today', route.name];
const focused = state.index === i;
const onPress = () => {
const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true });
if (!focused && !event.defaultPrevented) navigation.navigate(route.name);
};
if (icon === 'today')
return (
<Pressable key={route.key} onPress={onPress} accessibilityRole="tab" accessibilityState={{ selected: focused }} className="-mt-6 flex-1 items-center gap-1">
<View className="size-[68px] items-center justify-center rounded-full" style={{ backgroundColor: night ? 'rgb(18 24 60 / 0.9)' : 'rgb(255 255 255 / 0.85)' }}>
<LinearGradient colors={['#ffb067', '#ff7a45', '#d4552a']} locations={[0, 0.55, 1]} start={{ x: 0.3, y: 0 }} end={{ x: 0.7, y: 1 }} style={{ width: 60, height: 60, borderRadius: 30, alignItems: 'center', justifyContent: 'center', boxShadow: '0 8px 18px rgb(255 122 69 / 0.45)' }}>
<TabIcon name="today" size={30} color="#fff" strokeWidth={2.6} />
</LinearGradient>
</View>
<Text className="text-[12px] font-extrabold" style={{ color: focused ? orange : ink3 }}>
{label}
</Text>
</Pressable>
);
return (
<Pressable key={route.key} onPress={onPress} accessibilityRole="tab" accessibilityState={{ selected: focused }} className="flex-1 items-center gap-0.5">
<TabIcon name={icon} size={25} color={focused ? ink : ink3} strokeWidth={focused ? 2.4 : 1.9} />
<Text className="text-[11px] font-extrabold" style={{ color: focused ? ink : ink3 }}>
{label}
</Text>
</Pressable>
);
})}
</View>
);
}
-426
View File
@@ -1,426 +0,0 @@
import { addTalkMutation, blockTalkAuthorMutation, deleteTalkMutation, likeTalkMutation, reportTalkMutation, unlikeTalkMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen';
import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen';
import { holidayByTopic } from '@nalssigak/shared/lib/holiday';
import { useMutation } from '@tanstack/react-query';
import { Image } from 'expo-image';
import * as ImagePicker from 'expo-image-picker';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, useState } from 'react';
import { Pressable, TextInput, View } from 'react-native';
import { useCSSVariable } from 'uniwind';
import { CameraIcon, CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Avatar } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { CARD_BG } from '@/lib/colors';
import { useRegion } from '@/lib/region';
import { useShare } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { openTopics, talkImage, talkMeta, useMyTalks, useRefreshTalks } from '@/lib/talk';
const BODY_MAX = 100;
const PHOTO_MAX = 10 * 1024 * 1024;
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record<string, string> = {
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
INVALID_INPUT: '100자 안으로 써 주세요.',
};
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
[TalkReport.PRIVACY, '개인정보 노출'],
[TalkReport.ETC, '기타'],
] as const;
type Photo = { uri: string; name: string; type: string };
/** 고른 사진을 올려 주소를 받는다. 앱의 사진은 Blob 이 아니라 {uri} 라서 FormData 를 직접 만든다 */
async function uploadPhoto(photo: Photo) {
const form = new FormData();
form.append('file', photo as unknown as Blob);
const { data } = await uploadTalkImage({ body: { file: photo as unknown as Blob }, bodySerializer: () => form });
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload');
return data.image;
}
/** 이야기 쓰는 칸: 로그인해야 쓴다. 주제·사진(하나)을 붙여 올린다 */
export function Composer() {
const { region } = useRegion();
const { loggedIn, me } = useAuth();
const { open } = useSheet();
const s = useSoft();
const [ink2] = useCSSVariable(['--color-ink2']).map(String);
const refresh = useRefreshTalks();
const add = useMutation(addTalkMutation());
const [text, setText] = useState('');
const [topic, setTopic] = useState<TalkTopic>(TalkTopic.LOCAL);
const [error, setError] = useState<string | null>(null);
const [photo, setPhoto] = useState<Photo | null>(null);
const [uploading, setUploading] = useState(false);
const busy = add.isPending || uploading;
const place = region.name.split(' ').at(-1);
const pick = async () => {
if (!loggedIn) return open({ type: 'login' });
try {
const res = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], quality: 0.85 });
const a = res.canceled ? undefined : res.assets[0];
if (!a) return;
if (a.fileSize && a.fileSize > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.');
setError(null);
setPhoto({ uri: a.uri, name: a.fileName ?? 'photo.jpg', type: a.mimeType ?? 'image/jpeg' });
} catch (e) {
console.error('[talk] pick photo', e);
setError('사진을 고르지 못했어요. 다시 해 주세요.');
}
};
const submit = async () => {
if (!loggedIn) return open({ type: 'login' });
const body = text.trim();
if (!body || busy) return;
setError(null);
let image: string | undefined;
if (photo) {
setUploading(true);
try {
image = await uploadPhoto(photo);
} catch (e) {
console.error('[talk] photo upload', e);
return setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.');
} finally {
setUploading(false);
}
}
add.mutate(
{ body: { region_code: region.code, body, image, topic } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.');
track('talk_post', { topic, with_image: !!image });
setText('');
setPhoto(null);
setTopic(TalkTopic.LOCAL);
refresh();
},
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
},
);
};
return (
<View className="mx-3 mt-3.5 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
{/* 로그인 전엔 칸을 눌러도 키보드 대신 로그인 창 */}
<Pressable disabled={loggedIn} onPress={() => open({ type: 'login' })}>
<TextInput
value={text}
onChangeText={setText}
editable={loggedIn && !busy}
maxLength={BODY_MAX}
multiline
numberOfLines={2}
placeholder={`지금 ${place} 날씨 어때요?`}
placeholderTextColor={s.placeholder}
accessibilityLabel="동네 이야기 쓰기"
className="min-h-[60px] rounded-2xl px-3 py-2.5 text-[14.5px] text-ink"
style={{ backgroundColor: s.soft, textAlignVertical: 'top' }}
pointerEvents={loggedIn ? 'auto' : 'none'}
/>
</Pressable>
{photo && (
<View className="mt-2 w-[96px]">
<Image source={{ uri: photo.uri }} style={{ width: 96, aspectRatio: 4 / 5, borderRadius: 12 }} contentFit="cover" accessibilityLabel="올릴 사진" />
<Pressable onPress={() => setPhoto(null)} accessibilityRole="button" accessibilityLabel="사진 빼기" className="absolute -top-1.5 -right-1.5 size-6 items-center justify-center rounded-full bg-ink-btn">
<Text className="text-[13px] font-extrabold text-white">×</Text>
</Pressable>
</View>
)}
<View className="mt-2 flex-row flex-wrap gap-1.5" accessibilityRole="radiogroup" accessibilityLabel="글 주제">
{openTopics().map(([k, label]) => (
<Pressable key={k} onPress={() => setTopic(k)} accessibilityRole="radio" accessibilityState={{ checked: topic === k }} className={`rounded-full px-2.5 py-1 ${topic === k ? 'bg-ink-btn' : ''}`} style={topic === k ? undefined : { backgroundColor: s.soft }}>
<Text className={`text-[12.5px] font-extrabold ${topic === k ? 'text-white' : 'text-ink2'}`}>{label}</Text>
</Pressable>
))}
</View>
<View className="mt-1.5 flex-row items-center gap-2">
{/* 주제 칩과 헷갈리지 않게 글자 대신 카메라 아이콘 */}
<Pressable onPress={pick} disabled={busy} hitSlop={6} accessibilityRole="button" accessibilityLabel="사진 붙이기" className="size-8 items-center justify-center rounded-full disabled:opacity-40" style={{ backgroundColor: s.soft }}>
<CameraIcon size={18} color={ink2} />
</Pressable>
<Text numberOfLines={1} className="min-w-0 flex-1 text-xs font-bold text-ink3">
{me ? `${me.nickname} · ${place} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}
</Text>
<Text className="text-xs font-bold text-ink3">
{text.length}/{BODY_MAX}
</Text>
<Pressable onPress={submit} disabled={busy || (loggedIn && !text.trim())} accessibilityRole="button" className="rounded-full bg-orange px-3.5 py-1.5 disabled:opacity-40">
<Text className="text-[13px] font-extrabold text-white">{busy ? '올리는 중…' : '올리기'}</Text>
</Pressable>
</View>
{!!error && (
<Text accessibilityRole="alert" className="mt-1 text-xs font-bold text-heart">
{error}
</Text>
)}
</View>
);
}
type Menu = 'closed' | 'open' | 'confirm' | 'report' | 'done';
/** 좋아요: 로그인 없이 된다. 화면을 먼저 바꾸고, 실패하면 되돌린다 */
function useTalkLike(t: TalkData) {
const [liked, setLiked] = useState(t.liked);
const [count, setCount] = useState(t.like_count);
const like = useMutation(likeTalkMutation());
const unlike = useMutation(unlikeTalkMutation());
const toggle = () => {
if (like.isPending || unlike.isPending) return;
const next = !liked;
setLiked(next);
setCount((n) => n + (next ? 1 : -1));
const revert = () => {
setLiked(!next);
setCount(t.like_count);
};
(next ? like : unlike).mutate(
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (!res.result?.success || res.like_count == null) return revert();
if (next) track('like', { content_type: 'talk', item_id: t.talk_id });
setCount(res.like_count);
},
onError: revert,
},
);
};
return { liked, count, toggle };
}
function Chip({ label, danger, onPress, disabled }: { label: string; danger?: boolean; onPress: () => void; disabled?: boolean }) {
return (
<Pressable onPress={onPress} disabled={disabled} className={`rounded-full px-3 py-1 ${danger ? 'bg-[#fdecec]' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[12.5px] font-extrabold ${danger ? 'text-heart' : 'text-[#28304a]'}`}>{label}</Text>
</Pressable>
);
}
/** 글 메뉴(⋯)를 눌렀을 때 나오는 버튼 줄: 내 글은 지우기, 남의 글은 안 보기·신고 */
function TalkMenu({ t, menu, setMenu, className }: { t: TalkData; menu: Menu; setMenu: (m: Menu) => void; className?: string }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const refresh = useRefreshTalks();
const remove = useMutation(deleteTalkMutation());
const report = useMutation(reportTalkMutation());
const block = useMutation(blockTalkAuthorMutation());
const [failed, setFailed] = useState(false);
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = (done?: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true);
done?.();
setMenu('done');
refresh();
},
onError: () => setFailed(true),
});
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }));
return (
<View className={`flex-row flex-wrap items-center gap-1.5 ${className ?? ''}`} accessibilityLabel="글 메뉴">
{menu === 'done' ? (
<Text className="text-[12.5px] font-extrabold text-[#1f9d62]">처리했어요</Text>
) : t.mine && menu === 'confirm' ? (
<>
<Text className="text-[12.5px] font-extrabold text-ink2">지울까요?</Text>
<Chip label="지우기" danger disabled={remove.isPending} onPress={() => remove.mutate({ path: { talk_id: t.talk_id } }, after())} />
<Chip label="취소" onPress={() => setMenu('closed')} />
</>
) : t.mine ? (
<Chip label="지우기" danger onPress={() => setMenu('confirm')} />
) : menu === 'report' ? (
REASONS.map(([reason, label]) => <Chip key={reason} label={label} disabled={report.isPending} onPress={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after(() => track('report', { content_type: 'talk', reason })))} />)
) : (
<>
<Chip label="이 사람 글 안 보기" disabled={block.isPending} onPress={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after(() => track('block', { content_type: 'talk' }))))} />
<Chip label="신고하기" danger onPress={() => guard(() => setMenu('report'))} />
</>
)}
{failed && <Text className="text-[12.5px] font-extrabold text-heart">못 했어요. 다시 해 주세요</Text>}
</View>
);
}
function MenuButton({ menu, setMenu }: { menu: Menu; setMenu: (m: Menu) => void }) {
return (
<Pressable onPress={() => setMenu(menu === 'closed' ? 'open' : 'closed')} hitSlop={12} accessibilityRole="button" accessibilityState={{ expanded: menu !== 'closed' }} accessibilityLabel="글 메뉴">
<Text className="text-[15px] font-extrabold tracking-[1px] text-ink3">⋯</Text>
</Pressable>
);
}
function MineBadge() {
return (
<Text className="overflow-hidden rounded-full bg-[#ffe8dc] px-1.5 text-[11px] font-extrabold text-[#c2471b]">
{' 내 글 '}
</Text>
);
}
/** 한 줄 글: 목록·내 정보의 내 글 */
function TalkRow({ t, last }: { t: TalkData; last?: boolean }) {
const { liked, count, toggle } = useTalkLike(t);
const [menu, setMenu] = useState<Menu>('closed');
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
const src = talkImage(t);
return (
<View className={`flex-row items-start gap-2.5 py-2.5 ${last ? '' : 'border-b border-line'}`}>
<Avatar character={t.character} color={t.color} mood={t.mood} />
<View className="min-w-0 flex-1">
<Text className="text-xs font-bold text-ink3">
<Text className="font-extrabold text-ink">{t.nickname} </Text>
{t.mine && (
<>
<MineBadge />{' '}
</>
)}
{talkMeta(t)}
</Text>
<Text className="mt-0.5 text-[14.5px] text-ink">{t.body}</Text>
{!!src && <Image source={{ uri: src }} style={{ marginTop: 8, width: '100%', aspectRatio: 4 / 5, borderRadius: 16, backgroundColor: '#eef4fc' }} contentFit="cover" />}
<Text className="mt-0.5 text-xs font-bold text-ink3">
{t.ago} · 좋아요 {count}개
</Text>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="mt-1.5" />}
</View>
{/* 글 메뉴(⋯)는 하트 옆 오른쪽 위에: 아래 줄 끝에 두면 말줄임표처럼 읽힌다 */}
<View className="flex-row items-start gap-4">
<MenuButton menu={menu} setMenu={setMenu} />
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요" className="pt-1">
<HeartIcon size={16} color={liked ? heart : ink3} filled={liked} />
</Pressable>
</View>
</View>
);
}
// 사진 없는 글을 크게 띄울 때 주제별 바탕
const TOPIC_BG: Partial<Record<TalkTopic, string>> = { [TalkTopic.SKY]: 'peach', [TalkTopic.RAIN]: 'sky', [TalkTopic.FOLIAGE]: 'butter', [TalkTopic.OUTFIT]: 'lilac' };
/** 오늘 피드에 끼우는 사람 글: 운영 포스트와 같은 틀. 사진이 없으면 글을 4:5 칸에 크게. 두 번 누르면 좋아요 */
export function TalkPost({ t }: { t: TalkData }) {
const { open } = useSheet();
const { liked, count, toggle } = useTalkLike(t);
const [menu, setMenu] = useState<Menu>('closed');
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const shot = useRef<View>(null);
const lastTap = useRef(0);
const shareView = useShare();
const src = talkImage(t);
const bg = (t.topic && (TOPIC_BG[t.topic] ?? holidayByTopic(t.topic)?.bg)) || 'mint';
const title = `${t.nickname}의 글`;
const share = () => void shareView(shot, { title, message: `${t.body} · 날씨각 ${SITE_URL}` });
const comments = () => open({ type: 'comments', talkId: t.talk_id });
const onTap = () => {
const now = Date.now();
if (now - lastTap.current < 320 && !liked) toggle();
lastTap.current = now;
};
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<Avatar character={t.character} color={t.color} mood={t.mood} />
<View className="min-w-0 flex-1">
<Text className="text-sm leading-tight font-extrabold text-ink">
{t.nickname}
{t.mine && (
<>
{' '}
<MineBadge />
</>
)}
</Text>
<Text numberOfLines={1} className="text-xs font-semibold text-ink2">
{talkMeta(t)}
</Text>
</View>
<MenuButton menu={menu} setMenu={setMenu} />
</View>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="px-3 pb-2.5" />}
<Pressable onPress={onTap} className="aspect-[4/5] overflow-hidden">
<View ref={shot} collapsable={false} className="flex-1">
{src ? (
<Image source={{ uri: src }} style={{ flex: 1, backgroundColor: '#eef4fc' }} contentFit="cover" />
) : (
// 포스트 안은 밤에도 낮 색 (웹 b-day)
<View className="flex-1 items-center justify-center px-7">
<LinearGradient colors={CARD_BG.day[bg] ?? CARD_BG.day.mint} style={{ position: 'absolute', inset: 0 }} />
<Text className={`text-center font-jua text-[26px] leading-snug ${bg === 'night' ? 'text-white' : 'text-[#28304a]'}`}>{t.body}</Text>
</View>
)}
</View>
</Pressable>
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
<Pressable onPress={toggle} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={liked ? heart : ink} filled={liked} />
</Pressable>
<Pressable onPress={comments} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
<CommentIcon size={26} color={ink} />
</Pressable>
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
<SendIcon size={26} color={ink} />
</Pressable>
</View>
<Text className="px-3 py-0.5 text-sm font-extrabold text-ink">좋아요 {count.toLocaleString()}개</Text>
{!!src && (
<Text className="px-3 py-0.5 text-sm text-ink">
<Text className="font-extrabold">{t.nickname} </Text>
{t.body}
</Text>
)}
<Pressable onPress={comments}>
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{t.comment_count ? `댓글 ${t.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">{t.ago}</Text>
</View>
);
}
/** 이야기 탭 목록의 글 한 장 */
export function TalkCard({ t }: { t: TalkData }) {
return (
<View className="mx-3 mt-3 rounded-[20px] border-b-4 border-shade bg-card px-3" accessibilityLabel={`${t.nickname}의 글`}>
<TalkRow t={t} last />
</View>
);
}
/** 내 정보 창의 내가 쓴 글 */
export function MyTalks() {
const { talks, loaded, more, loadMore } = useMyTalks();
const s = useSoft();
if (!loaded) return null;
return (
<View accessibilityLabel="내 글">
<Text className="mb-1 text-sm font-extrabold text-ink">내 글</Text>
{talks.length ? talks.map((t, i) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} last={i === talks.length - 1} />) : <Text className="text-[13px] font-semibold text-ink3">아직 쓴 글이 없어요</Text>}
{more && (
<Pressable onPress={() => loadMore()} className="mt-1 rounded-[14px] py-2.5" style={{ backgroundColor: s.soft }}>
<Text className="text-center text-[13.5px] font-extrabold text-ink2">더 보기</Text>
</Pressable>
)}
</View>
);
}
-53
View File
@@ -1,53 +0,0 @@
import type { PostReaction, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { MEDALS } from '@nalssigak/shared/lib';
import { Link } from 'expo-router';
import { Pressable, View } from 'react-native';
import { PostFrame } from '@/components/post/post-frame';
import { Text } from '@/components/text';
import { Grad, Ic } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
/** 오늘의 각 1~5위를 포스트 틀에 담은 카드 (웹 GakCard). 좋아요·댓글은 gak_post 에 붙는다 */
export function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
const { open } = useSheet();
const top = items.filter((g) => g.active).slice(0, 5);
return (
<PostFrame
title={`오늘의 각 · ${place}`}
account="오늘의 각"
avatar="rabbit"
caption="누르면 계산 근거를 보여 줘요"
pinned={{ key: 'gak_post', post }}
more={
<Link href="/gak" className="text-[13px] font-bold text-ink2">
전체 보기
</Link>
}
>
{/* 웹 b-band-2. 포스트 안은 밤에도 낮 색 */}
<Grad colors={['#fff6d8', '#f7fbff']} className="px-4 pt-3.5 pb-3">
<Text className="font-jua text-[19px] text-ink">
오늘의 각 · {place} {at}
</Text>
<View className="mt-2 gap-1.5">
{top.map((g, i) => (
<Pressable key={g.index_id} onPress={() => open({ type: 'gak', indexId: g.index_id })} accessibilityRole="button" accessibilityLabel={`${i + 1}위 ${g.name} ${g.score}점, 계산 근거 보기`} className="flex-row items-center gap-2.5 rounded-[18px] border-b-4 border-shade bg-card px-3 py-2">
{i < 3 ? <Ic name={MEDALS[i]} size={24} /> : <Text className="w-6 text-center font-jua text-ink3">{i + 1}</Text>}
<Ic name={g.icon} size={34} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">{g.name}</Text>
{!!g.summary && (
<Text numberOfLines={1} className="text-xs font-semibold text-ink2">
{g.summary}
</Text>
)}
</View>
<Text className="font-bagel text-[22px] text-orange">{g.score}</Text>
</Pressable>
))}
</View>
</Grad>
</PostFrame>
);
}
-349
View File
@@ -1,349 +0,0 @@
import { getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { Hero as HeroData, PostReaction, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { kindOfHour, kst, loadOf, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib';
import { KINDS, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today';
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Pressable, View, type DimensionValue, type ViewStyle } from 'react-native';
import { Text } from '@/components/text';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient';
import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg';
import { Fall } from '@/components/fall';
import { MoonArt } from '@/components/moon';
import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { Shoot, type ShootSpec } from '@/components/sky-bg';
import { Ic, Skel } from '@/components/ui';
import { track } from '@/lib/analytics';
import { usePinnedLike } from '@/lib/pinned-like';
import { useRegion } from '@/lib/region';
import { useShare } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { useSky } from '@/lib/sky';
type Mode = 'now' | TimeKind;
const HERO_BG: Record<TimeKind | 'gray', readonly [string, string, string]> = {
morning: ['#ffd9b8', '#ffe9d4', '#dff0ff'],
day: ['#9fd3ff', '#cfe9ff', '#f1f8ff'],
sunset: ['#4c42b0', '#6a48b0', '#9a4a88'],
night: ['#141b3d', '#27306a', '#3d3f86'],
gray: ['#a9bbd0', '#cbd7e4', '#eef2f7'],
};
// 가운데 해(낮)·달(저녁·밤) 색과 글자색
const ORB: Record<'sun' | 'sunset' | 'night', { stops: [string, string, string, string]; text: string }> = {
sun: { stops: ['#fff5cf', '#ffc86e', '#ff8e4e', '#ee6436'], text: '#5c1f08' },
sunset: { stops: ['#fff4e6', '#ffd9b8', '#f7a991', '#e07a8f'], text: '#4a2442' },
night: { stops: ['#ffffff', '#e7e3ff', '#b9b0f2', '#8f86d9'], text: '#2b2a5c' },
};
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }) as const);
// 구름 자리·떨어지는 지연·둥둥 주기 (웹 CLOUDS). 구름 수: 구름 많음 둘, 흐림·비·눈 셋
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게 (웹 TodayPage SHOOTS, 밀리초)
const SHOOTS: ShootSpec[] = [
{ top: '6%', left: '80%', len: 90, dur: 7000, dl: 1500 },
{ top: '20%', left: '52%', len: 70, dur: 9000, dl: 4000 },
{ top: '34%', left: '94%', len: 80, dur: 11000, dl: 6500 },
];
const CLOUDS = [
{ top: 36, left: '5%', w: 84, h: 32, d: 100, f: 6000 },
{ top: 96, left: '63%', w: 96, h: 36, d: 250, f: 6400 },
{ top: 30, left: '72%', w: 64, h: 28, d: 400, f: 5400 },
] as const;
const CLOUD_N: Record<Weather, number> = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 };
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, top: `${(i * 29) % 90}%`, delay: ((i * 37) % 100) * 10, dur: 550 + ((i * 13) % 5) * 100 }) as const);
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, top: `${(i * 31) % 90}%`, delay: ((i * 53) % 100) * 40, dur: 3200 + ((i * 7) % 5) * 500 }) as const);
/** 둥근 구름: 몸통 위에 동그라미 둘을 겹친다 (웹 .b-cloud ::before/::after) */
function Cloud({ w, h, night }: { w: number; h: number; night: boolean }) {
const bg = night ? '#c9cdf0' : '#fff';
const big = w * 0.46;
const small = w * 0.36;
return (
<View style={{ width: w, height: h }}>
<View style={{ position: 'absolute', left: w * 0.16, top: -h * 0.58, width: big, height: big, borderRadius: big, backgroundColor: bg }} />
<View style={{ position: 'absolute', left: w * 0.5, top: -h * 0.36, width: small, height: small, borderRadius: small, backgroundColor: bg }} />
<View style={{ width: w, height: h, borderRadius: h, backgroundColor: bg, boxShadow: '0 16px 28px rgb(40 70 120 / 0.13)' }} />
</View>
);
}
/** 비 줄기·눈송이 하나: 위에서 아래로 계속 떨어진다. 동작 줄이기면 제자리에 멈춘다 */
function Particle({ left, top, delay, dur, snow, light }: { left: DimensionValue; top: DimensionValue; delay: number; dur: number; snow: boolean; light: boolean }) {
const reduce = useReducedMotion();
const t = useSharedValue(0);
useEffect(() => {
if (reduce) return;
t.value = withDelay(delay, withRepeat(withTiming(1, { duration: dur, easing: Easing.linear }), -1, false));
return () => cancelAnimation(t);
}, [reduce, delay, dur, t]);
const anim = useAnimatedStyle(() => ({ transform: [{ translateX: (snow ? 18 : -8) * t.value }, { translateY: 440 * t.value }] }));
const place: ViewStyle = { position: 'absolute', left, top: reduce ? top : -24 };
if (snow) return <Animated.View style={[place, { width: 7, height: 7, borderRadius: 7, backgroundColor: '#fff', boxShadow: '0 0 4px rgb(120 150 200 / 0.5)' }, anim]} />;
return (
<Animated.View style={[place, anim]}>
<LinearGradient colors={['transparent', light ? 'rgba(220,230,255,0.7)' : 'rgba(80,130,200,0.7)']} style={{ width: 2, height: 18, borderRadius: 2 }} />
</Animated.View>
);
}
function useNow(ms = 20000) {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => setNow(new Date()), ms);
return () => clearInterval(id);
}, [ms]);
return now;
}
const failed = (load: Load) => load === 'error' || load === 'retrying';
// 값이 오기 전엔 스켈레톤, 못 불러왔거나 값이 없으면 '?'
function heroVal(load: Load, v: ReactNode, skel: string) {
if (v != null) return v;
if (load === 'loading') return <Skel className={skel} />;
return <Text className="opacity-50">?</Text>;
}
type Props = { hero?: HeroData | null; post?: PostReaction | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load };
export function Hero({ hero, post, today, ranked, feedLoad, todayLoad }: Props) {
const { open } = useSheet();
const { region } = useRegion();
const like = usePinnedLike('hero_post', post);
const shot = useRef<View>(null);
// 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다 (웹 TodayPage Hero)
const [tmr, setTmr] = useState(false);
const [tmrKind, setTmrKind] = useState<TimeKind>('day');
const tomorrowQ = useQuery({ ...getWeatherTodayOptions({ query: { region: region.code, day: 'tomorrow' } }), enabled: tmr });
const ahead = hero?.tomorrow;
const { preview, setServerKind, setPreview } = useSky();
const mode: Mode = tmr ? tmrKind : (preview ?? 'now');
const clock = useNow();
const t = kst(tmr ? new Date(clock.getTime() + 86400000) : clock);
const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi);
const kind = mode === 'now' ? nowKind : mode;
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind]);
// 내일을 볼 땐 배경·글자색도 내일 고른 칸을 따른다
useEffect(() => {
if (tmr) setPreview(tmrKind);
}, [tmr, tmrKind, setPreview]);
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? [];
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad;
// 지금은 가장 가까운 3시간 칸. 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
const slotOf = (k: Mode) => {
if (k === 'now') {
const known = slots.filter((x) => x.temp_c != null);
const at = t.h + t.mi / 60;
return known.length ? known.reduce((a, b) => (Math.abs(kst(b.at).h - at) < Math.abs(kst(a.at).h - at) ? b : a)) : undefined;
}
const h = PREVIEW[k].hour;
const s = slots.length ? slotAt(slots, h) : undefined;
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s);
};
const weather = weatherOf(slotOf(mode));
const slotScore = mode === 'now' ? undefined : (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[mode]];
const score = tmr ? slotScore : (slotScore ?? hero?.weather_score);
// 점수를 누르면 보고 있는 시간대(지금이면 지금 구간)의 날씨 점수 근거
const whyKey = mode === 'now' ? SLOT_KEY[nowKind] : SLOT_KEY[mode];
const why = (tmr ? ahead?.weather_why : hero?.weather_why)?.[whyKey];
const whyLabel = tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label;
const slotTop = mode === 'now' || tmr ? undefined : ranked.find((g) => g.active);
const top1 = tmr ? ahead?.top1 : (slotTop ?? hero?.top1);
const dark = kind === 'sunset' || kind === 'night';
const moon = !tmr && dark && hero?.moon_name && hero.moon_pct != null ? { pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null;
// 말풍선 머리말: 지금은 / 낮은 / 내일은 / 내일 낮은
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label;
const tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}`;
const bubble = tmr
? top1
? top1.score >= 70
? `${tmrWhen}은 ${top1.name}!`
: `${tmrWhen}은 쉬어 가요`
: null
: slotTop
? slotTop.score >= 70
? `${when}은 ${slotTop.name}!`
: `${when}은 쉬어 가요`
: hero
? (hero.bubble ?? '지금은 쉬어 가요')
: failed(feedLoad)
? '앗, 날씨를 못 불러왔어요'
: null;
// 내일은 최저·최고 기온과 고른 시간대 습도
const temps = slots.flatMap((x) => (x.temp_c != null ? [x.temp_c] : []));
const humidity = tmr && mode !== 'now' ? slotOf(mode)?.humidity : null;
const status = tmr
? [
...(temps.length
? [
{ label: '최저', value: deg(Math.min(...temps)), tone: 'info' },
{ label: '최고', value: deg(Math.max(...temps)), tone: 'info' },
]
: []),
...(humidity != null ? [{ label: '습도', value: `${humidity}%`, tone: 'info' }] : []),
]
: (hero?.status ?? []);
const openWhy = () => why && score != null && open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } });
const switchDay = (v: boolean) => {
// 내일로 넘어갈 땐 지금 보던 시간대 그대로 시작해 배경이 튀지 않게
if (v && !tmr) setTmrKind(kind);
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}` });
};
const gray = !dark && weather !== 'clear' && weather !== 'partly';
const rain = weather === 'rain' || weather === 'sleet';
const snow = weather === 'snow' || weather === 'sleet';
const orb = ORB[kind === 'sunset' ? 'sunset' : kind === 'night' ? 'night' : 'sun'];
const text = dark ? 'text-white' : 'text-[#28304a]';
const icon = dark ? '#ffffff' : '#28304a';
const strip = dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)';
// 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐·삭)이면 흰 글씨
const orbText: { color: string; textShadowColor?: string; textShadowRadius?: number } = !moon
? { color: orb.text }
: moon.pct >= 50
? { color: orb.text, textShadowColor: '#fff', textShadowRadius: 8 }
: { color: '#fff', textShadowColor: 'rgba(10,14,40,0.6)', textShadowRadius: 8 };
return (
<View ref={shot} collapsable={false} className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
<LinearGradient colors={HERO_BG[gray ? 'gray' : kind]} locations={kind === 'night' ? [0, 0.6, 1] : [0, 0.5, 1]} style={{ position: 'absolute', inset: 0 }} />
{kind === 'night' && STARS.map((s, i) => <View key={i} className="absolute size-[3px] rounded-full bg-white" style={{ left: s.left, top: s.top, opacity: s.opacity }} />)}
{kind === 'night' && SHOOTS.map((s, i) => <Shoot key={i} {...s} />)}
{(rain || snow) && (
<View pointerEvents="none" style={{ position: 'absolute', inset: 0 }}>
{rain && DROPS.map((p, i) => <Particle key={`r${i}`} {...p} snow={false} light={dark} />)}
{snow && FLAKES.map((p, i) => <Particle key={`s${i}`} {...p} snow light={dark} />)}
</View>
)}
<View className="z-[3] flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
<View className="flex-row rounded-full p-[3px]" style={{ backgroundColor: strip }} accessibilityRole="radiogroup" accessibilityLabel="오늘 또는 내일 날씨">
{(
[
[false, '오늘'],
[true, '내일'],
] as const
).map(([v, l]) => (
<Pressable key={l} onPress={() => switchDay(v)} accessibilityRole="radio" accessibilityState={{ checked: tmr === v }} className={`rounded-full px-2.5 py-0.5 ${tmr === v ? 'bg-white' : ''}`}>
<Text className={`font-jua text-[13px] ${tmr === v ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{l}</Text>
</Pressable>
))}
</View>
<Text className={`text-[13px] font-bold opacity-80 ${text}`}>
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</Text>
</View>
<View className="flex-row items-center">
{post && (
<>
<Pressable onPress={like.toggle} hitSlop={6} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel={like.failed ? '좋아요를 반영하지 못했어요. 다시 눌러 주세요' : '오늘 날씨 좋아요'} className={`h-8 flex-row items-center gap-1 px-[5px] ${like.liked ? '' : 'opacity-80'}`}>
<HeartIcon size={22} color={like.liked ? '#ff3b5c' : icon} filled={like.liked} />
{like.count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{like.count.toLocaleString()}</Text>}
</Pressable>
<Pressable onPress={() => open({ type: 'comments', postId: post.post_id })} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 댓글" className="h-8 flex-row items-center gap-1 px-[5px] opacity-80">
<CommentIcon size={22} color={icon} />
{post.comment_count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{post.comment_count.toLocaleString()}</Text>}
</Pressable>
</>
)}
<Pressable onPress={share} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 보내기" className="h-8 flex-row items-center px-[5px] opacity-80">
<SendIcon size={22} color={icon} />
</Pressable>
</View>
</View>
<View className="h-[146px] items-center">
<Fall d={0} f={5600} amp={8}>
<View className="mt-2 size-32 items-center justify-center" style={moon ? undefined : { boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}>
{/* 저녁·밤엔 오늘 밤 실제 모양의 달 (빛 번짐까지 그려서 공보다 크게) */}
{moon ? (
<View pointerEvents="none" style={{ position: 'absolute', top: -32, left: -32 }}>
<MoonArt pct={moon.pct} waxing={!moon.waning} tone={kind === 'sunset' ? 'dusk' : 'night'} size={192} />
</View>
) : (
<Svg viewBox="-1 -1 2 2" width={128} height={128} style={{ position: 'absolute' }}>
<Defs>
<RadialGradient id="orb" cx="-0.32" cy="-0.4" r="1.4" gradientUnits="userSpaceOnUse">
<Stop offset="0" stopColor={orb.stops[0]} />
<Stop offset="0.3" stopColor={orb.stops[1]} />
<Stop offset="0.68" stopColor={orb.stops[2]} />
<Stop offset="1" stopColor={orb.stops[3]} />
</RadialGradient>
</Defs>
<Rect x="-1" y="-1" width="2" height="2" rx="1" fill="url(#orb)" opacity={gray ? 0.85 : 1} />
</Svg>
)}
{/* 점수 근거가 있으면 해를 눌러도 근거 창 */}
<Pressable disabled={!why || score == null} onPress={openWhy} className="items-center" accessibilityLabel={why && score != null ? `${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기` : undefined}>
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text>
</Pressable>
</View>
</Fall>
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
<Fall key={c.left} d={c.d} f={c.f} style={{ position: 'absolute', top: c.top, left: c.left }}>
<Cloud w={c.w} h={c.h} night={kind === 'night'} />
</Fall>
))}
</View>
<View className="items-center">
{bubble ? (
<Pressable disabled={!top1} onPress={() => top1 && open({ type: 'gak', indexId: top1.index_id })} accessibilityLabel={top1 ? `${bubble} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기` : undefined}>
<Text className={`text-center font-jua text-[24px] leading-tight ${text}`}>{bubble}</Text>
</Pressable>
) : (
<Skel className="h-6 w-[160px]" />
)}
{top1?.summary ? <Text className={`mt-0.5 text-center text-[15px] font-bold opacity-80 ${text}`}>{top1.summary}</Text> : feedLoad === 'loading' ? <Skel className="mt-1 w-[140px]" /> : null}
{/* 상태 한 줄: 습도·불쾌지수·자외선·미세먼지 단계 이름. 조심할 것만 색 */}
{status.length > 0 && (
<Text className={`mt-1.5 text-center font-jua text-[14px] ${text}`}>
{status.map((x, i) => (
<Text key={x.label}>
{i > 0 && <Text className="opacity-30"> · </Text>}
<Text style={x.tone === 'warn' ? { color: dark ? '#ffb38a' : '#d4552a' } : undefined}>
<Text className={x.tone !== 'warn' ? 'opacity-75' : undefined}>{x.label}</Text> {x.value}
</Text>
</Text>
))}
{why && score != null && (
<Text onPress={openWhy} accessibilityRole="button" accessibilityLabel={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} style={{ color: dark ? '#ffb38a' : '#d4552a' }}>
{' '}· 점수 근거 ›
</Text>
)}
</Text>
)}
</View>
<View className="mt-2.5 flex-row gap-1 rounded-[18px] p-[3px]" style={{ backgroundColor: dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)' }} accessibilityRole="tablist" accessibilityLabel="하루 흐름, 누르면 그 시간대 하늘로">
{KINDS.map((k) => {
const isNow = !tmr && k === nowKind;
const s = slotOf(isNow ? 'now' : k);
const on = k === kind;
return (
<Pressable key={k} accessibilityRole="tab" accessibilityState={{ selected: on }} onPress={() => (tmr ? setTmrKind(k) : setPreview(isNow ? null : k))} className={`flex-1 items-center rounded-[14px] py-1.5 ${on ? 'bg-white' : ''}`} style={on ? { boxShadow: '0 4px 12px rgb(40 48 74 / 0.1)' } : undefined}>
<Text className={`text-[13px] font-bold ${on ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{isNow ? '지금' : PREVIEW[k].label}</Text>
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} size={22} style={{ marginVertical: 2 }} />
<Text className={`font-jua text-[15px] ${on ? 'text-[#28304a]' : text}`}>{heroVal(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</Text>
</Pressable>
);
})}
</View>
</View>
);
}
-61
View File
@@ -1,61 +0,0 @@
import { router, type Href } from 'expo-router';
import type { ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Rail } from '@/components/ui';
import { track } from '@/lib/analytics';
import { HIDDEN } from '@/lib/level';
import { useSajuSeenToday } from '@/lib/saju-birth';
type Item = { key: string; label: string; icon: string; badge?: ReactNode; to?: Href; onPress?: () => void };
const Dot = () => <View className="absolute -top-0.5 -right-0.5 size-[11px] rounded-full border-2 border-white bg-[#ff4d4f]" />;
function Tile({ it }: { it: Item }) {
return (
<>
<View className="size-[52px] items-center justify-center rounded-[17px] border-b-4 border-shade bg-card">
<Ic name={it.icon} size={32} />
{it.badge}
</View>
<Text className="mt-1.5 text-[11.5px] font-extrabold text-ink2">{it.label}</Text>
</>
);
}
/** 오늘 탭 히어로 아래 아이콘 줄: 누르면 그 화면으로 가거나 내 각 줄로 내려간다. 오늘 아직 안 본 사주엔 빨간 점 (웹 todayIcons.tsx, 타로는 웹처럼 숨김) */
export function TodayIcons({ foliage, onMyGak }: { foliage: boolean; onMyGak: () => void }) {
const sajuSeen = useSajuSeenToday();
const all: Item[] = [
{ key: 'saju', label: '날씨 사주', icon: 'yin_yang', badge: sajuSeen ? null : <Dot />, to: '/saju' },
{ key: 'game', label: '날씨 게임', icon: 'game', to: '/game' },
...(foliage ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' as Href }] : []),
{ key: 'shorts', label: '쇼츠', icon: 'clapper', to: '/shorts' },
{ key: 'myGak', label: '내 각', icon: 'rabbit', onPress: onMyGak },
{ key: 'talk', label: '동네 이야기', icon: 'speech', to: '/talk' },
];
const items = all.filter((it) => !HIDDEN.has(it.key));
return (
<View accessibilityLabel="바로 가기" className="pb-2">
<Rail>
{items.map((it) => (
<Pressable
key={it.key}
onPress={() => {
track('today_icon', { icon: it.key });
if (it.to) router.push(it.to);
else it.onPress?.();
}}
accessibilityRole={it.to ? 'link' : 'button'}
accessibilityLabel={it.label}
className="w-[60px] items-center"
>
<Tile it={it} />
</Pressable>
))}
</Rail>
</View>
);
}
-54
View File
@@ -1,54 +0,0 @@
import type { BandArticle } from '@nalssigak/shared/api/client/types.gen';
import { cardBg } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import type { Href } from 'expo-router';
import type { ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Rail, Sec, Thumb } from '@/components/ui';
import { CARD_BG, BAND_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
const CARD = 'overflow-hidden rounded-[22px] border-b-[5px] border-shade bg-card';
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: Href; children: ReactNode }) {
const { kind } = useSky();
return (
<View className="mt-3.5 pb-3.5" accessibilityLabel={title}>
<LinearGradient colors={BAND_BG[kind === 'night' ? 'night' : 'day'][tone]} style={{ position: 'absolute', inset: 0 }} />
<View className="-mt-[6px]">
<Sec title={title} sub={sub} more={to} />
</View>
{children}
</View>
);
}
function useCardBg() {
const { kind } = useSky();
return CARD_BG[kind === 'night' ? 'night' : 'day'];
}
export function SeasonBand({ news }: { news: BandArticle[] }) {
const bg = useCardBg();
const { open } = useSheet();
return (
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
<Rail>
{news.map((a) => (
<Pressable key={a.article_id} onPress={() => open({ type: 'article', articleId: a.article_id })} className={`w-[200px] ${CARD}`}>
<Thumb image={a.image} icon={a.icon} iconSize={76} className="h-[116px]">
<LinearGradient colors={bg[cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
</Thumb>
<View className="px-3 pt-2.5 pb-3">
<Text className="font-jua text-[16.5px] leading-snug text-ink">{a.title}</Text>
<Text className="text-[12.5px] font-semibold text-ink2">{a.meta}</Text>
</View>
</Pressable>
))}
</Rail>
</Band>
);
}
-96
View File
@@ -1,96 +0,0 @@
import { getSeasonWeekOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { kst, seasonOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { usePathname } from 'expo-router';
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
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';
const TITLES: Record<string, string> = { '/sky': '노을', '/gak': '오늘의 각', '/week': '주말·행사', '/season': '계절·상식' };
/** 로고 옆 계절 칩: 계절 이름과 지금 절기. 누르면 이번 주 절기 창 */
function SeasonChip() {
const { open } = useSheet();
const week = useQuery(getSeasonWeekOptions());
const [month] = useState(() => kst(new Date()).mo);
const [name, icon] = seasonOf(month);
const term = week.data?.term_now?.name;
return (
<Pressable onPress={() => open({ type: 'seasonWeek' })} accessibilityLabel={`지금 ${name}${term ? `, ${term}` : ''}. 이번 주 절기 보기`} className="shrink flex-row items-center gap-1 rounded-full bg-card/70 py-1 pr-2.5 pl-1.5">
<Ic name={icon} size={18} />
<Text numberOfLines={1} className="shrink text-[13px] font-extrabold text-ink">
{name}
{term && <Text className="font-bold opacity-70"> · {term}</Text>}
</Text>
</Pressable>
);
}
/** 아바타 옆 작은 레벨 표시 */
function LevelBadge() {
const level = useLevel().data;
if (!level) return null;
return (
<View pointerEvents="none" className="absolute -right-1.5 -bottom-1.5 rounded-full border-2 border-white bg-ink-btn px-1.5">
<Text className="text-[9.5px] leading-4 font-extrabold text-white">Lv.{level.level}</Text>
</View>
);
}
/** 오른쪽 끝: 내 정보(아바타) 또는 로그인 버튼 */
function Account() {
const { open } = useSheet();
const { me, mePending } = useAuth();
if (mePending) return <View className="size-9 shrink-0 rounded-full bg-skel" />;
if (me)
return (
<Pressable onPress={() => open({ type: 'me' })} accessibilityLabel={`내 정보, ${me.nickname}`} className="shrink-0 rounded-full" style={{ boxShadow: '0 6px 12px rgb(40 48 74 / 0.12)' }}>
<Avatar character={me.character} color={me.color} mood={me.mood} size={36} />
<LevelBadge />
</Pressable>
);
return (
<Pressable onPress={() => open({ type: 'login' })} className="shrink-0 rounded-full bg-ink-btn px-3 py-1.5">
<Text className="text-[13px] font-extrabold text-white">로그인</Text>
</Pressable>
);
}
export function TopBar() {
const pathname = usePathname();
const { region, locateStatus } = useRegion();
const { open } = useSheet();
const { kind } = useSky();
const { top } = useSafeAreaInsets();
const ink = String(useCSSVariable('--color-ink'));
const title = TITLES[pathname];
return (
<View style={{ paddingTop: top, backgroundColor: kind === 'night' ? 'rgb(14 20 51 / 0.35)' : 'rgb(255 255 255 / 0.18)' }}>
<View className="h-[54px] flex-row items-center gap-2 px-4">
{title ? <Text className="font-jua text-[22px] text-ink">{title}</Text> : <Text className="font-jua text-[25px] text-orange">날씨각</Text>}
<SeasonChip />
<Pressable onPress={() => open({ type: 'region' })} accessibilityLabel={`위치 바꾸기, 지금 ${region.name}`} className="ml-auto shrink-0 flex-row items-center gap-1 rounded-full border-b-4 border-shade bg-card px-3 pt-1 pb-1.5">
<PinIcon size={14} color={ink} />
{locateStatus === 'locating' ? (
<Skel className="w-[52px]" />
) : (
<Text numberOfLines={1} className="text-[13.5px] font-bold text-ink">
{region.name.split(' ').at(-1)}
</Text>
)}
</Pressable>
<Account />
</View>
</View>
);
}
-192
View File
@@ -1,192 +0,0 @@
import { AVATAR_COLORS, moodEmoji, naverMap, type Load } from '@nalssigak/shared/lib';
import { Image, type ImageStyle } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { Link, type Href } from 'expo-router';
import { useEffect, useState, type ReactNode } from 'react';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated';
import { Linking, Pressable, ScrollView, View, type StyleProp, type ViewStyle } from 'react-native';
import { Text } from '@/components/text';
import { ICONS } from '@/lib/icons';
import { imageUri } from '@/lib/site';
/** 아이콘 이름 → 그림. 'none'(데이터 없는 칸)은 빈 자리, 모르는 이름은 구름 낀 해 */
export function Ic({ name, size, style }: { name: string; size: number; style?: StyleProp<ImageStyle> }) {
if (name === 'none') return <View style={{ width: size, height: size }} />;
return <Image source={ICONS[name] ?? ICONS.sun_cloud} style={[{ width: size, height: size }, style]} contentFit="contain" />;
}
type Stops = readonly [string, string, ...string[]];
/** 위에서 아래로 흐르는 그라데이션 (웹 linear-gradient(180deg, ...)) */
export function Grad({ colors, locations, className, style, children }: { colors: Stops; locations?: readonly [number, number, ...number[]]; className?: string; style?: StyleProp<ViewStyle>; children?: ReactNode }) {
return (
<View className={className} style={style}>
<LinearGradient colors={colors} locations={locations} style={{ position: 'absolute', inset: 0 }} />
{children}
</View>
);
}
/** 사진이 있으면 사진, 없거나 못 불러오면 아이콘 */
export function Thumb({ image, icon, iconSize, className, style, children }: { image?: string | null; icon: string; iconSize: number; className?: string; style?: StyleProp<ViewStyle>; children?: ReactNode }) {
const [failed, setFailed] = useState<string | null>(null);
const photo = image && image !== failed ? image : null;
return (
<View className={`items-center justify-center overflow-hidden ${className ?? ''}`} style={style}>
{photo ? <Image source={{ uri: imageUri(photo) }} onError={() => setFailed(photo)} style={{ position: 'absolute', inset: 0 }} contentFit="cover" /> : <Ic name={icon} size={iconSize} />}
{children}
</View>
);
}
/** 불러오는 동안 자리만 잡는 막대. 천천히 깜빡인다 (웹 animate-pulse, 동작 줄이기면 멈춤) */
export function Skel({ className }: { className?: string }) {
const reduce = useReducedMotion();
const dim = useSharedValue(0);
useEffect(() => {
if (reduce) return;
dim.value = withRepeat(withTiming(1, { duration: 1000, easing: Easing.bezier(0.4, 0, 0.6, 1) }), -1, true);
return () => cancelAnimation(dim);
}, [reduce, dim]);
const pulse = useAnimatedStyle(() => ({ opacity: 1 - dim.value * 0.5 }));
return (
<Animated.View style={pulse}>
<View className={`h-[0.9em] min-h-3 rounded-full bg-skel ${className ?? ''}`} />
</Animated.View>
);
}
export function Sec({ title, sub, more }: { title: string; sub?: string; more?: Href }) {
return (
<View className="flex-row items-end justify-between px-4 pt-[22px] pb-1.5">
<View>
<Text className="font-jua text-[21px] text-ink">{title}</Text>
{sub && <Text className="mt-0.5 text-[13px] font-semibold text-ink2">{sub}</Text>}
</View>
{more && (
<Link href={more} className="text-[13px] font-bold text-ink2">
전체 보기
</Link>
)}
</View>
);
}
/** 가로로 넘기는 줄 */
export function Rail({ children }: { children: ReactNode }) {
return (
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerClassName="gap-2.5 px-4 pt-3 pb-1">
{children}
</ScrollView>
);
}
/**
* 실패·빈 목록 안내. 불러오는 중엔 그리지 않는다(그 자리는 스켈레톤).
* hold 에 스켈레톤을 주면 그 크기를 보이지 않게 깔고 안내를 그 위에 띄운다 — 로딩·실패·빈 상태의 자리 크기가 같다.
* 이때 boxClassName 은 안내 상자의 위치(스켈레톤 바깥 여백만큼 inset).
*/
export function StateBox({ load, onRetry, empty, hold, boxClassName = 'inset-x-3 top-3 bottom-0' }: { load: Load; onRetry?: () => void; empty?: string; hold?: ReactNode; boxClassName?: string }) {
const failed = load === 'error' || load === 'retrying';
const text = failed ? '정보를 불러오지 못했어요.' : load === 'ready' ? empty : undefined;
if (!text) return null;
const box = (
<View className={`items-center justify-center gap-2 rounded-[22px] border-b-[5px] border-shade bg-card px-4 py-6 ${hold ? `absolute ${boxClassName}` : 'mx-3 mt-3'}`}>
<Text className="text-center text-[13.5px] font-semibold text-ink2">{text}</Text>
{failed && onRetry && (
<Pressable onPress={onRetry} disabled={load === 'retrying'} className="rounded-full bg-ink-btn px-4 py-1.5 disabled:opacity-60">
<Text className="text-[13px] font-bold text-white">{load === 'retrying' ? '다시 불러오는 중…' : '다시 시도'}</Text>
</Pressable>
)}
</View>
);
if (!hold) return box;
return (
<View>
<View style={{ opacity: 0 }} pointerEvents="none" accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
{hold}
</View>
{box}
</View>
);
}
/** 사진 출처 표기 (공공누리 조건). 위치는 className 으로 */
export function Credit({ text, className = 'right-1 bottom-1' }: { text: string; className?: string }) {
return (
<View pointerEvents="none" className={`absolute z-[1] rounded-[5px] bg-[rgb(16_20_34/0.5)] px-1 py-px ${className}`}>
<Text numberOfLines={1} className="text-[9px] leading-tight font-semibold text-white">
{text}
</Text>
</View>
);
}
/** 프로필 동그라미: 고른 배경색 위에 캐릭터, 오른쪽 위에 오늘 기분 */
export function Avatar({ character, color, mood, size = 34 }: { character: string; color?: string | null; mood?: string | null; size?: number }) {
const emoji = moodEmoji(mood);
return (
<View className="items-center justify-center rounded-full" style={{ width: size, height: size, backgroundColor: AVATAR_COLORS[color ?? ''] ?? AVATAR_COLORS.orange }}>
<Ic name={character} size={size * 0.7} />
{emoji && (
<View className="absolute -top-1 -right-1 items-center justify-center rounded-full bg-white" style={{ width: size * 0.48, height: size * 0.48 }}>
<Text style={{ fontSize: size * 0.3 }}>{emoji}</Text>
</View>
)}
</View>
);
}
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; disabled?: boolean };
/** 가로로 넘기는 고르기 칩 */
export function Chips<K extends string>({ items, value, onChange, disabled }: ChipsProps<K>) {
return (
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerClassName="gap-2 px-4 pt-3 pb-0.5">
{items.map(([k, l]) => (
<Pressable key={k} accessibilityState={{ selected: value === k }} disabled={disabled} onPress={() => onChange(k)} className={`rounded-full px-3.5 py-[7px] ${value === k ? 'bg-ink-btn' : 'border-b-[3px] border-shade bg-chip'}`}>
<Text className={`text-[13.5px] font-bold ${value === k ? 'text-white' : 'text-ink2'}`}>{l}</Text>
</Pressable>
))}
</ScrollView>
);
}
/** 장소 이름. 누르면 네이버 지도가 열린다 */
export function MapLink({ place, children }: { place: string; children: ReactNode }) {
return (
<Text onPress={() => Linking.openURL(naverMap(place))} accessibilityRole="link" accessibilityLabel={`${place}, 네이버 지도에서 보기`} className="underline">
{children}
</Text>
);
}
/** 자외선 단계(1 낮음 ~ 5 위험) 칩 색 */
const LEVEL_CHIP = [
['#1f9d62', '#fff'],
['#ffc21a', '#3a2a00'],
['#f0700a', '#fff'],
['#e03131', '#fff'],
['#8e3bc4', '#fff'],
] as const;
/** 줄 목록 (라벨 · 값) */
export function Rows({ rows, dark = false }: { rows: { label: string; value: string; place?: string | null; level?: number | null }[]; dark?: boolean }) {
return (
<View className="mt-auto">
{rows.map((r, i) => (
<View key={r.label} className="flex-row items-center justify-between gap-2.5 py-2.5" style={i < rows.length - 1 ? { borderBottomWidth: 2, borderColor: dark ? 'rgb(255 255 255 / 0.18)' : 'rgb(40 48 74 / 0.08)' } : undefined}>
<Text className={`font-bold ${dark ? 'text-white' : 'text-ink'}`}>{r.label}</Text>
{r.level ? (
<Text className="overflow-hidden rounded-full px-2.5 py-[3px] font-jua text-[15px]" style={{ backgroundColor: LEVEL_CHIP[r.level - 1][0], color: LEVEL_CHIP[r.level - 1][1] }}>
{r.value}
</Text>
) : (
<Text className={`text-right font-jua text-[17px] ${dark ? 'text-white' : 'text-ink'}`}>{r.place ? <MapLink place={r.place}>{r.value}</MapLink> : r.value}</Text>
)}
</View>
))}
</View>
);
}
-150
View File
@@ -1,150 +0,0 @@
import type { EventData, PlaceData, WeekRankItem, DayData } from '@nalssigak/shared/api/client/types.gen';
import { cardBg, dateRange } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, ScrollView, View } from 'react-native';
import { Text } from '@/components/text';
import { Credit, Ic, MapLink, Thumb } from '@/components/ui';
import { CARD_BG } from '@/lib/colors';
import { useSky } from '@/lib/sky';
import { DAY_W, EVENT_CARD, PLACE_CARD } from './skels';
const PLACE_BG: Record<string, string> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', bulb: 'lilac' };
function useBg() {
const { kind } = useSky();
return { night: kind === 'night', bg: CARD_BG[kind === 'night' ? 'night' : 'day'] };
}
/** 열흘 날짜 줄: 누르면 그날 추천이 바뀐다 */
export function DayStrip({ days, selected, onPick, dim }: { days: DayData[]; selected?: string; onPick: (day: string) => void; dim: boolean }) {
const { night } = useBg();
const red = night ? '#ff8db5' : '#d6457a';
return (
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerClassName="gap-1 px-3 pt-3" style={{ opacity: dim ? 0.6 : 1 }} accessibilityLabel="날짜 고르기">
{days.map((d) => {
const on = d.day === selected;
const weekend = d.weekday === '토' || d.weekday === '일' || !!d.holiday;
return (
<Pressable key={d.day} accessibilityState={{ selected: on }} onPress={() => onPick(d.day)} className={`${DAY_W} items-center gap-0.5 rounded-[18px] pt-[9px] pb-2 ${on ? 'bg-ink-btn' : 'border-b-4 border-shade bg-card'}`}>
<Text className={`text-xs font-extrabold ${on ? 'text-white' : weekend ? '' : 'text-ink2'}`} style={!on && weekend ? { color: red } : undefined}>
{d.weekday}
</Text>
<Ic name={d.icon} size={28} />
<Text className={`font-jua text-sm ${on ? 'text-white' : 'text-ink'}`}>{d.temp_max_c != null ? `${Math.round(d.temp_max_c)}°` : <Text className="opacity-50">?</Text>}</Text>
<Text numberOfLines={1} className="px-0.5 text-[9.5px] font-extrabold" style={{ color: on ? '#ffb3c4' : red }}>
{d.holiday ? d.holiday.replace(/\(.*\)/, '') : `${Number(d.day.slice(8))}일`}
</Text>
</Pressable>
);
})}
</ScrollView>
);
}
/** 고른 날 추천 한 장 */
export function PickCard({ day }: { day: DayData }) {
const { night, bg } = useBg();
return (
<View className="mx-3 mt-3 flex-row items-center gap-3.5 overflow-hidden rounded-3xl border-b-[5px] border-shade p-4" accessibilityLiveRegion="polite">
<LinearGradient colors={night ? bg.mint : ['#e9fbf2', '#ffffff']} style={{ position: 'absolute', inset: 0 }} />
<Ic name={day.icon} size={64} />
<View className="flex-1">
<Text className="font-jua text-[19px] text-ink">{day.headline}</Text>
<Text className="mt-0.5 text-[13.5px] font-semibold text-ink2">{day.summary}</Text>
<Text className="mt-2 font-jua text-base text-ink">{day.pick}</Text>
</View>
</View>
);
}
export function PlaceCard({ place: p, index }: { place: PlaceData; index: number }) {
const { bg } = useBg();
return (
<View className={PLACE_CARD}>
<Thumb image={p.image} icon={p.icon} iconSize={62} className="h-[104px]">
<LinearGradient colors={bg[PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, index))]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
{p.is_good && (
<View className={`absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] ${p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-rain'}`}>
<Text className="text-[11.5px] font-extrabold text-white">{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</Text>
</View>
)}
{p.image && p.image_credit && <Credit text={p.image_credit} />}
</Thumb>
<View className="px-3 pt-2.5 pb-3">
<Text className="text-[11.5px] font-extrabold text-ink3">
{p.area} · {p.distance_km}km · {p.is_outdoor ? '야외' : '실내'}
</Text>
<Text className="font-jua text-[16.5px] text-ink">
<MapLink place={p.name}>{p.name}</MapLink>
</Text>
<Text className="text-[12.5px] leading-snug font-semibold text-ink2">
{p.reason}
{'\n'}추천 {p.best_time}
</Text>
</View>
</View>
);
}
export function RankRow({ item: r, mine }: { item: WeekRankItem; mine: boolean }) {
return (
<View className={`flex-row items-center gap-2.5 border-b-[1.5px] border-line px-1 py-3 ${mine ? 'rounded-2xl bg-card' : ''}`}>
<Text className="w-[34px] text-center font-bagel text-xl text-orange">{r.rank}</Text>
<View className="min-w-0 flex-1">
<Text numberOfLines={1} className="font-jua text-[17px] text-ink">
{r.name}
{mine && <Text className="text-xs font-extrabold text-rain"> 내 지역</Text>}
</Text>
<Text numberOfLines={1} className="text-[12.5px] font-semibold text-ink2">
{r.reason}
{r.estimated && ' · 예상'}
</Text>
<View className="mt-[5px] h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
<LinearGradient colors={['#9be7c4', '#1f9d62']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${r.score}%` }} />
</View>
</View>
<View className="flex-row items-center gap-1">
<Ic name={r.icon} size={24} />
<Text className="font-jua text-base text-ink">{r.score}점</Text>
</View>
</View>
);
}
export function EventRow({ event: e, index }: { event: EventData; index: number }) {
const { night, bg } = useBg();
const live = e.status === 'live';
const rainy = e.fit?.includes('비');
return (
<View className={EVENT_CARD}>
<Thumb image={e.image} icon={e.icon} iconSize={56} className="h-[84px] w-[84px] rounded-2xl">
<LinearGradient colors={bg[cardBg(e.icon, index)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
{e.image && e.image_credit && <Credit text={e.image_credit} />}
</Thumb>
{/* 이름 두 줄·정보 한 줄·날씨 한 줄로 고정해 카드 높이가 데이터와 무관하게 같다 */}
<View className="min-w-0 flex-1">
<Text numberOfLines={2} className="h-[46px] font-jua text-[17px] leading-snug text-ink">
<Text className="text-[11px] font-extrabold" style={{ color: live ? (night ? '#4fd39a' : '#1f7a4f') : night ? '#ffab85' : '#c2471b', backgroundColor: live ? (night ? 'rgba(79,211,154,0.16)' : '#dff5ea') : night ? 'rgba(255,138,87,0.16)' : '#ffe8dc' }}>
{` ${e.status_label} `}
</Text>{' '}
{e.name}
</Text>
<Text numberOfLines={1} className="text-[12.5px] font-semibold text-ink2">
{dateRange(e.start_date, e.end_date)}
{e.place_name && (
<>
{' · '}
<MapLink place={e.place_name}>{e.place_name}</MapLink>
</>
)}
{!e.is_confirmed && ' · 일정 확인 필요'}
</Text>
<Text numberOfLines={1} className="mt-[5px] text-xs font-extrabold" style={{ color: rainy ? (night ? '#ff8db5' : '#d6457a') : night ? '#4fd39a' : '#1f9d62' }}>
{e.fit ?? ' '}
</Text>
</View>
</View>
);
}
-103
View File
@@ -1,103 +0,0 @@
import { View } from 'react-native';
import { Skel } from '@/components/ui';
const TEN = Array.from({ length: 10 }, (_, i) => i);
const THREE = [0, 1, 2];
export const DAY_W = 'w-[46px]';
export const PLACE_CARD = 'w-[178px] overflow-hidden rounded-[22px] border-b-[5px] border-shade bg-card';
export const EVENT_CARD = 'mx-3 mt-2.5 flex-row items-center gap-3 rounded-[22px] border-b-[5px] border-shade bg-card p-3';
export function DaysSkel() {
return (
<View className="flex-row gap-1 overflow-hidden px-3 pt-3">
{TEN.map((i) => (
<View key={i} className={`${DAY_W} items-center gap-1 rounded-[18px] border-b-4 border-shade bg-card pt-[9px] pb-2`}>
<Skel className="w-3" />
<View className="size-7 rounded-full bg-skel" />
<Skel className="w-6" />
<Skel className="w-5" />
</View>
))}
</View>
);
}
export function PickSkel() {
return (
<View className="mx-3 mt-3 flex-row items-center gap-3.5 rounded-3xl border-b-[5px] border-shade bg-card p-4">
<View className="size-16 rounded-full bg-skel" />
<View className="flex-1 gap-1.5">
<Skel className="h-4 w-32" />
<Skel className="w-4/5" />
<Skel className="mt-1 w-36" />
</View>
</View>
);
}
export function PlacesSkel() {
return (
<View className="flex-row gap-2.5 overflow-hidden px-4 pt-3 pb-1">
{THREE.map((i) => (
<View key={i} className={PLACE_CARD}>
<View className="h-[104px] bg-skel" />
<View className="gap-1.5 px-3 pt-2.5 pb-3">
<Skel className="w-16" />
<Skel className="h-4 w-24" />
<Skel className="w-full" />
<Skel className="w-20" />
</View>
</View>
))}
</View>
);
}
export function EventSkel() {
return (
<View className={EVENT_CARD}>
<View className="h-[84px] w-[84px] rounded-2xl bg-skel" />
<View className="flex-1 gap-1.5">
<Skel className="h-4 w-40" />
<Skel className="h-4 w-20" />
<Skel className="w-44" />
<Skel className="w-24" />
</View>
</View>
);
}
export function EventsSkel() {
return (
<>
{THREE.map((i) => (
<EventSkel key={i} />
))}
</>
);
}
export function RankSkel() {
return (
<View className="mx-3 mt-1.5">
{TEN.map((i) => (
<View key={i} className="flex-row items-center gap-2.5 border-b-[1.5px] border-line px-1 py-3">
<View className="w-[34px] items-center">
<Skel className="w-5" />
</View>
<View className="flex-1 gap-1.5">
<Skel className="h-4 w-24" />
<Skel className="w-40" />
<View className="h-1.5 rounded-full bg-skel" />
</View>
<View className="flex-row items-center gap-1">
<View className="size-6 rounded-full bg-skel" />
<Skel className="w-9" />
</View>
</View>
))}
</View>
);
}
-6
View File
@@ -40,9 +40,3 @@
}
}
}
@theme {
--font-jua: 'Jua_400Regular';
--font-bagel: 'BagelFatOne_400Regular';
--font-batang: 'GowunBatang_400Regular';
}
-20
View File
@@ -1,20 +0,0 @@
import { GA_NAME, type Events as SharedEvents } from '@nalssigak/shared/lib/analytics';
import type { SheetState } from '@/lib/sheet';
/** 이벤트 목록은 웹과 같이 쓴다 (shared/lib/analytics.ts, docs/이벤트_추적.md) */
type Events = SharedEvents<Exclude<SheetState, null>['type']>;
type Sender = (name: string, params: Record<string, unknown>) => void;
let sender: Sender | null = null;
/** GA4 로 실제로 보내는 함수를 단다. Firebase Analytics(google-services.json)를 붙이면 앱 시작 때 부른다. 그 전에는 보내지 않는다 */
export function setAnalyticsSender(next: Sender | null) {
sender = next;
}
export function track<E extends keyof Events>(event: E, params: Events[E]) {
if (__DEV__) return;
sender?.(GA_NAME[event], { ...params, platform: 'app' });
}
-15
View File
@@ -1,15 +0,0 @@
import { configureApi } from '@nalssigak/shared/api/setup';
import * as SecureStore from 'expo-secure-store';
import { API_URL } from '@/lib/site';
configureApi({
baseUrl: API_URL,
storage: {
getItem: (key) => SecureStore.getItem(key),
setItem: (key, value) => SecureStore.setItem(key, value),
removeItem: (key) => {
SecureStore.deleteItemAsync(key).catch((e: unknown) => console.warn('토큰 삭제 실패', key, e));
},
},
});
-46
View File
@@ -1,46 +0,0 @@
import { clearTokens, getAccessToken, subscribeAuth } from '@nalssigak/shared/api/auth';
import { meOptions, meQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { logout as logoutOnServer } from '@nalssigak/shared/api/client/sdk.gen';
import type { Me } from '@nalssigak/shared/api/client/types.gen';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { createContext, use, useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react';
/** mePending: 토큰은 있고 내 정보를 받는 중 (아바타 자리를 비워 두지 않으려고) */
export type AuthApi = { loggedIn: boolean; me: Me | null; mePending: boolean; logout: () => void };
const AuthContext = createContext<AuthApi | null>(null);
export function useAuth() {
const ctx = use(AuthContext);
if (!ctx) throw new Error('useAuth must be used inside AuthProvider');
return ctx;
}
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb());
/** 서버에서 이 계정의 토큰을 모두 무효로 만들고(실패해도) 기기 토큰을 지운다 */
const logout = () => {
void logoutOnServer({ throwOnError: false }).finally(clearTokens);
};
export function AuthProvider({ children }: { children: ReactNode }) {
const token = useSyncExternalStore(subscribe, getAccessToken);
const queryClient = useQueryClient();
const me = useQuery({ ...meOptions(), enabled: !!token });
// 로그인·로그아웃하면 좋아요 여부가 달라지니 받아 둔 데이터를 다시 받는다
// 로그아웃·탈퇴 땐 내 정보 캐시를 먼저 버린다. 남겨 두면 다시 받다가 401 이 나서 로그인 창이 뜬다
useEffect(
() =>
subscribeAuth((reason) => {
if (reason !== 'change') return;
if (!getAccessToken()) queryClient.removeQueries({ queryKey: meQueryKey() });
void queryClient.invalidateQueries();
}),
[queryClient],
);
const mePending = !!token && me.isPending;
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, mePending, logout }), [token, me.data, mePending]);
return <AuthContext value={api}>{children}</AuthContext>;
}
-28
View File
@@ -1,28 +0,0 @@
// 웹 b.css 의 카드 배경(.b-bg-*)·가로 띠(.b-band-*) 그라데이션. 밤은 어두운 판
type Stops = readonly [string, string, ...string[]];
export const CARD_BG: Record<'day' | 'night', Record<string, Stops>> = {
day: {
sky: ['#bfe3ff', '#eef7ff'],
butter: ['#ffe7a0', '#fff6d8'],
peach: ['#ffd2bb', '#fff2ea'],
mint: ['#bfecd6', '#effaf4'],
lilac: ['#d8cffc', '#f4f1ff'],
dusk: ['#7e6fe6', '#f08aa2', '#ffc28a'],
night: ['#1f2658', '#3d3f86'],
},
night: {
sky: ['#2a4384', '#1f2c62'],
butter: ['#4d4128', '#2c2a3e'],
peach: ['#553632', '#2e2840'],
mint: ['#1f4a45', '#1d2d4a'],
lilac: ['#3d3480', '#262a5e'],
dusk: ['#7e6fe6', '#f08aa2', '#ffc28a'],
night: ['#1f2658', '#3d3f86'],
},
};
export const BAND_BG: Record<'day' | 'night', Record<1 | 2 | 3, Stops>> = {
day: { 1: ['#fff4ec', '#f7fbff'], 2: ['#fff6d8', '#f7fbff'], 3: ['#e9fbf2', '#f7fbff'] },
night: { 1: ['rgba(255,160,110,0.12)', 'rgba(255,255,255,0)'], 2: ['rgba(255,214,110,0.12)', 'rgba(255,255,255,0)'], 3: ['rgba(110,230,180,0.12)', 'rgba(255,255,255,0)'] },
};
-13
View File
@@ -1,13 +0,0 @@
import { foliageOn, foliageToday } from '@nalssigak/shared/lib/foliage';
import { useMemo, useState } from 'react';
export { foliageInSeason } from '@nalssigak/shared/lib/foliage';
/** 단풍 지도 그림 (웹 public/foliage/korea-map.webp 를 그대로 묶는다, 정사각형) */
export const MAP_IMAGE: number = require('../../../frontend/public/foliage/korea-map.webp');
/** 오늘(한국 시각) 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false (웹 useFoliage) */
export function useFoliage() {
const [today] = useState(() => foliageToday());
return useMemo(() => foliageOn(today), [today]);
}
-155
View File
@@ -1,155 +0,0 @@
// frontend/public 의 아이콘을 그대로 쓴다 (공용 public/icons, 웹 전용 public/b/icons). Metro 는 정적 require 만 묶을 수 있어 이름마다 적는다
export const ICONS: Record<string, number> = {
apple: require('../../../frontend/public/icons/apple.png'),
baseball: require('../../../frontend/public/icons/baseball.png'),
bear: require('../../../frontend/public/icons/bear.png'),
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'),
carwash: require('../../../frontend/public/icons/carwash.png'),
chestnut: require('../../../frontend/public/icons/chestnut.png'),
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'),
jjamppong: require('../../../frontend/public/icons/jjamppong.png'),
kimchi: require('../../../frontend/public/icons/kimchi.png'),
kite: require('../../../frontend/public/icons/kite.png'),
laundry: require('../../../frontend/public/icons/laundry.png'),
letter: require('../../../frontend/public/icons/letter.png'),
makeup: require('../../../frontend/public/icons/makeup.png'),
makgeolli: require('../../../frontend/public/icons/makgeolli.png'),
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'),
rabbit: require('../../../frontend/public/icons/rabbit.png'),
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: 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'),
newyear_bell: require('../../../frontend/public/b/icons/newyear_bell.png'),
newyear_popper: require('../../../frontend/public/b/icons/newyear_popper.png'),
newyear_pouch: require('../../../frontend/public/b/icons/newyear_pouch.png'),
newyear_sunset: require('../../../frontend/public/b/icons/newyear_sunset.png'),
newyear_tteokguk: require('../../../frontend/public/b/icons/newyear_tteokguk.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'),
suneung_bouquet: require('../../../frontend/public/b/icons/suneung_bouquet.png'),
suneung_eraser: require('../../../frontend/public/b/icons/suneung_eraser.png'),
suneung_heatpack: require('../../../frontend/public/b/icons/suneung_heatpack.png'),
suneung_lunchbox: require('../../../frontend/public/b/icons/suneung_lunchbox.png'),
suneung_mochi: require('../../../frontend/public/b/icons/suneung_mochi.png'),
suneung_pencil: require('../../../frontend/public/b/icons/suneung_pencil.png'),
suneung_ticket: require('../../../frontend/public/b/icons/suneung_ticket.png'),
suneung_yeot: require('../../../frontend/public/b/icons/suneung_yeot.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'),
};
-95
View File
@@ -1,95 +0,0 @@
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({});
};
}
-159
View File
@@ -1,159 +0,0 @@
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 };
}
-43
View File
@@ -1,43 +0,0 @@
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen';
import type { PinnedKey } from '@nalssigak/shared/lib/analytics';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { track } from '@/lib/analytics';
/** 히어로·오늘의 각처럼 포스트 틀이 아닌 카드의 좋아요 (웹 pinnedLike.ts). 로그인 없이 된다. 화면을 먼저 바꾸고 실패하면 되돌린다 */
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
const queryClient = useQueryClient();
const like = useMutation(likePostMutation());
const unlike = useMutation(unlikePostMutation());
const [failed, setFailed] = useState(false);
const liked = !!r?.liked;
const count = r?.like_count ?? 0;
const patch = (values: Partial<PostReaction>) =>
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed,
);
const toggle = () => {
if (!r || like.isPending || unlike.isPending) return;
const on = !liked;
setFailed(false);
patch({ liked: on, like_count: count + (on ? 1 : -1) });
const revert = () => {
patch({ liked, like_count: count });
setFailed(true);
};
(on ? like : unlike).mutate(
{ path: { post_id: r.post_id } },
{
onSuccess: (res) => {
if (!res.result?.success) return revert();
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) });
if (on) track('like', { content_type: key, item_id: r.post_id });
},
onError: revert,
},
);
};
return { liked, count, failed, toggle };
}
-18
View File
@@ -1,18 +0,0 @@
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분 넘게 묵은 데이터만 다시 받는다
if (Platform.OS !== 'web') {
focusManager.setEventListener((setFocused) => {
const sub = AppState.addEventListener('change', (state) => setFocused(state === 'active'));
return () => sub.remove();
});
}
// 웹과 같은 기본값: 다시 받는 동안 이전 결과를 그대로 두어 화면이 비지 않게 한다
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() }) }),
});
-98
View File
@@ -1,98 +0,0 @@
import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen';
import type { RegionData } from '@nalssigak/shared/api/client/types.gen';
import { DEFAULT_REGION } from '@nalssigak/shared/lib';
import * as Location from 'expo-location';
import * as SecureStore from 'expo-secure-store';
import { createContext, use, useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
import { track } from '@/lib/analytics';
const KEY = 'nalssigak.region';
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error';
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: (onFound?: () => void) => void; locateStatus: LocateStatus };
const RegionContext = createContext<RegionApi | null>(null);
export function useRegion() {
const ctx = use(RegionContext);
if (!ctx) throw new Error('useRegion must be used inside RegionProvider');
return ctx;
}
function readStored(): RegionData | null {
try {
const raw = SecureStore.getItem(KEY);
return raw ? (JSON.parse(raw) as RegionData) : null;
} catch (e) {
console.warn('저장한 지역을 읽지 못함', e);
return null;
}
}
/** 위치를 못 잡으면(실내·에뮬레이터) 끝없이 기다리지 않게 웹처럼 10초에 끊는다 */
function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
return Promise.race([p, new Promise<never>((_, reject) => setTimeout(() => reject(new Error('위치 찾기 시간 초과')), ms))]);
}
/** 위치 권한을 받아 가장 가까운 구. 권한이 없으면 'denied' */
async function findNearest(): Promise<RegionData | 'denied'> {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') return 'denied';
const pos = (await Location.getLastKnownPositionAsync({ maxAge: 600000 })) ?? (await withTimeout(Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced }), 10000));
const { data } = await nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } });
if (!data.region) throw new Error('가까운 구를 찾지 못함');
return data.region;
}
export function RegionProvider({ children }: { children: ReactNode }) {
const [stored] = useState(readStored);
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION);
// 처음 켠 사람은 위치로 가장 가까운 구를 찾는 동안 지역 칩을 스켈레톤으로
const [locateStatus, setLocateStatus] = useState<LocateStatus>(stored ? 'idle' : 'locating');
const setRegion = useCallback((r: RegionData) => {
setRegionState(r);
try {
SecureStore.setItem(KEY, JSON.stringify(r));
} catch (e) {
console.warn('지역을 저장하지 못함', e);
}
}, []);
const locate = useCallback(
(onFound?: () => void) => {
setLocateStatus('locating');
findNearest()
.then((r) => {
if (r === 'denied') return setLocateStatus('denied');
setLocateStatus('idle');
setRegion(r);
track('region_change', { region_name: r.name, method: 'location' });
onFound?.();
})
.catch((e: unknown) => {
console.warn('위치로 지역을 찾지 못함', e);
setLocateStatus('error');
});
},
[setRegion],
);
// 처음 켠 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다. 못 찾으면 조용히 기본 구
useEffect(() => {
if (stored) return;
findNearest()
.then((r) => {
if (r === 'denied') return;
setRegion(r);
track('region_change', { region_name: r.name, method: 'location' });
})
.catch((e: unknown) => console.warn('첫 위치로 지역을 찾지 못함', e))
.finally(() => setLocateStatus('idle'));
}, [stored, setRegion]);
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus]);
return <RegionContext value={api}>{children}</RegionContext>;
}
-169
View File
@@ -1,169 +0,0 @@
import { getBirthQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { deleteBirth, getBirth, putBirth } from '@nalssigak/shared/api/client/sdk.gen';
import type { SajuSavedBirth } from '@nalssigak/shared/api/client/types.gen';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useSyncExternalStore } from 'react';
import { useAuth } from '@/lib/auth';
/** 날씨 사주에 쓰는 태어난 정보. 기기에 두고, 로그인했으면 계정에도 저장한다 (웹 sajuBirth.ts) */
export type Birth = { y: number; m: number; d: number; hour: number | null; minute: number | null; place: string; gender: 'M' | 'F' | null };
// SecureStore 키는 영문·숫자·._- 만 된다
const KEY = 'nalssigak.birth';
const SEEN_KEY = 'nalssigak.sajuSeen';
/** 태어난 곳: 시각을 그곳 경도로 맞춘다 (시·도청 경도) */
export const BIRTH_PLACES: [string, string, number][] = [
['seoul', '서울', 126.98],
['busan', '부산', 129.08],
['daegu', '대구', 128.6],
['incheon', '인천', 126.71],
['gwangju', '광주', 126.85],
['daejeon', '대전', 127.38],
['ulsan', '울산', 129.31],
['sejong', '세종', 127.29],
['gyeonggi', '경기', 127.01],
['gangwon', '강원', 127.73],
['chungbuk', '충북', 127.49],
['chungnam', '충남', 126.67],
['jeonbuk', '전북', 127.11],
['jeonnam', '전남', 126.46],
['gyeongbuk', '경북', 128.51],
['gyeongnam', '경남', 128.69],
['jeju', '제주', 126.5],
];
export const placeLon = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[2] ?? 127;
export const placeName = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[1] ?? key;
const pad = (n: number) => String(n).padStart(2, '0');
/** 사주 풀이·궁합 요청에 넣는 생년월일 */
export const toBody = (b: Birth) => ({
birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`,
birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined,
longitude: placeLon(b.place),
});
function readLocal(): Birth | null {
try {
const raw = SecureStore.getItem(KEY);
return raw ? (JSON.parse(raw) as Birth) : null;
} catch (e) {
console.warn('[saju] 기기에 저장한 생년월일을 읽지 못함', e);
return null;
}
}
// 사주 화면과 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
let birth: Birth | null | undefined;
const listeners = new Set<() => void>();
const subscribe = (cb: () => void) => {
listeners.add(cb);
return () => listeners.delete(cb);
};
const getBirthLocal = () => {
if (birth === undefined) birth = readLocal();
return birth;
};
export function setBirth(b: Birth | null) {
birth = b;
listeners.forEach((cb) => cb());
try {
if (b) SecureStore.setItem(KEY, JSON.stringify(b));
else void SecureStore.deleteItemAsync(KEY);
} catch (e) {
console.warn('[saju] 기기에 저장하지 못함', e);
}
}
export const useBirth = () => useSyncExternalStore(subscribe, getBirthLocal);
const toSaved = (b: Birth): SajuSavedBirth => ({
birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`,
birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined,
place: b.place,
gender: b.gender === 'M' ? 'male' : b.gender === 'F' ? 'female' : undefined,
});
const fromSaved = (s: SajuSavedBirth): Birth => {
const [y, m, d] = s.birth_date.split('-').map(Number);
const [hour, minute] = s.birth_time ? s.birth_time.split(':').map(Number) : [null, null];
return { y, m, d, hour, minute, place: s.place ?? 'seoul', gender: s.gender === 'male' ? 'M' : s.gender === 'female' ? 'F' : null };
};
/** 로그인했으면 계정의 생년월일을 기기로 가져온다. 계정엔 없고 기기에만 있으면 계정으로 올린다. 받는 중이면 true */
export function useAccountBirth() {
const { loggedIn } = useAuth();
const q = useQuery({ queryKey: getBirthQueryKey(), enabled: loggedIn, staleTime: Infinity, queryFn: async () => (await getBirth()).data });
useEffect(() => {
if (!loggedIn || !q.data?.result?.success) return;
if (q.data.birth) setBirth(fromSaved(q.data.birth));
else {
const local = getBirthLocal();
if (local) putBirth({ body: toSaved(local) }).catch((e) => console.warn('[saju] 계정에 올리지 못함', e));
}
}, [loggedIn, q.data]);
return loggedIn && q.isPending;
}
/** 생년월일 저장·지우기: 기기에 두고, 로그인했으면 계정에도 */
export function useSaveBirth() {
const { loggedIn } = useAuth();
const queryClient = useQueryClient();
return async (b: Birth | null) => {
setBirth(b);
if (!loggedIn) return;
try {
const { data } = b ? await putBirth({ body: toSaved(b) }) : await deleteBirth();
if (data.result?.success) queryClient.setQueryData(getBirthQueryKey(), data);
} catch (e) {
console.warn('[saju] 계정에 저장하지 못함', e);
}
};
}
/** 있는 날짜이고 1900-01-01 ~ 오늘 사이인지 */
export function validBirth(y: number, m: number, d: number) {
const at = new Date(Date.UTC(y, m - 1, d));
const ok = at.getUTCFullYear() === y && at.getUTCMonth() === m - 1 && at.getUTCDate() === d;
return ok && y >= 1900 && at.getTime() <= Date.now();
}
// 오늘 사주를 본 날 (오늘 아이콘 줄의 빨간 점)
let seen: string | null | undefined;
const seenListeners = new Set<() => void>();
const subscribeSeen = (cb: () => void) => {
seenListeners.add(cb);
return () => seenListeners.delete(cb);
};
const getSeen = () => {
if (seen === undefined) {
try {
seen = SecureStore.getItem(SEEN_KEY);
} catch (e) {
console.warn('[saju] 본 날을 읽지 못함', e);
// 저장소를 못 쓰면 점을 보이지 않는다
seen = new Date().toDateString();
}
}
return seen;
};
/** 오늘 아이콘 줄의 빨간 점: 오늘 날씨 사주를 이미 봤는지 (웹 SajuPage sajuSeenToday) */
export const sajuSeenToday = () => getSeen() === new Date().toDateString();
/** sajuSeenToday 를 화면에서 쓸 때: 사주를 보고 돌아오면 바로 점이 사라진다 */
export const useSajuSeenToday = () => useSyncExternalStore(subscribeSeen, getSeen) === new Date().toDateString();
export function markSajuSeen() {
seen = new Date().toDateString();
seenListeners.forEach((cb) => cb());
try {
SecureStore.setItem(SEEN_KEY, seen);
} catch (e) {
console.warn('[saju] 본 날을 저장하지 못함', e);
}
}
-35
View File
@@ -1,35 +0,0 @@
import * as Sharing from 'expo-sharing';
import type { RefObject } from 'react';
import { Share, type View } from 'react-native';
import { captureRef } from 'react-native-view-shot';
import { track } from '@/lib/analytics';
import { useShareReward } from '@/lib/level';
type ShareText = { title: string; message: string };
/** 보이는 화면 조각을 PNG로 찍어 공유. 이미지 공유가 안 되는 곳(웹 등)이면 글로 보낸다. 보냈으면 true */
async function shareView(ref: RefObject<View | null>, { 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 true;
}
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<View | null>, text: ShareText) => {
if (await shareView(ref, text)) reward();
};
}
-33
View File
@@ -1,33 +0,0 @@
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 };
type CommentsState = { type: 'comments'; draft?: string } & CommentTarget;
export type SheetState =
| { type: 'gak'; indexId: number }
| { type: 'article'; articleId: number }
| CommentsState
| { type: 'seasonWeek' }
| { type: 'login'; then?: CommentsState; why?: 'level' }
| { type: 'me' }
| { type: 'region' }
| { 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 };
export const SheetContext = createContext<SheetApi | null>(null);
export function useSheet() {
const ctx = use(SheetContext);
if (!ctx) throw new Error('useSheet must be used inside SheetProvider');
return ctx;
}
-39
View File
@@ -1,39 +0,0 @@
import { kindOfHour, kst, type TimeKind } from '@nalssigak/shared/lib';
import { createContext, use, useEffect, useMemo, useState, type ReactNode } from 'react';
import { Uniwind } from 'uniwind';
/** 화면 전체 하늘의 시간대. 히어로에서 고른 미리보기는 탭을 옮겨도 유지된다 */
export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void };
const SkyContext = createContext<SkyApi | null>(null);
/** 밤에만 어두운 테마 (기기 다크 모드와 상관없이 하늘 시간대를 따른다). 같으면 건드리지 않는다 */
function applyTheme(kind: TimeKind) {
const theme = kind === 'night' ? 'dark' : 'light';
if (Uniwind.currentTheme !== theme) Uniwind.setTheme(theme);
}
// 첫 화면을 그리기 전에 지금 시각의 테마로 맞춰, 그리는 도중에 테마가 바뀌지 않게 한다
const t0 = kst(new Date());
applyTheme(kindOfHour(t0.h, t0.mo, t0.mi));
export function useSky() {
const ctx = use(SkyContext);
if (!ctx) throw new Error('useSky must be used inside SkyProvider');
return ctx;
}
export function SkyProvider({ children }: { children: ReactNode }) {
const [preview, setPreview] = useState<TimeKind | null>(null);
const [serverKind, setServerKind] = useState<TimeKind | null>(null);
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 60000);
return () => clearInterval(id);
}, []);
const t = kst(now);
const kind = preview ?? serverKind ?? kindOfHour(t.h, t.mo, t.mi);
useEffect(() => applyTheme(kind), [kind]);
const api = useMemo(() => ({ kind, preview, setPreview, setServerKind }), [kind, preview]);
return <SkyContext value={api}>{children}</SkyContext>;
}
-75
View File
@@ -1,75 +0,0 @@
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen';
import { kst } from '@nalssigak/shared/lib';
import { HOLIDAYS, holidayOn } from '@nalssigak/shared/lib/holiday';
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useRegion } from '@/lib/region';
import { apiUri } from '@/lib/site';
// 글 주제와 이름 (웹 talkState.ts)
export const TOPICS = [
[TalkTopic.LOCAL, '동네 이야기'],
[TalkTopic.SKY, '하늘·노을'],
[TalkTopic.RAIN, '비·눈'],
[TalkTopic.FOLIAGE, '단풍·꽃'],
[TalkTopic.OUTFIT, '오늘 옷차림'],
...HOLIDAYS.map((h) => [h.topic, h.name] as const),
] as const;
export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기';
/** 지금 고를 수 있는 주제: 기념일 주제는 그 기간에만 */
export function openTopics() {
const on = holidayOn()?.topic;
return TOPICS.filter(([k]) => !HOLIDAYS.some((h) => h.topic === k) || k === on);
}
/** 주제별 글 페이지 목록 (topic 없으면 전체) */
export function useTopicTalks(topic?: TalkTopic) {
const { region } = useRegion();
const list = useInfiniteQuery({
...listTalksInfiniteOptions({ query: { region: region.code, ...(topic ? { topic } : {}) } }),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
});
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
refetch: list.refetch,
refetching: list.isRefetching,
};
}
/** 내가 쓴 글 (최신순) */
export function useMyTalks(enabled = true) {
const list = useInfiniteQuery({
...listMyTalksInfiniteOptions(),
enabled,
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
});
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
};
}
export function useRefreshTalks() {
const queryClient = useQueryClient();
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') });
}
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
function slotWord(iso: string) {
const h = kst(iso).h;
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤';
}
export const talkMeta = (t: TalkData) => [t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ');
/** 올린 사진은 API 서버 경로(/v1/talk/image/...) */
export const talkImage = (t: TalkData) => (t.image ? apiUri(t.image) : undefined);
+52 -535
View File
File diff suppressed because it is too large. Load diff