feat: 앱 내 각 — 오늘 피드 내 각 줄, 만들기 창(있는 각 불러오기·아이콘·조건·시간대·미리보기 점수), 상세 창(시간대·조건별 점수, 링크 공유·지우기), 로그인 전 기기에 하나 저장 후 로그인하면 계정으로, ?my= 받은 각 열기 (GA my_gak_save)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
f6884fe9c9
commit
5a88b08a44
6 files changed
+546
-4
No files matched your search
+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`, 화면에 반쯤 보일 때).
|
||||
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`).
|
||||
- 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다.
|
||||
|
||||
## GA4 설정
|
||||
|
||||
@@ -3,9 +3,11 @@ import { PostType } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { kst, loadOf } from '@nalssigak/shared/lib';
|
||||
import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Fragment, useRef, type ReactNode } from 'react';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { Fragment, useEffect, useRef, type ReactNode } from 'react';
|
||||
import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-native';
|
||||
|
||||
import { MyGakRow } from '@/components/my-gak/my-gak';
|
||||
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
|
||||
import { Composer, TalkPost } from '@/components/talk/talk';
|
||||
import { GakCard } from '@/components/today/gak-card';
|
||||
@@ -13,7 +15,9 @@ import { Hero } from '@/components/today/hero';
|
||||
import { SeasonBand } from '@/components/today/rails';
|
||||
import { StateBox } from '@/components/ui';
|
||||
import { track } from '@/lib/analytics';
|
||||
import { fromShare } from '@/lib/my-gak';
|
||||
import { useRegion } from '@/lib/region';
|
||||
import { useSheet } from '@/lib/sheet';
|
||||
import { useSky } from '@/lib/sky';
|
||||
import { useTopicTalks } from '@/lib/talk';
|
||||
|
||||
@@ -67,6 +71,16 @@ export default function TodayScreen() {
|
||||
const talkFrom = Math.floor(posts.length / TALK_EVERY);
|
||||
const eventNo = new Map(posts.filter((p) => p.post_type === PostType.EVENT).map((p, n) => [p.post_id, n + 1]));
|
||||
const seen = useSeen();
|
||||
const { open } = useSheet();
|
||||
const { my } = useLocalSearchParams<{ my?: string }>();
|
||||
|
||||
// 친구가 보낸 내 각 링크(?my=...)로 들어오면 내 동네 기준으로 보여 준다
|
||||
useEffect(() => {
|
||||
if (!my) return;
|
||||
router.setParams({ my: undefined });
|
||||
const g = fromShare(my);
|
||||
if (g) open({ type: 'mix', shared: g });
|
||||
}, [my, open]);
|
||||
const refresh = () => Promise.all([feed.refetch(), today.refetch(), talkList.refetch()]);
|
||||
|
||||
// 웹처럼 9번째 글 뒤에 계절 이야기 띠를 넣고, 글이 모자라면 맨 뒤에 붙인다
|
||||
@@ -86,6 +100,7 @@ export default function TodayScreen() {
|
||||
>
|
||||
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<Composer />
|
||||
<MyGakRow />
|
||||
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
|
||||
{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}시 기준` : '오늘 기준'} />
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { LinearGradient } from 'expo-linear-gradient';
|
||||
import { useRef, useState, type ReactNode } from 'react';
|
||||
import { Pressable, ScrollView, TextInput, View } from 'react-native';
|
||||
|
||||
import { Body, useSoft } from '@/components/sheets/parts';
|
||||
import { Text } from '@/components/text';
|
||||
import { Ic, Rail, Sec } from '@/components/ui';
|
||||
import { gakName, MY_GAK_ICON, shareUrl, SLOT_WORD, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from '@/lib/my-gak';
|
||||
import { useRegion } from '@/lib/region';
|
||||
import { useShare } from '@/lib/share-image';
|
||||
import { useSheet } from '@/lib/sheet';
|
||||
|
||||
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
|
||||
const v = s?.score;
|
||||
return <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>
|
||||
);
|
||||
}
|
||||
@@ -5,15 +5,16 @@ import { Text } from '@/components/text';
|
||||
import Animated, { Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withTiming } from 'react-native-reanimated';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
|
||||
import { MixSheet, MyGakSheet } from '@/components/my-gak/my-gak';
|
||||
import { track } from '@/lib/analytics';
|
||||
import { SheetContext, useSheet, type SheetState } from '@/lib/sheet';
|
||||
|
||||
import { ArticleSheet, SeasonWeekSheet } from './article';
|
||||
import { CommentsSheet } from './comments';
|
||||
import { GakSheet } from './gak';
|
||||
import { LevelSheet, LevelUpSheet } from './level';
|
||||
import { LoginSheet } from './login';
|
||||
import { MeSheet } from './me';
|
||||
import { LevelSheet, LevelUpSheet } from './level';
|
||||
import { RegionSheet } from './region';
|
||||
import { WeatherWhySheet } from './weather-why';
|
||||
|
||||
@@ -68,7 +69,7 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () =>
|
||||
const [articleTitle, setArticleTitle] = useState('');
|
||||
|
||||
const then = state?.type === 'login' ? state.then : undefined;
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type];
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : state.type === 'myGak' ? '내 각' : TITLES[state.type];
|
||||
|
||||
return (
|
||||
<Modal visible={next != null} transparent animationType="fade" onRequestClose={onClose} statusBarTranslucent>
|
||||
@@ -96,6 +97,8 @@ function SheetHost({ state: next, onClose }: { state: SheetState; 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>
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
|
||||
import { scoreMyGak } from '@nalssigak/shared/api/client/sdk.gen';
|
||||
import type { MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { useEffect, useSyncExternalStore } from 'react';
|
||||
|
||||
import { track } from '@/lib/analytics';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { useRegion } from '@/lib/region';
|
||||
import { useSheet } from '@/lib/sheet';
|
||||
import { SITE_URL } from '@/lib/site';
|
||||
|
||||
const KEY = 'nalssigak.myRule';
|
||||
|
||||
export type Slot = 'morning' | 'day' | 'evening' | 'night';
|
||||
export const SLOTS: [Slot, string][] = [
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['evening', '저녁'],
|
||||
['night', '밤'],
|
||||
];
|
||||
export const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>;
|
||||
|
||||
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) (웹 myGakState.ts) */
|
||||
export type MyGak = { id?: number; name: string; icon?: string | null; rule: MyGakRule };
|
||||
|
||||
/** 아이콘을 안 골랐을 때 */
|
||||
export const MY_GAK_ICON = 'rabbit';
|
||||
|
||||
function readLocal(): MyGak | null {
|
||||
try {
|
||||
const raw = SecureStore.getItem(KEY);
|
||||
return raw ? (JSON.parse(raw) as MyGak) : null;
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 기기에 저장한 각을 읽지 못함', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 창과 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
|
||||
let local: MyGak | null | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
const subscribe = (cb: () => void) => {
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
};
|
||||
const getLocal = () => {
|
||||
if (local === undefined) local = readLocal();
|
||||
return local;
|
||||
};
|
||||
|
||||
function setLocal(g: MyGak | null) {
|
||||
local = g;
|
||||
listeners.forEach((cb) => cb());
|
||||
try {
|
||||
if (g) SecureStore.setItem(KEY, JSON.stringify(g));
|
||||
else void SecureStore.deleteItemAsync(KEY);
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 기기에 저장하지 못함', e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
|
||||
export const gakName = (name: string) => {
|
||||
const n = name.trim().replace(/\s+/g, ' ');
|
||||
return n && !n.endsWith('각') ? `${n}각` : n;
|
||||
};
|
||||
|
||||
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 (웹과 같은 형식) */
|
||||
export function shareUrl(g: MyGak) {
|
||||
const json = JSON.stringify({ n: g.name, i: g.icon ?? undefined, r: g.rule });
|
||||
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)));
|
||||
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`;
|
||||
}
|
||||
|
||||
export function fromShare(code: string): MyGak | null {
|
||||
try {
|
||||
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'));
|
||||
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; i?: unknown; r?: unknown };
|
||||
const icon = typeof v.i === 'string' && /^[a-z_]{1,32}$/.test(v.i) ? v.i : null;
|
||||
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, icon, rule: v.r as MyGakRule } : null;
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 받은 링크를 읽지 못함', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
|
||||
export function useMyGakScores(rules: MyGakRule[]) {
|
||||
const { region } = useRegion();
|
||||
return useQuery({
|
||||
queryKey: ['myGakScore', region.code, rules],
|
||||
enabled: rules.length > 0,
|
||||
staleTime: 5 * 60_000,
|
||||
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
|
||||
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } });
|
||||
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score');
|
||||
return { nowSlot: data.now_slot as Slot | null | undefined, scores: data.scores ?? [] };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */
|
||||
export function usePresets() {
|
||||
return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] });
|
||||
}
|
||||
|
||||
export function useMyGak() {
|
||||
const { loggedIn } = useAuth();
|
||||
const { open } = useSheet();
|
||||
const queryClient = useQueryClient();
|
||||
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn });
|
||||
const saved = useSyncExternalStore(subscribe, getLocal);
|
||||
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() });
|
||||
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh });
|
||||
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh });
|
||||
|
||||
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
|
||||
const { mutate } = add;
|
||||
useEffect(() => {
|
||||
if (!loggedIn || !saved) return;
|
||||
mutate({ body: { name: saved.name, icon: saved.icon, rule: saved.rule } }, { onSuccess: () => setLocal(null) });
|
||||
}, [loggedIn, saved, mutate]);
|
||||
|
||||
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, icon: g.icon, rule: g.rule })) : saved ? [saved] : [];
|
||||
|
||||
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
|
||||
const create = (g: MyGak, onDone?: () => void) => {
|
||||
const item = { name: gakName(g.name), icon: g.icon, rule: g.rule };
|
||||
if (loggedIn) {
|
||||
add.mutate(
|
||||
{ body: item },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success) return;
|
||||
track('my_gak_save', { gak_name: item.name });
|
||||
onDone?.();
|
||||
},
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (saved) {
|
||||
open({ type: 'login' });
|
||||
return;
|
||||
}
|
||||
setLocal(item);
|
||||
track('my_gak_save', { gak_name: item.name });
|
||||
onDone?.();
|
||||
};
|
||||
|
||||
const remove = (g: MyGak) => {
|
||||
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } });
|
||||
setLocal(null);
|
||||
};
|
||||
|
||||
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false };
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createContext, use } from 'react';
|
||||
|
||||
import type { WeatherWhyPayload } from '@/components/sheets/weather-why';
|
||||
import type { MyGak } from '@/lib/my-gak';
|
||||
|
||||
/** 댓글이 달린 곳: 운영 포스트 또는 사람 글 */
|
||||
export type CommentTarget = { postId: number } | { talkId: number };
|
||||
@@ -17,6 +18,8 @@ export type SheetState =
|
||||
| { type: 'weatherWhy'; why: WeatherWhyPayload }
|
||||
| { type: 'level' }
|
||||
| { type: 'levelUp'; level: number }
|
||||
| { type: 'mix'; shared?: MyGak }
|
||||
| { type: 'myGak'; gak: MyGak }
|
||||
| null;
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void };
|
||||
|
||||
Reference in new issue
Block a user