feat: 앱 날씨 사주 — /saju 생년월일 입력(연·월·일 칩, 시각 −/+), 오늘 점수 링·할 일 카드, 사주 명식, 레벨로 열리는 이번 주·금전·연애·이달·올해, 궁합(Lv.5), 기기·계정 생년월일 저장, ?open= 으로 그 칸 (GA saju_input·saju_view)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
47526c1cef
commit
02ebcda0ea
10 files changed
+1073
-1
No files matched your search
+1
-1
@@ -78,7 +78,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
|
||||
|
||||
- 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다.
|
||||
- **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다.
|
||||
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음).
|
||||
- 앱에서 부르는 곳: `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`). 사주: `saju_input`(`components/saju/birth-form.tsx`), `saju_view`(`saju/reading.tsx`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음).
|
||||
- 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다.
|
||||
|
||||
## GA4 설정
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user