From f71dd2cebbc166a49d700795ba9344be06fe9f81 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 14:45:56 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=95=B1=20=EB=82=98=EB=A8=B8=EC=A7=80?= =?UTF-8?q?=20=ED=99=94=EB=A9=B4=20=EC=9D=B4=EC=A0=84=20=E2=80=94=20?= =?UTF-8?q?=EA=B2=8C=EC=8B=9C=EB=AC=BC=20=EC=B9=B4=EB=93=9C=C2=B7=EC=8B=9C?= =?UTF-8?q?=ED=8A=B8=C2=B7=EA=B0=81/=EB=85=B8=EC=9D=84/=EC=A3=BC=EB=A7=90/?= =?UTF-8?q?=EA=B3=84=EC=A0=88=20=ED=83=AD=C2=B7=EC=9B=80=EC=A7=81=EC=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 게시물 카드 슬라이드 7종, 좋아요·댓글, 텍스트 공유 - 시트 7종(RN Modal), 위 막대 지역·계절·로그인/아바타 - 각·노을·주말·행사·계절·상식 탭, 당겨서 새로고침 - 히어로 해·구름·비·눈 움직임, 스켈레톤 깜빡임, 첫 로딩 덮개, 하늘색 전환 --- TODO.md | 13 +- mobile/src/app/_layout.tsx | 2 + mobile/src/app/gak.tsx | 65 +++++- mobile/src/app/index.tsx | 28 ++- mobile/src/app/season.tsx | 46 +++- mobile/src/app/sky.tsx | 82 ++++++- mobile/src/app/week.tsx | 135 +++++++++++- mobile/src/components/coming-soon.tsx | 11 - mobile/src/components/first-load.tsx | 71 +++++++ mobile/src/components/gak/grid.tsx | 51 +++++ mobile/src/components/gak/podium.tsx | 56 +++++ mobile/src/components/post/icons.tsx | 29 +++ mobile/src/components/post/pager.tsx | 29 +++ mobile/src/components/post/post-card.tsx | 226 ++++++++++++++++++++ mobile/src/components/post/slides.tsx | 247 ++++++++++++++++++++++ mobile/src/components/season/parts.tsx | 101 +++++++++ mobile/src/components/sheets/article.tsx | 79 +++++++ mobile/src/components/sheets/comments.tsx | 222 +++++++++++++++++++ mobile/src/components/sheets/gak.tsx | 219 +++++++++++++++++++ mobile/src/components/sheets/index.tsx | 72 ++++++- mobile/src/components/sheets/login.tsx | 82 +++++++ mobile/src/components/sheets/me.tsx | 128 +++++++++++ mobile/src/components/sheets/parts.tsx | 72 +++++++ mobile/src/components/sheets/region.tsx | 71 +++++++ mobile/src/components/sky-bg.tsx | 42 +++- mobile/src/components/sky/colors.ts | 16 ++ mobile/src/components/sky/parts.tsx | 189 +++++++++++++++++ mobile/src/components/sky/skyline.tsx | 34 +++ mobile/src/components/today/hero.tsx | 133 ++++++++++-- mobile/src/components/top-bar.tsx | 39 +++- mobile/src/components/ui.tsx | 19 +- mobile/src/components/week/sections.tsx | 149 +++++++++++++ mobile/src/components/week/skels.tsx | 103 +++++++++ 33 files changed, 2786 insertions(+), 75 deletions(-) delete mode 100644 mobile/src/components/coming-soon.tsx create mode 100644 mobile/src/components/first-load.tsx create mode 100644 mobile/src/components/gak/grid.tsx create mode 100644 mobile/src/components/gak/podium.tsx create mode 100644 mobile/src/components/post/icons.tsx create mode 100644 mobile/src/components/post/pager.tsx create mode 100644 mobile/src/components/post/post-card.tsx create mode 100644 mobile/src/components/post/slides.tsx create mode 100644 mobile/src/components/season/parts.tsx create mode 100644 mobile/src/components/sheets/article.tsx create mode 100644 mobile/src/components/sheets/comments.tsx create mode 100644 mobile/src/components/sheets/gak.tsx create mode 100644 mobile/src/components/sheets/login.tsx create mode 100644 mobile/src/components/sheets/me.tsx create mode 100644 mobile/src/components/sheets/parts.tsx create mode 100644 mobile/src/components/sheets/region.tsx create mode 100644 mobile/src/components/sky/colors.ts create mode 100644 mobile/src/components/sky/parts.tsx create mode 100644 mobile/src/components/sky/skyline.tsx create mode 100644 mobile/src/components/week/sections.tsx create mode 100644 mobile/src/components/week/skels.tsx diff --git a/TODO.md b/TODO.md index eada69b..0185530 100644 --- a/TODO.md +++ b/TODO.md @@ -168,11 +168,14 @@ | [x] | 앱 토큰 저장소 `expo-secure-store`로 `configureApi` 연결, API 주소는 `EXPO_PUBLIC_API_BASE_URL` | 웹은 localStorage | `mobile/src/lib/api.ts`, `mobile/.env.example` | | [ ] | 시뮬레이터·실기기에서 앱 띄워 API 호출·로그인 확인 (번들 빌드까지만 확인함) | | `mobile/` | | [x] | 3단계-1: 탭 5개 구조·위 막대·하늘 배경·밤 테마(Uniwind dark), Today 히어로·각 순위·행사/TOP5/계절 띠 | | `mobile/src/app/`, `mobile/src/components/` | -| [ ] | Today 게시물 카드(`Post.tsx` 459줄, 슬라이드 넘기기·좋아요) 옮기기 — 지금은 띠만 이어서 보임 | 3단계-1 범위 밖 | `frontend/src/b/Post.tsx` | -| [ ] | 시트(각 근거·지역 고르기·로그인·내 정보, `Sheets.tsx` 1045줄) → `@gorhom/bottom-sheet`. 지금 앱은 눌러도 반응 없음, 위 막대에 로그인 버튼 없음 | 3단계-1 범위 밖 | `frontend/src/b/Sheets.tsx` | -| [ ] | 지역: 위치로 찾기(`expo-location`)·고른 지역 저장 — 지금은 마포구 고정 | | `mobile/src/lib/region.tsx` | -| [ ] | 움직임: 해·구름 떨어지기/둥둥, 비·눈 줄기, 구름, 스켈레톤 깜빡임, 첫 로딩 덮개 (reanimated) | 3단계-1은 정지 화면만 | `frontend/src/b/b.css` | -| [ ] | 나머지 탭(각·노을·주말·행사·계절·상식) 옮기기 — 지금은 '옮기는 중' 안내 | | `frontend/src/b/*Page.tsx` | +| [x] | Today 게시물 카드(슬라이드 7종·넘기기·좋아요·댓글·텍스트 공유), 3·6·9번째 글 뒤 띠 | | `mobile/src/components/post/`, `mobile/src/app/index.tsx` | +| [x] | 시트 7종(각 근거·읽을거리·댓글·이번 주 특집·로그인/가입·내 정보·지역 고르기)을 RN `Modal`로, 위 막대 로그인/아바타 | 새 패키지 없이 | `mobile/src/components/sheets/`, `mobile/src/components/top-bar.tsx` | +| [x] | 고른 지역 저장 (SecureStore) | | `mobile/src/lib/region.tsx` | +| [ ] | **[결정 필요]** '지금 위치로 찾기' — `expo-location` 새 패키지 필요 | 웹은 처음 온 사람 위치로 구를 맞춤 | `mobile/src/lib/region.tsx`, `mobile/src/components/sheets/region.tsx` | +| [x] | 움직임: 해·구름 떨어지기/둥둥, 비·눈, 스켈레톤 깜빡임, 첫 로딩 덮개, 하늘색 서서히 바뀜, 밤 별 반짝임 ('동작 줄이기' 켜면 멈춤) | | `mobile/src/components/today/hero.tsx`, `first-load.tsx`, `sky-bg.tsx` | +| [x] | 나머지 탭(각·노을·주말·행사·계절·상식) 옮기기 | | `mobile/src/app/`, `mobile/src/components/{gak,sky,week,season}/` | +| [ ] | **[결정 필요]** 게시물·주말 일정을 이미지로 공유 — 지금은 텍스트만. `react-native-view-shot` + `expo-sharing` 새 패키지 필요 | 웹은 스토리 이미지 | `mobile/src/components/post/post-card.tsx`, `mobile/src/app/week.tsx` | +| [ ] | 웹과 다른 작은 것들: 좋아요 튀는 하트·토스트, 밤 별똥별, 단풍잎 떨어짐, 시 구절 고운바탕 글꼴, 실패·빈 안내가 스켈레톤 높이를 유지(웹 hold), 시트 배경이 판과 같이 올라옴 | 1차 이전에서 뺌 | `mobile/src/` | | [ ] | **[결정 필요]** `mobile/` 템플릿 부속물(`.claude`, `AGENTS.md`, `.vscode`, `LICENSE`, 예제 화면) 둘지 지울지 | create-expo-app 기본 템플릿 | `mobile/` | | [ ] | `frontend-dev` 개발 컨테이너 실제로 띄워 확인 (이미지 빌드만 확인, 5173이 사용 중이라 실행은 못 함) | 볼륨 경로 바뀜 | `compose.yaml` | | [ ] | 운영 서버가 git pull 뒤 루트 `package-lock.json`으로 빌드되는지 배포 때 확인 | 빌드 대상이 `./frontend` → `.` | `deploy.sh`, `compose.yaml` | diff --git a/mobile/src/app/_layout.tsx b/mobile/src/app/_layout.tsx index 6a9a347..12a5aa9 100644 --- a/mobile/src/app/_layout.tsx +++ b/mobile/src/app/_layout.tsx @@ -11,6 +11,7 @@ import { View } from 'react-native'; import '@/global.css'; import { SkyBg } from '@/components/sky-bg'; import { TabBar } from '@/components/tab-bar'; +import { FirstLoad } from '@/components/first-load'; import { SheetProvider } from '@/components/sheets'; import { TopBar } from '@/components/top-bar'; import { AuthProvider } from '@/lib/auth'; @@ -34,6 +35,7 @@ function Shell() { + ); } diff --git a/mobile/src/app/gak.tsx b/mobile/src/app/gak.tsx index 72e02f6..e1a4de6 100644 --- a/mobile/src/app/gak.tsx +++ b/mobile/src/app/gak.tsx @@ -1,5 +1,64 @@ -import { ComingSoon } from '@/components/coming-soon'; +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, Text, View } from 'react-native'; -export default function Screen() { - return ; +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> = { 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('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 ( + q.refetch()} />}> + + {top.length === 3 ? : load === 'loading' ? : q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." />} + + {load === 'loading' ? ( + + ) : !items.length ? ( + // 실패 안내·다시 시도는 위 받침대 자리에 한 번만 + + ) : ( + + )} + {howto && load !== 'loading' && ( + 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"> + + + 각 점수는 어떻게 매길까? + 기온·비·바람·습도·공기·시간대 6가지로 계산해요 + + + )} + + ); } diff --git a/mobile/src/app/index.tsx b/mobile/src/app/index.tsx index d5a356f..25ea026 100644 --- a/mobile/src/app/index.tsx +++ b/mobile/src/app/index.tsx @@ -2,8 +2,10 @@ import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/cl import { kst, loadOf } from '@nalssigak/shared/lib'; import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today'; import { useQuery } from '@tanstack/react-query'; +import { Fragment, type ReactNode } from 'react'; import { RefreshControl, ScrollView } from 'react-native'; +import { PostCard, PostCardSkel } from '@/components/post/post-card'; import { Hero } from '@/components/today/hero'; import { EventsBand, SeasonBand, Stories, StoriesSkel, TopBand } from '@/components/today/rails'; import { Sec, StateBox } from '@/components/ui'; @@ -16,6 +18,7 @@ export default function TodayScreen() { const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } })); const { preview } = useSky(); const f = feed.data; + const posts = f?.posts ?? []; const stories = atSlot(f?.stories ?? [], preview); const sloted = preview != null && stories !== f?.stories; const bands = f?.bands; @@ -23,14 +26,33 @@ export default function TodayScreen() { const load = loadOf(feed); const refresh = () => Promise.all([feed.refetch(), today.refetch()]); + // 웹처럼 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다 + const bandAt: [number, ReactNode][] = [ + [3, bands?.events?.length ? : null], + [6, bands?.top5?.length ? g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null], + [9, bands?.season?.length ? : null], + ]; + return ( + // 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다 } style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}> {stories.length ? : load === 'loading' ? : feed.refetch()} empty="오늘 계산된 각이 없어요." />} - {!!bands?.events?.length && } - {!!bands?.top5?.length && g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />} - {!!bands?.season?.length && } + {load === 'loading' && ( + <> + + + + )} + {load !== 'loading' && !posts.length && feed.refetch()} empty="오늘 올라온 글이 아직 없어요." />} + {posts.map((p, i) => ( + + + {bandAt.find(([at]) => at === i + 1)?.[1]} + + ))} + {feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => {node})} ); } diff --git a/mobile/src/app/season.tsx b/mobile/src/app/season.tsx index f5630c6..fd272fc 100644 --- a/mobile/src/app/season.tsx +++ b/mobile/src/app/season.tsx @@ -1,5 +1,45 @@ -import { ComingSoon } from '@/components/coming-soon'; +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'; -export default function Screen() { - return ; +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 ( + }> + {w?.headline ? open({ type: 'seasonWeek' })} /> : weekLoad === 'loading' ? : week.refetch()} empty="이번 주 특집이 아직 없어요." />} + + + {artLoad === 'loading' && } + {artLoad !== 'loading' && !list.length && arts.refetch()} empty="읽을거리가 아직 없어요." />} + {list.map((a) => ( + open({ type: 'article', articleId: a.article_id })} /> + ))} + + + ); } diff --git a/mobile/src/app/sky.tsx b/mobile/src/app/sky.tsx index a1e7c3b..c68e134 100644 --- a/mobile/src/app/sky.tsx +++ b/mobile/src/app/sky.tsx @@ -1,5 +1,81 @@ -import { ComingSoon } from '@/components/coming-soon'; +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'; -export default function Screen() { - return ; +import { DayTiles, Li, LiSkel, ScoreHelp, SkyHero, Timeline } from '@/components/sky/parts'; +import { Sec, StateBox } from '@/components/ui'; +import { useRegion } from '@/lib/region'; + +const THREE = [0, 1, 2]; +const RANK_SKELS = Array.from({ length: 8 }, (_, i) => i); + +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(); + // 타일을 누르면 그날, 아니면 다음에 오는 날 + 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 ( + } style={{ opacity: sky.isPlaceholderData ? 0.6 : 1 }}> + {plan || load === 'loading' ? ( + + ) : ( + + sky.refetch()} empty="오늘 노을 정보가 없어요." /> + + )} + {plans.length > 1 && } + {plan && } + + {plan?.timeline?.length || load === 'loading' ? : } + {!rise && } + {rise ? null : spots.length ? ( + + {spots.map((p, i) => ( +
  • + ))} + {/* 3곳이 안 되면 빈 줄로 높이를 지켜 아래 순위가 밀리지 않게 */} + {THREE.slice(spots.length).map((i) => ( + + ))} + + ) : load === 'loading' ? ( + + {THREE.map((i) => ( + + ))} + + ) : ( + // 실패 안내·다시 시도는 위 히어로에 한 번만 + + )} + + {items.length ? ( + + {items.map((r, i) => ( +
  • + ))} + + ) : rankLoad === 'loading' ? ( + + {RANK_SKELS.map((i) => ( + + ))} + + ) : ( + ranking.refetch()} empty="순위가 아직 없어요." /> + )} + + ); } diff --git a/mobile/src/app/week.tsx b/mobile/src/app/week.tsx index 64de3b6..0c4fd18 100644 --- a/mobile/src/app/week.tsx +++ b/mobile/src/app/week.tsx @@ -1,5 +1,134 @@ -import { ComingSoon } from '@/components/coming-soon'; +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 { useState } from 'react'; +import { Pressable, RefreshControl, ScrollView, Share, Text, View } from 'react-native'; -export default function Screen() { - return ; +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 { 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(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(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 sendPlan = () => { + if (!sel) return; + const message = [`${sel.weekday}요일 일정 · ${region.name}`, sel.headline, sel.summary, sel.pick, `날씨각 ${SITE_URL}`].filter(Boolean).join('\n'); + Share.share({ message }).catch((e: unknown) => console.warn('일정 공유 실패', e)); + }; + + const placeSub = sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : sel.icon === 'sun' ? '맑아서 야외 명소를 먼저' : '비 소식이 없어 야외 명소를 먼저'} 보여 줘요` : weekLoad === 'loading' ? undefined : '날씨에 맞춰 골라 보여 줘요'; + + return ( + }> + + {days.length ? ( + + ) : weekLoad === 'loading' ? ( + <> + + + + ) : ( + week.refetch()} empty="날씨가 아직 없어요." /> + )} + {sel && } + {(sel || weekLoad !== 'ready') && ( + <> + 30km 안 · 데이트 명소 + [a, a] as const)} value={area} onChange={(a) => setAreaPick({ region: region.code, area: a })} disabled={!areas.length} /> + + )} + {/* 명소 데이터가 없으면 칸 전체를 숨긴다 */} + {!(placeLoad === 'ready' && !placeList.length) && ( + <> + + + + {!placeSub && } + {placeList.length ? ( + + + {placeList.map((p, i) => ( + + ))} + + + ) : placeLoad === 'loading' ? ( + + ) : ( + places.refetch()} empty={sel ? '30km 안에 데이트 명소가 아직 없어요.' : '날씨를 불러오면 명소를 골라 드려요.'} /> + )} + + )} + + {rankDays.length ? ( + [d.day, `${d.weekday}요일 ${shortDay(d.day)}`] as const)} value={rankDay?.day ?? ''} onChange={setRankPick} /> + ) : ( + undefined} disabled /> + )} + {rankItems.length ? ( + + {rankItems.map((r) => ( + + ))} + + ) : rankLoad === 'loading' ? ( + + ) : ( + ranking.refetch()} empty="주말 예보가 아직 없어요." /> + )} + + {eventList.length ? ( + + {eventList.map((e, i) => ( + + ))} + + ) : eventLoad === 'loading' ? ( + + ) : ( + events.refetch()} empty="30km 안에 열리는 행사가 아직 없어요. 다른 지역을 골라 보세요." /> + )} + {/* 행사 수가 정해진 뒤에 붙여 목록이 늘어날 때 밀리지 않게 */} + {eventLoad !== 'loading' && ( + + 이번 주말 일정 보내기 + + )} + + ); } diff --git a/mobile/src/components/coming-soon.tsx b/mobile/src/components/coming-soon.tsx deleted file mode 100644 index d0513ef..0000000 --- a/mobile/src/components/coming-soon.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { Text, View } from 'react-native'; - -/** 아직 옮기지 않은 탭 */ -export function ComingSoon({ title }: { title: string }) { - return ( - - {title} - 앱으로 옮기는 중이에요 - - ); -} diff --git a/mobile/src/components/first-load.tsx b/mobile/src/components/first-load.tsx new file mode 100644 index 0000000..8e81571 --- /dev/null +++ b/mobile/src/components/first-load.tsx @@ -0,0 +1,71 @@ +import type { TimeKind } from '@nalssigak/shared/lib'; +import { useIsFetching } from '@tanstack/react-query'; +import { useEffect, useState } from 'react'; +import { StyleSheet, Text, View } from 'react-native'; +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 = { + 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 ( + + + + ); +} + +/** 처음 들어올 때만: 첫 데이터를 다 받을 때까지 하늘 위에 캐릭터와 '날씨 불러오는 중…'. 한 번 사라지면 다시 안 뜬다 */ +export function FirstLoad() { + const fetching = useIsFetching(); + const { kind } = useSky(); + const [started, setStarted] = useState(false); + const [done, setDone] = useState(false); + const [gone, setGone] = useState(false); + // 받기 시작했다가 받는 게 없어지면 끝 (렌더 중에 바로 맞춘다) + if (fetching > 0 && !started) setStarted(true); + if (fetching === 0 && started && !done) setDone(true); + // 느린 망에서도 10초 넘게 막지 않는다 (그 뒤는 화면 안 스켈레톤이 맡는다) + useEffect(() => { + const id = setTimeout(() => setDone(true), 10000); + return () => clearTimeout(id); + }, []); + 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 ( + + + + 날씨 불러오는 중… + + + ); +} diff --git a/mobile/src/components/gak/grid.tsx b/mobile/src/components/gak/grid.tsx new file mode 100644 index 0000000..1dfe9ee --- /dev/null +++ b/mobile/src/components/gak/grid.tsx @@ -0,0 +1,51 @@ +import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen'; +import { Pressable, Text, View } from 'react-native'; + +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 ( + + {SKELS.map((i) => ( + + + + + + ))} + + ); +} + +/** 3칸 바둑판. 지금 시간대가 아니거나 제철이 아닌 각은 흐리게 */ +export function GakGrid({ items, dim }: { items: IndexSummary[]; dim: boolean }) { + const { open } = useSheet(); + return ( + + {items.map((g) => ( + 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 && {g.rank}} + {g.season && {g.season}} + + + {g.name} + + {g.active ? ( + {g.score} + ) : ( + {g.in_season === false ? '제철 아님' : '지금 아님'} + )} + + ))} + + ); +} diff --git a/mobile/src/components/gak/podium.tsx b/mobile/src/components/gak/podium.tsx new file mode 100644 index 0000000..6ade3d9 --- /dev/null +++ b/mobile/src/components/gak/podium.tsx @@ -0,0 +1,56 @@ +import type { IndexSummary } from '@nalssigak/shared/api/client/types.gen'; +import { MEDALS } from '@nalssigak/shared/lib'; +import { LinearGradient } from 'expo-linear-gradient'; +import { Pressable, Text, View } from 'react-native'; + +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 ( + + {ORDER.map((k) => ( + + + + + + + ))} + + ); +} + +export function Podium({ top, dim }: { top: IndexSummary[]; dim: boolean }) { + const { open } = useSheet(); + const { kind } = useSky(); + return ( + + {ORDER.map((k) => { + const g = top[k]; + return ( + 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' && } + + + + + + + {k + 1}위 {g.name} + + + {g.score} + {g.summary && {g.summary}} + + ); + })} + + ); +} diff --git a/mobile/src/components/post/icons.tsx b/mobile/src/components/post/icons.tsx new file mode 100644 index 0000000..e651879 --- /dev/null +++ b/mobile/src/components/post/icons.tsx @@ -0,0 +1,29 @@ +import Svg, { 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 ( + + + + ); +} + +export function CommentIcon({ size, color }: P) { + return ( + + + + ); +} + +export function SendIcon({ size, color }: P) { + return ( + + + + ); +} diff --git a/mobile/src/components/post/pager.tsx b/mobile/src/components/post/pager.tsx new file mode 100644 index 0000000..a552665 --- /dev/null +++ b/mobile/src/components/post/pager.tsx @@ -0,0 +1,29 @@ +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) => onIndex(Math.round(e.nativeEvent.contentOffset.x / width)); + return ( + 1} onMomentumScrollEnd={onEnd} style={{ width, height }}> + {children.map((c, i) => ( + + {c} + + ))} + + ); +} + +/** 슬라이드 위치 점 */ +export function Dots({ n, index }: { n: number; index: number }) { + if (n < 2) return null; + const items = Array.from({ length: n }, (_, i) => i); + return ( + + {items.map((i) => ( + + ))} + + ); +} diff --git a/mobile/src/components/post/post-card.tsx b/mobile/src/components/post/post-card.tsx new file mode 100644 index 0000000..c942d68 --- /dev/null +++ b/mobile/src/components/post/post-card.tsx @@ -0,0 +1,226 @@ +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, Share, Text, View } from 'react-native'; +import Svg, { Path } from 'react-native-svg'; +import { useCSSVariable } from 'uniwind'; + +import { CommentIcon, HEART, HeartIcon, SendIcon } from '@/components/post/icons'; +import { Dots, Pager } from '@/components/post/pager'; +import { slideBg, SlideView } from '@/components/post/slides'; +import { Ic, Skel } from '@/components/ui'; +import { useAuth } from '@/lib/auth'; +import { useSheet } from '@/lib/sheet'; +import { SITE_URL } from '@/lib/site'; + +const ACCOUNTS: Record = { + [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'], +}; + +type PostProps = { post: PostData }; + +/** 받아 둔 피드 데이터에도 좋아요를 반영한다. 안 하면 다른 탭에 다녀왔을 때 예전 값으로 다시 그려진다 */ +function patchFeed(queryClient: QueryClient, postId: number, patch: Partial) { + queryClient.setQueriesData({ 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]; + return ( + + + + {account} + + {post.title} {post.caption} + + + + ); +} + +/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */ +export function PostCard({ post }: PostProps) { + return post.size === 'line' ? : ; +} + +/** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */ +export function PostCardSkel() { + return ( + + + + + + + + + + + + + + + + + + + + + + ); +} + +/** 좋아요 때 가운데에 커졌다 사라지는 하트 */ +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 ( + + + + + + ); +} + +function FullCard({ post }: PostProps) { + const { open } = useSheet(); + const { loggedIn } = useAuth(); + 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]; + const n = post.slides.length; + const patch = (values: Partial) => patchFeed(queryClient, post.post_id, values); + const comments = () => open({ type: 'comments', postId: post.post_id }); + const share = () => { + Share.share({ message: `${post.title} · 날씨각 ${SITE_URL}` }).catch((e: unknown) => console.warn('공유 실패', e)); + }; + + useEffect(() => { + if (!likeFailed) return; + const t = setTimeout(() => setLikeFailed(0), 2500); + return () => clearTimeout(t); + }, [likeFailed]); + + // 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다) + const setLike = (on: boolean) => { + if (!loggedIn) return open({ type: 'login' }); + 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) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()), + onError: revert, + }, + ); + }; + + const onTap = () => { + const now = Date.now(); + if (now - lastTap.current < 320) { + if (liked && loggedIn) setPop((p) => p + 1); + else setLike(true); + } + lastTap.current = now; + }; + + return ( + + + + + + + + + + 날씨각 + {account} + + + setWidth(e.nativeEvent.layout.width)} className="aspect-[4/5] overflow-hidden" accessibilityLabel={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}> + {width > 0 && ( + + {post.slides.map((s, i) => ( + + ))} + + )} + {n > 1 && ( + + + {index + 1}/{n} + + + )} + {pop > 0 && } + {likeFailed > 0 && ( + + {liked ? '좋아요를 취소하지 못했어요' : '좋아요를 반영하지 못했어요'}. 다시 해 주세요. + + )} + + + + setLike(!liked)} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요"> + + + + + + + + + + 좋아요 {likeCount.toLocaleString()}개 + + 날씨각 + {post.caption} + + + {post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'} + + 오늘 + + ); +} diff --git a/mobile/src/components/post/slides.tsx b/mobile/src/components/post/slides.tsx new file mode 100644 index 0000000..98f7475 --- /dev/null +++ b/mobile/src/components/post/slides.tsx @@ -0,0 +1,247 @@ +import type { GakSlide, HoursSlide, 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 type { ReactNode } from 'react'; +import { Pressable, StyleSheet, Text, View } from 'react-native'; +import Svg, { Polygon } from 'react-native-svg'; + +import { Credit, Ic, Rows, Thumb } from '@/components/ui'; +import { CARD_BG } from '@/lib/colors'; +import { useSheet } from '@/lib/sheet'; +import { imageUri } from '@/lib/site'; +import { useSky } from '@/lib/sky'; + +export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide; + +type Stops = readonly [string, string, ...string[]]; + +const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac']; +const ROW_ICON_BG: Record = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac', glasses: 'butter' }; +const DARK = new Set(['dusk', 'night']); + +// 노을 하늘 상황(1 가려짐 2 낮은 구름 3 물들 구름 적음 4 넓게 물듦 5 두꺼움)별 하늘, 시간 칸 색 (웹 .b-sit-*, .b-cut-*) +const SIT_BG: Record = { + 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 = { + [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') 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) 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 ( + + + {children} + + ); +} + +function Eyebrow({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) { + return {children}; +} + +function Big({ children, light, className }: { children: ReactNode; light?: boolean; className?: string }) { + return {children}; +} + +function Pic({ name, widthPct = 42 }: { name: string; widthPct?: number }) { + return ( + + + + ); +} + +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 ( + + {slide.eyebrow} + {slide.line} + + {slide.hours.map((h) => { + const tone = HOUR_TONE[h.tone ?? '']; + return ( + + {h.temp_c != null && } + {h.label} + + {deg(h.temp_c)} + + ); + })} + + + ); + } + if (slide.kind === 'gak') + return ( + + 오늘의 각 · {slide.rank}위 + {slide.line} + + {slide.score} + {slide.name} + {slide.summary} + 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]"> + 계산 근거 보기 + + + ); + if (slide.kind === 'sunset') { + const sit = slide.situation ? SIT_BG[slide.situation] : undefined; + return ( + + {slide.eyebrow} + {/* 노을 탭 히어로와 같은 순서: 결론 → 가장 붉을 때 → 쉬운 이유 */} + {slide.headline ?? slide.grade_label} + {slide.line && {slide.line}} + + {slide.cuts.map((c, i) => ( + + + + + + + {clockShort(c.at)} + {c.label} + + + ))} + + + ); + } + if (slide.kind === 'week') + return ( + + {slide.eyebrow} + {slide.line} + {/* 칸은 제목 바로 아래, 팁만 맨 아래로 */} + + {slide.days.map((d) => ( + + + + {d.weekday} {d.day.split('-').slice(1).map(Number).join('.')} + + + {deg(d.temp_min_c)} → {deg(d.temp_max_c)} + + + 비 {d.rain_prob ?? '?'}%{d.temp_min_c != null && d.temp_max_c != null && ` · 일교차 ${Math.round(d.temp_max_c - d.temp_min_c)}°`} + + {d.gaks && d.gaks.length > 0 && ( + + 이날 할 만한 각 + {d.gaks.map((g) => ( + + + + {g.name} + + {g.score} + + ))} + + )} + + ))} + + {slide.tip && {slide.tip}} + + ); + if (slide.kind === 'plan') { + const credits = [...new Set(slide.steps.flatMap((st) => (st.image && st.image_credit ? [st.image_credit] : [])))]; + return ( + + {slide.eyebrow} + {slide.line} + + {slide.steps.map((st, i) => ( + + {st.time} + + + + {st.title} + + + {st.sub} + + + {st.image && } + + ))} + + {credits.length > 0 && 사진 {credits.join(' · ')}} + + ); + } + if (slide.kind === 'rows' && slide.image) + return ( + + + {slide.image_credit && } + + + {slide.eyebrow} + {slide.line} + + + + ); + return ( + + + {slide.eyebrow} + + + {slide.line} + + + + + ); +} diff --git a/mobile/src/components/season/parts.tsx b/mobile/src/components/season/parts.tsx new file mode 100644 index 0000000..69664b9 --- /dev/null +++ b/mobile/src/components/season/parts.tsx @@ -0,0 +1,101 @@ +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, Text, View } from 'react-native'; + +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 = { 1: ['#1f9d62', '#4fd39a'], 2: ['#7a5cd6', '#b9a6ff'], 3: ['#ff7a45', '#ff8a57'] }; + +/** 특집 상자와 같은 틀: 머리말 · 제목 두 줄 · 시 한 줄 · 절기 막대 */ +export function HeadSkel() { + return ( + + + + + + + + + ); +} + +export function RowsSkel() { + return ( + <> + {ROW_SKELS.map((i) => ( + + + + + + + + + ))} + + ); +} + +/** 이번 주 특집: 제목·시·절기 막대. 누르면 이번 주 절기 창 */ +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 ( + + + + 이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''} + {w.headline} + {poem.length > 0 && {poem.join('\n')}} + {w.term_now && w.term_next && ( + + + + {w.term_now.name} {shortDay(w.term_now.day)} + + + {w.term_next.name} {shortDay(w.term_next.day)} + + + + + + + )} + + ); +} + +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 ( + + + {ARTICLE_LABEL[a.category] && ( + + {ARTICLE_LABEL[a.category]} + + )} + {a.title} + {a.read_minutes}분 읽기 + + + + {a.image && a.image_credit && } + + + ); +} diff --git a/mobile/src/components/sheets/article.tsx b/mobile/src/components/sheets/article.tsx new file mode 100644 index 0000000..b0f960a --- /dev/null +++ b/mobile/src/components/sheets/article.tsx @@ -0,0 +1,79 @@ +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 } from 'react'; +import { Pressable, Text, View } from 'react-native'; + +import { Credit, Ic, StateBox, Thumb } from '@/components/ui'; +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 load = loadOf(q); + if (!a) return {load === 'loading' ? : q.refetch()} empty="글을 찾지 못했어요." />}; + return ( + + + + {a.image && a.image_credit && } + + {articleMeta(a)} + {a.title} + {(q.data?.body ?? []).map((t) => ( + + {t} + + ))} + + ); +} + +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 {load === 'loading' ? : q.refetch()} empty="이번 주 특집이 아직 없어요." />}; + return ( + + + + + + {w.start && w.end ? dateRange(w.start, w.end) : '이번 주'} + {w.headline} + {(w.poem_lines ?? []).length > 0 && ( + + + {w.poem_lines?.join(' ')} + + {w.author && {w.author}} + + )} + {w.term_now && w.term_next && ( + + 지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요. + + )} + {(w.news ?? []).map((n) => ( + open({ type: 'article', articleId: n.article_id })} className="flex-row items-center gap-2.5 border-b-[1.5px] border-line py-2.5"> + + {n.title} + + ))} + + ); +} diff --git a/mobile/src/components/sheets/comments.tsx b/mobile/src/components/sheets/comments.tsx new file mode 100644 index 0000000..a5aa2c6 --- /dev/null +++ b/mobile/src/components/sheets/comments.tsx @@ -0,0 +1,222 @@ +import { + addCommentMutation, + deleteCommentMutation, + getFeedQueryKey, + likeCommentMutation, + listCommentsInfiniteOptions, + listCommentsInfiniteQueryKey, + unlikeCommentMutation, +} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import type { CommentData, 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 { useRef, useState } from 'react'; +import { Pressable, Text, TextInput, View } from 'react-native'; +import { useCSSVariable } from 'uniwind'; + +import { Avatar, Skel, StateBox } from '@/components/ui'; +import { useAuth } from '@/lib/auth'; +import { useRegion } from '@/lib/region'; +import { useSheet } from '@/lib/sheet'; + +import { Body, ErrorLine, Field, HeartIcon } from './parts'; + +const NOT_FOUND = 3001; // 서버 ErrorType.NOT_FOUND +const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']; +const N3 = [0, 1, 2]; + +function CommentsSkel() { + return ( + + {N3.map((i) => ( + + + + + + + + ))} + + ); +} + +function CommentRow({ c, postId }: { c: CommentData; postId: number }) { + const { region } = useRegion(); + const { loggedIn } = useAuth(); + const { open } = useSheet(); + 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 (!loggedIn) return open({ type: 'login' }); + 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); + return; + } + revert(); + // 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다 + if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) }); + 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 = listCommentsInfiniteQueryKey({ path: { post_id: postId } }); + await queryClient.cancelQueries({ queryKey: key }); + queryClient.setQueryData>(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 }); + queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) }); + }, + onError: () => setRemoveFailed(true), + }, + ); + }; + + return ( + + + + + {c.nickname} + {c.body} + + + {ago(c.created_at)} · {likeFailed ? 좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요 : `좋아요 ${count}개`} + {c.mine && ( + <> + {' · '} + + {remove.isPending ? '지우는 중…' : removeFailed ? '못 지웠어요 · 다시' : '지우기'} + + + )} + + + + + + + ); +} + +export function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) { + const { region } = useRegion(); + const { open } = useSheet(); + const { loggedIn, me } = useAuth(); + const queryClient = useQueryClient(); + const list = useInfiniteQuery({ + ...listCommentsInfiniteOptions({ path: { post_id: postId } }), + initialPageParam: { path: { post_id: postId } }, + getNextPageParam: (last) => last.next_cursor ?? undefined, + }); + const add = useMutation(addCommentMutation()); + const [addFailed, setAddFailed] = useState(false); + const [text, setText] = useState(draft ?? ''); + const inputRef = useRef(null); + const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []; + + const submit = () => { + if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } }); + const body = text.trim(); + if (!body || add.isPending) return; + setAddFailed(false); + add.mutate( + { path: { post_id: postId }, body: { body } }, + { + onSuccess: (res) => { + setAddFailed(!res.result?.success); + if (!res.result?.success) return; + setText(''); + queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) }); + queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) }); + }, + onError: () => setAddFailed(true), + }, + ); + }; + + return ( + <> + + {comments.length ? ( + <> + {/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */} + {comments.map((c) => ( + + ))} + {list.hasNextPage && ( + list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50"> + {list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'} + + )} + + ) : loadOf(list) === 'loading' ? ( + + ) : ( + list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." /> + )} + + + {EMOJIS.map((e) => ( + { + setText((t) => (t + e).slice(0, 60)); + inputRef.current?.focus(); + }} + > + {e} + + ))} + + + + + + + + {add.isPending ? '올리는 중…' : '게시'} + + + + ); +} diff --git a/mobile/src/components/sheets/gak.tsx b/mobile/src/components/sheets/gak.tsx new file mode 100644 index 0000000..576b801 --- /dev/null +++ b/mobile/src/components/sheets/gak.tsx @@ -0,0 +1,219 @@ +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 } from 'react'; +import { Text, View } from 'react-native'; +import Svg, { Circle, Line, Polygon, Text as SvgText, TSpan } from 'react-native-svg'; + +import { Ic, Skel, StateBox } from '@/components/ui'; +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 ( + + + {[0.25, 0.5, 0.75, 1].map((v) => ( + + ))} + {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) => ( + + ))} + {factors.map((f, i) => { + const lines = labelLines(f.label); + const [x, y] = pt(i, 1.24); + return ( + + {lines.map((line, k) => ( + + {line} + + ))} + + ); + })} + + + ); +} + +function GakSkel() { + const s = useSoft(); + return ( + + + + + + + + + + + + {N4.map((i) => ( + + + + + ))} + + + {N6.map((i) => ( + + + + + + ))} + + + ); +} + +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 load = loadOf(q); + if (!g) return {load === 'loading' ? : q.refetch()} empty="이 각의 계산 근거가 아직 없어요." />}; + const factors = d.factors ?? []; + const bands = d.bands ?? []; + const now = bands.find((b) => b.current); + return ( + + + + + {g.name} + {d.description && {d.description}} + + {g.score} + + {!g.active && 지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.} + {now && ( + + + {now.low}~{now.high}점{' '} + + {now.text} + + )} + {factors.length > 2 && } + {g.slots && g.slots.length > 0 && ( + + {SLOT_KEYS.map((k) => { + const sl = g.slots?.find((x) => x.slot === k); + const cur = g.active && g.slot === k; + return ( + + + {SLOT_NAMES[k]} + {cur && ' · 지금'} + + {sl ? sl.score : '–'} + + ); + })} + + )} + {g.trend && g.trend.length > 0 && ( + + {g.trend.map((t) => ( + + + {t.label} + + {t.score} + 예상 + + ))} + + )} + {bands.length > 0 && ( + + {bands.map((b) => ( + + + + {b.low}~{b.high} + + + {b.text} + + ))} + + )} + + {factors.map((f) => ( + + + {f.label} + + + + 비중 {f.weight}% + + {f.note} + + ))} + + + {d.zero_reason && ( + + 오늘 걸린 조건: {d.zero_reason} + + )} + {factors.length > 0 && ( + + 계산 방법: 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요 + + )} + {d.zero_rules && ( + + 점수 깎이는 조건: {d.zero_rules} + + )} + {d.limit && ( + + 반영 못 한 것: {d.limit} + + )} + + + ); +} diff --git a/mobile/src/components/sheets/index.tsx b/mobile/src/components/sheets/index.tsx index aadc333..8fb4a06 100644 --- a/mobile/src/components/sheets/index.tsx +++ b/mobile/src/components/sheets/index.tsx @@ -1,9 +1,71 @@ -import { useMemo, useState, type ReactNode } from 'react'; +import { subscribeAuth } from '@nalssigak/shared/api/auth'; +import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'; +import { KeyboardAvoidingView, Modal, Platform, Pressable, Text, View } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; -import { SheetContext, type SheetState } from '@/lib/sheet'; +import { SheetContext, useSheet, type SheetState } from '@/lib/sheet'; + +import { ArticleSheet, SeasonWeekSheet } from './article'; +import { CommentsSheet } from './comments'; +import { GakSheet } from './gak'; +import { LoginSheet } from './login'; +import { MeSheet } from './me'; +import { RegionSheet } from './region'; export function SheetProvider({ children }: { children: ReactNode }) { - const [, setState] = useState(null); - const api = useMemo(() => ({ open: (s: Exclude) => setState(s), close: () => setState(null) }), []); - return {children}; + const [state, setState] = useState(null); + const open = useCallback((s: Exclude) => 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 ( + + {children} + + + ); +} + +const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const; + +/** 아래에서 올라오는 창. 바깥을 누르거나 뒤로 가기(안드로이드)로 닫는다 */ +function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) { + 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 : TITLES[state.type]; + + return ( + + + + {state && ( + + + + + {title} + + + × + + + {state.type === 'gak' && } + {state.type === 'article' && } + {state.type === 'seasonWeek' && } + {state.type === 'comments' && } + {state.type === 'login' && open(then) : onClose} />} + {state.type === 'me' && } + {state.type === 'region' && } + + )} + + + ); } diff --git a/mobile/src/components/sheets/login.tsx b/mobile/src/components/sheets/login.tsx new file mode 100644 index 0000000..9d0ff85 --- /dev/null +++ b/mobile/src/components/sheets/login.tsx @@ -0,0 +1,82 @@ +import { setTokens } from '@nalssigak/shared/api/auth'; +import { loginMutation, signupMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'; +import { useMutation } from '@tanstack/react-query'; +import { useState } from 'react'; +import { Pressable, Text, View } from 'react-native'; + +import { useAuth } from '@/lib/auth'; + +import { MeSheet } from './me'; +import { Body, ErrorLine, Field, useSoft } from './parts'; + +const AUTH_ERRORS: Record = { + AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.', + AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.', + INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.', +}; + +const MODES = [ + ['login', '로그인'], + ['signup', '처음이에요'], +] as const; + +export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) { + const { me } = useAuth(); + const s = useSoft(); + const [mode, setMode] = useState<'login' | 'signup'>('login'); + const [loginId, setLoginId] = useState(''); + const [password, setPassword] = useState(''); + const [nickname, setNickname] = useState(''); + const [error, setError] = useState(''); + const login = useMutation(loginMutation()); + const signup = useMutation(signupMutation()); + const pending = login.isPending || signup.isPending; + + const done = (res: ResAuth) => { + if (!res.result?.success || !res.access_token) { + setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.'); + return; + } + setTokens(res.access_token, res.refresh_token ?? null); + onLoggedIn(); + }; + const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'); + + // 웹 폼의 required·minLength 를 그대로 앞에서 확인한다 + const submit = () => { + setError(''); + const id = loginId.trim(); + if (id.length < 4 || !password || (mode === 'signup' && (password.length < 8 || nickname.trim().length < 2))) { + setError(AUTH_ERRORS.INVALID_INPUT); + return; + } + if (mode === 'login') login.mutate({ body: { login_id: id, password } }, { onSuccess: done, onError: fail }); + else signup.mutate({ body: { login_id: id, password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail }); + }; + + if (me) return ; + + return ( + + 좋아요·댓글은 로그인한 뒤에 할 수 있어요. + + {MODES.map(([m, l]) => ( + setMode(m)} className={`flex-1 rounded-full py-2 ${mode === m ? 'bg-ink-btn' : ''}`}> + {l} + + ))} + + + + {mode === 'signup' && } + + + {mode === 'login' ? (pending ? '로그인 중…' : '로그인') : pending ? '가입하는 중…' : '가입하고 시작하기'} + + + 나중에 할게요 + + + ); +} diff --git a/mobile/src/components/sheets/me.tsx b/mobile/src/components/sheets/me.tsx new file mode 100644 index 0000000..e078a9a --- /dev/null +++ b/mobile/src/components/sheets/me.tsx @@ -0,0 +1,128 @@ +import { meQueryKey, updateMeMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import { AVATAR_COLORS, CHARACTERS, MOODS } from '@nalssigak/shared/lib'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { Pressable, Text, View } from 'react-native'; + +import { Avatar, Ic } from '@/components/ui'; +import { useAuth } from '@/lib/auth'; + +import { Body, Field, useSoft } from './parts'; + +/** 내 정보: 캐릭터·배경색·기분·닉네임·로그아웃 */ +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 ( + + + + {me.login_id}(으)로 로그인했어요 + + + 내 캐릭터 + + {CHARACTERS.map(([key, label]) => ( + 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 }} + > + + {label} + + ))} + + + + 배경색 + + {Object.entries(AVATAR_COLORS).map(([key, hex]) => ( + save({ color: key })} + className={`size-9 rounded-full border-[3px] ${color === key ? 'border-ink' : 'border-white'}`} + style={{ backgroundColor: hex }} + /> + ))} + + + + 오늘 기분 + + {MOODS.map(([key, emoji, label]) => ( + 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 }} + > + {emoji} + {label} + + ))} + + 한 번 더 누르면 지워져요 + + + + nick.length >= 2 && save({ nickname: nick })} /> + + 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"> + {saving?.nickname != null ? '저장 중…' : '바꾸기'} + + + {saving ? (saving.nickname == null ? '저장 중…' : '') : error} + { + logout(); + onDone(); + }} + className="rounded-[14px] p-[13px]" + style={{ backgroundColor: s.soft }} + > + 로그아웃 + + + ); +} diff --git a/mobile/src/components/sheets/parts.tsx b/mobile/src/components/sheets/parts.tsx new file mode 100644 index 0000000..f3e47f6 --- /dev/null +++ b/mobile/src/components/sheets/parts.tsx @@ -0,0 +1,72 @@ +import type { ReactNode, Ref } from 'react'; +import { ScrollView, Text, TextInput, View, type TextInputProps } from 'react-native'; +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 ( + + {children} + + ); +} + +/** 입력칸: 둥근 연한 판 */ +export function Field({ round = false, style, ...props }: TextInputProps & { round?: boolean; ref?: Ref }) { + const s = useSoft(); + return ( + + ); +} + +export function HeartIcon({ size, fill, stroke }: { size: number; fill: string; stroke: string }) { + return ( + + + + ); +} + +const N3 = [0, 1, 2]; + +/** 읽을거리·이번 주 특집: 그림 150px · 머리말 · 제목 · 본문 */ +export function ArticleSkel() { + return ( + + + + + {N3.map((k) => ( + + + + + ))} + + ); +} + +/** 빨간 안내 한 줄 (자리 높이는 그대로) */ +export function ErrorLine({ text, className }: { text?: string; className?: string }) { + return {text ?? ''}; +} diff --git a/mobile/src/components/sheets/region.tsx b/mobile/src/components/sheets/region.tsx new file mode 100644 index 0000000..e55ccf9 --- /dev/null +++ b/mobile/src/components/sheets/region.tsx @@ -0,0 +1,71 @@ +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, useState } from 'react'; +import { Pressable, Text, View } from 'react-native'; + +import { Skel, StateBox } from '@/components/ui'; +import { useAuth } from '@/lib/auth'; +import { useRegion } from '@/lib/region'; +import { useSheet } from '@/lib/sheet'; + +import { Body, Field } from './parts'; + +const N14 = Array.from({ length: 14 }, (_, i) => i); + +function RegionsSkel() { + return ( + + {N14.map((i) => ( + + + + ))} + + ); +} + +/** 지역 바꾸기: 구 이름으로 찾기 + 목록 */ +export function RegionSheet({ onDone }: { onDone: () => void }) { + const { region, setRegion } = useRegion(); + 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 ( + + + {listLoad === 'loading' && } + {listLoad !== 'loading' && !regions.length && list.refetch()} empty="찾는 구가 없어요." />} + + {regions.map((r) => { + const here = r.code === region.code; + return ( + { + setRegion(r); + onDone(); + }} + className="flex-row items-center justify-between border-b-[1.5px] border-line px-1 py-3" + > + {r.name} + {here && 지금 보는 곳} + + ); + })} + + + {me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'} + open({ type: 'login' })} hitSlop={8}> + {me ? '로그아웃' : '로그인'} + + + + ); +} diff --git a/mobile/src/components/sky-bg.tsx b/mobile/src/components/sky-bg.tsx index f8b923c..e9ec5f3 100644 --- a/mobile/src/components/sky-bg.tsx +++ b/mobile/src/components/sky-bg.tsx @@ -1,9 +1,13 @@ import type { TimeKind } from '@nalssigak/shared/lib'; import { LinearGradient } from 'expo-linear-gradient'; +import { useEffect } from 'react'; import { StyleSheet, View } from 'react-native'; +import Animated, { cancelAnimation, Easing, 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 = { morning: { colors: ['#ffe0c4', '#fff0e2', '#e4f2ff'], locations: [0, 0.38, 1] }, day: { colors: ['#cde7ff', '#e9f5ff', '#f7fbff'], locations: [0, 0.45, 1] }, @@ -11,16 +15,44 @@ const SKY: Record ({ left: `${(i * 41 + 7) % 100}%`, top: `${(i * 67 + 3) % 96}%`, size: 1 + (i % 3) * 0.8, opacity: 0.4 + ((i * 7) % 6) / 10 }) as const); +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 ( + + + + ); +} + +/** 밤 별: 제각각 주기로 반짝인다 */ +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 ; +} + +/** 화면 전체 하늘: 시간대별 색이 서서히 바뀌고, 밤에는 별이 반짝인다 */ export function SkyBg() { const { kind } = useSky(); + const reduce = useReducedMotion(); return ( - - {kind === 'night' && - STARS.map((s, i) => )} + {KINDS.map((k) => ( + + ))} + {kind === 'night' && STARS.map((s, i) => )} ); } diff --git a/mobile/src/components/sky/colors.ts b/mobile/src/components/sky/colors.ts new file mode 100644 index 0000000..909d523 --- /dev/null +++ b/mobile/src/components/sky/colors.ts @@ -0,0 +1,16 @@ +// 웹 b.css 노을 탭 그라데이션. 등급별 하늘색(히어로·3일 타일)과 시간표 막대 +type Grad = { colors: readonly [string, string, ...string[]]; locations?: readonly [number, number, ...number[]] }; + +export const GRADE_SKY: Record = { + 잿빛: { 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; diff --git a/mobile/src/components/sky/parts.tsx b/mobile/src/components/sky/parts.tsx new file mode 100644 index 0000000..61aad78 --- /dev/null +++ b/mobile/src/components/sky/parts.tsx @@ -0,0 +1,189 @@ +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, Text, View } from 'react-native'; +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 ( + + + + + {children ?? ( + + {plan ? ( + + {plan.title} + + ) : ( + + )} + {!plan ? ( + + ) : plan.situation_label ? ( + + {plan.situation_label} + + ) : null} + + )} + + ); +} + +/** 오늘·내일·모레를 그날 예상 하늘색 타일로. 누르면 그날로 */ +export function DayTiles({ plans, day, onPick }: { plans: SkyPlanData[]; day?: string; onPick: (day: string) => void }) { + const ink = String(useCSSVariable('--color-ink')); + return ( + + {plans.map((p) => { + const g = skyOf(p.grade_label).tile; + const on = p.day === day; + return ( + onPick(p.day)} className="flex-1 rounded-[18px] p-[2px]" style={{ borderWidth: 3, borderColor: on ? ink : 'transparent' }}> + + + {p.when} + {p.best_at ? clockShort(p.best_at) : '–'} + + {p.grade_label} {p.score} + + + + ); + })} + + ); +} + +function Toggle({ label, children, end }: { label: ReactNode; children: ReactNode; end?: boolean }) { + const [open, setOpen] = useState(false); + return ( + + setOpen(!open)} accessibilityState={{ expanded: open }} className={`flex-row items-center gap-1.5 ${end ? 'justify-between' : ''}`}> + {label} + + {open && children} + + ); +} + +const Q = ({ className = 'bg-card/80' }: { className?: string }) => ( + + ? + +); + +/** 노을 점수 뜻. 지금 하늘이 아니라 해 질(뜰) 무렵 예보라는 것도 */ +export function ScoreHelp({ plan }: { plan: SkyPlanData }) { + const sunAt = plan.timeline?.find((t) => t.kind === 'sun')?.at; + const rise = plan.kind === 'sunrise'; + return ( + + + 노을 점수 100점 만점 · 높을수록 붉어요 + + + } + > + + 80점 넘으면 붉게, 60점 넘으면 곱게, 40점 넘으면 은은하게 물들어요. + {sunAt && ` 해 ${rise ? '뜰' : '질'} 무렵(${new Date(sunAt).getHours()}시) 날씨 예보로 계산했고, 노을 피크 시각은 해 ${rise ? '뜨기 10~20분 전' : '지고 10~20분 뒤'}로 어림한 거라 실제와 다를 수 있어요.`} + + + + ); +} + +/** 언제 보면 좋을까: 왼쪽 세로 줄 색이 그 시각 하늘색, 노을 피크만 강조 */ +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 ( + + + + + {list.map((t, i) => { + const peak = t?.kind === 'peak'; + return ( + + + {t ? {t.end ? `${clockShort(t.at)}~${clockShort(t.end)}` : clockShort(t.at)} : } + + {t ? {t.label} : } + + ); + })} + + + {rows && ( + + + + 골든아워·블루아워가 뭐예요 + + } + > + + 골든아워 해가 {kind === 'sunrise' ? '뜬 뒤' : '지기 전'}, 햇빛이 금빛으로 물드는 시간{'\n'} + 블루아워 해가 {kind === 'sunrise' ? '뜨기 전' : '진 뒤'}, 하늘이 짙은 파랑으로 남는 시간 + + + + )} + + ); +} + +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 ( + + + + + + + + + + + ); +} + +/** 번호 · 이름(+설명) · 오른쪽 값 한 줄 */ +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 ( + + {no} + + + {place ? {title} : title} + {mine && 내 지역} + + + {sub || ' '} + + + {right} + + ); +} diff --git a/mobile/src/components/sky/skyline.tsx b/mobile/src/components/sky/skyline.tsx new file mode 100644 index 0000000..21eb8c7 --- /dev/null +++ b/mobile/src/components/sky/skyline.tsx @@ -0,0 +1,34 @@ +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 ( + + + + + + ); +} + +/** 건물 뒤로 지는 해 (.b-sit-sun) */ +export function SitSun({ size = 112, bottom = 24, opacity = 1 }: { size?: number; bottom?: number; opacity?: number }) { + return ( + + + + + + + + + + + + + ); +} diff --git a/mobile/src/components/today/hero.tsx b/mobile/src/components/today/hero.tsx index 2d9d641..532a1e5 100644 --- a/mobile/src/components/today/hero.tsx +++ b/mobile/src/components/today/hero.tsx @@ -1,9 +1,10 @@ import type { Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen'; import { kindOfHour, kst, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'; -import { KINDS, moonPath, PREVIEW, SLOT_KEY, WANING, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today'; +import { KINDS, moonPath, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today'; import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'; import { useEffect, useState, type ReactNode } from 'react'; -import { Pressable, Text, View } from 'react-native'; +import { Pressable, Text, View, type DimensionValue, type ViewStyle } from 'react-native'; +import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated'; import { LinearGradient } from 'expo-linear-gradient'; import Svg, { Defs, Path, RadialGradient, Rect, Stop } from 'react-native-svg'; @@ -28,6 +29,77 @@ const ORB: Record<'sun' | 'sunset' | 'night', { stops: [string, string, string, }; 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). 구름 수: 구름 많음 둘, 흐림·비·눈 셋 +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 = { 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-fall: b-drop 1.05초 뒤 b-float 무한). d·f 는 밀리초 */ +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 {children}; +} + +/** 둥근 구름: 몸통 위에 동그라미 둘을 겹친다 (웹 .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 ( + + + + + + ); +} + +/** 비 줄기·눈송이 하나: 위에서 아래로 계속 떨어진다. 동작 줄이기면 제자리에 멈춘다 */ +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 ; + return ( + + + + ); +} + function useNow(ms = 20000) { const [now, setNow] = useState(() => new Date()); useEffect(() => { @@ -80,6 +152,8 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) { const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null; const status = hero?.status ?? []; 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]'; @@ -87,31 +161,44 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) { {kind === 'night' && STARS.map((s, i) => )} + {(rain || snow) && ( + + {rain && DROPS.map((p, i) => )} + {snow && FLAKES.map((p, i) => )} + + )} {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 - - - - - - - - - - - - {/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */} - {moon && } - - - {failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`} - - - {heroVal(feedLoad, score, 'w-[84px] h-10')} - - + + + + + + + + + + + + + {/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */} + {moon && } + + + {failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`} + + + {heroVal(feedLoad, score, 'w-[84px] h-10')} + + + + {CLOUDS.slice(0, CLOUD_N[weather]).map((c) => ( + + + + ))} {bubble ? ( diff --git a/mobile/src/components/top-bar.tsx b/mobile/src/components/top-bar.tsx index 8ae5642..0c6056e 100644 --- a/mobile/src/components/top-bar.tsx +++ b/mobile/src/components/top-bar.tsx @@ -3,37 +3,59 @@ import { kst, seasonOf } from '@nalssigak/shared/lib'; import { useQuery } from '@tanstack/react-query'; import { usePathname } from 'expo-router'; import { useState } from 'react'; -import { Text, View } from 'react-native'; +import { Pressable, Text, View } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { useCSSVariable } from 'uniwind'; import { PinIcon } from '@/components/svg'; -import { Ic } from '@/components/ui'; +import { Avatar, Ic } from '@/components/ui'; +import { useAuth } from '@/lib/auth'; import { useRegion } from '@/lib/region'; +import { useSheet } from '@/lib/sheet'; import { useSky } from '@/lib/sky'; const TITLES: Record = { '/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 ( - + 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"> - + {name} {term && · {term}} - + + ); +} + +/** 오른쪽 끝: 내 정보(아바타) 또는 로그인 버튼 */ +function Account() { + const { open } = useSheet(); + const { me, mePending } = useAuth(); + if (mePending) return ; + if (me) + return ( + open({ type: 'me' })} accessibilityLabel={`내 정보, ${me.nickname}`} className="shrink-0 rounded-full" style={{ boxShadow: '0 6px 12px rgb(40 48 74 / 0.12)' }}> + + + ); + return ( + open({ type: 'login' })} className="shrink-0 rounded-full bg-ink-btn px-3 py-1.5"> + 로그인 + ); } export function TopBar() { const pathname = usePathname(); const { region } = useRegion(); + const { open } = useSheet(); const { kind } = useSky(); const { top } = useSafeAreaInsets(); const ink = String(useCSSVariable('--color-ink')); @@ -43,12 +65,13 @@ export function TopBar() { {title ? {title} : 날씨각} - + 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"> {region.name.split(' ').at(-1)} - + + ); diff --git a/mobile/src/components/ui.tsx b/mobile/src/components/ui.tsx index 86736fa..a049bc3 100644 --- a/mobile/src/components/ui.tsx +++ b/mobile/src/components/ui.tsx @@ -2,7 +2,8 @@ import { AVATAR_COLORS, moodEmoji, naverMap, type Load } from '@nalssigak/shared import { Image, type ImageStyle } from 'expo-image'; import { LinearGradient } from 'expo-linear-gradient'; import { Link, type Href } from 'expo-router'; -import { useState, type ReactNode } from 'react'; +import { useEffect, useState, type ReactNode } from 'react'; +import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated'; import { Linking, Pressable, ScrollView, Text, View, type StyleProp, type ViewStyle } from 'react-native'; import { ICONS } from '@/lib/icons'; @@ -38,9 +39,21 @@ export function Thumb({ image, icon, iconSize, className, style, children }: { i ); } -/** 불러오는 동안 자리만 잡는 막대 */ +/** 불러오는 동안 자리만 잡는 막대. 천천히 깜빡인다 (웹 animate-pulse, 동작 줄이기면 멈춤) */ export function Skel({ className }: { className?: string }) { - return ; + 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 ( + + + + ); } export function Sec({ title, sub, more }: { title: string; sub?: string; more?: Href }) { diff --git a/mobile/src/components/week/sections.tsx b/mobile/src/components/week/sections.tsx new file mode 100644 index 0000000..0569a04 --- /dev/null +++ b/mobile/src/components/week/sections.tsx @@ -0,0 +1,149 @@ +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, Text, View } from 'react-native'; + +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 = { 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 ( + + {days.map((d) => { + const on = d.day === selected; + const weekend = d.weekday === '토' || d.weekday === '일' || !!d.holiday; + return ( + 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'}`}> + + {d.weekday} + + + {d.temp_max_c != null ? `${Math.round(d.temp_max_c)}°` : ?} + + {d.holiday ? d.holiday.replace(/\(.*\)/, '') : `${Number(d.day.slice(8))}일`} + + + ); + })} + + ); +} + +/** 고른 날 추천 한 장 */ +export function PickCard({ day }: { day: DayData }) { + const { night, bg } = useBg(); + return ( + + + + + {day.headline} + {day.summary} + {day.pick} + + + ); +} + +export function PlaceCard({ place: p, index }: { place: PlaceData; index: number }) { + const { bg } = useBg(); + return ( + + + + {p.is_good && ( + + {p.is_outdoor ? '오늘 딱' : '비 와도 OK'} + + )} + {p.image && p.image_credit && } + + + + {p.area} · {p.distance_km}km · {p.is_outdoor ? '야외' : '실내'} + + + {p.name} + + + {p.reason} + {'\n'}추천 {p.best_time} + + + + ); +} + +export function RankRow({ item: r, mine }: { item: WeekRankItem; mine: boolean }) { + return ( + + {r.rank} + + + {r.name} + {mine && 내 지역} + + + {r.reason} + {r.estimated && ' · 예상'} + + + + + + + + {r.score}점 + + + ); +} + +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 ( + + + + {e.image && e.image_credit && } + + {/* 이름 두 줄·정보 한 줄·날씨 한 줄로 고정해 카드 높이가 데이터와 무관하게 같다 */} + + + + {` ${e.status_label} `} + {' '} + {e.name} + + + {dateRange(e.start_date, e.end_date)} + {e.place_name && ( + <> + {' · '} + {e.place_name} + + )} + {!e.is_confirmed && ' · 일정 확인 필요'} + + + {e.fit ?? ' '} + + + + ); +} diff --git a/mobile/src/components/week/skels.tsx b/mobile/src/components/week/skels.tsx new file mode 100644 index 0000000..709aea9 --- /dev/null +++ b/mobile/src/components/week/skels.tsx @@ -0,0 +1,103 @@ +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 ( + + {TEN.map((i) => ( + + + + + + + ))} + + ); +} + +export function PickSkel() { + return ( + + + + + + + + + ); +} + +export function PlacesSkel() { + return ( + + {THREE.map((i) => ( + + + + + + + + + + ))} + + ); +} + +export function EventSkel() { + return ( + + + + + + + + + + ); +} + +export function EventsSkel() { + return ( + <> + {THREE.map((i) => ( + + ))} + + ); +} + +export function RankSkel() { + return ( + + {TEN.map((i) => ( + + + + + + + + + + + + + + + ))} + + ); +}