From e5cdfa2642a168a6baa000d0d90797b80ea4a084 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Wed, 4 Nov 2026 17:52:23 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=95=B1=20=EB=8B=A8=ED=92=8D=20?= =?UTF-8?q?=EC=A7=80=EB=8F=84=20=E2=80=94=20/foliage=20=EC=A7=80=EB=8F=84(?= =?UTF-8?q?=EB=91=90=20=EC=86=90=EA=B0=80=EB=9D=BD=20=ED=99=95=EB=8C=80?= =?UTF-8?q?=C2=B7=EC=9D=B4=EB=8F=99,=20=EB=88=8C=EB=9F=AC=20=EA=B0=80?= =?UTF-8?q?=EA=B9=8C=EC=9A=B4=20=EB=AA=85=EC=86=8C)=C2=B7=EB=8B=A8?= =?UTF-8?q?=EA=B3=84=EB=B3=84=20=EB=AA=85=EC=86=8C=20=EB=AA=A9=EB=A1=9D,?= =?UTF-8?q?=20=EB=8B=A8=ED=92=8D=EC=B2=A0=20=EC=98=A4=EB=8A=98=20=ED=94=BC?= =?UTF-8?q?=EB=93=9C=20=EB=A7=A8=20=EC=95=9E=20=EC=B9=B4=EB=93=9C(foliage?= =?UTF-8?q?=5Fpost=20=EC=A2=8B=EC=95=84=EC=9A=94=C2=B7=EB=8C=93=EA=B8=80)?= =?UTF-8?q?=EC=99=80=20=EC=95=84=EC=9D=B4=EC=BD=98.=20=EB=AA=85=EC=86=8C?= =?UTF-8?q?=20=EB=8D=B0=EC=9D=B4=ED=84=B0=C2=B7=EA=B3=84=EC=82=B0=EC=9D=84?= =?UTF-8?q?=20shared/lib/foliage.ts=20=EB=A1=9C=20(GA=20foliage=5Fopen?= =?UTF-8?q?=C2=B7foliage=5Fspot)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- docs/이벤트_추적.md | 2 +- frontend/src/b/foliage.ts | 184 +----------- mobile/src/app/(tabs)/index.tsx | 7 +- mobile/src/app/foliage.tsx | 85 ++++++ .../src/components/foliage/foliage-card.tsx | 153 ++++++++++ mobile/src/components/foliage/foliage-map.tsx | 272 ++++++++++++++++++ mobile/src/components/foliage/parts.tsx | 135 +++++++++ mobile/src/components/foliage/spot-list.tsx | 93 ++++++ mobile/src/lib/foliage.ts | 13 + shared/lib/foliage.ts | 201 +++++++++++++ shared/tsconfig.json | 1 + 11 files changed, 966 insertions(+), 180 deletions(-) create mode 100644 mobile/src/app/foliage.tsx create mode 100644 mobile/src/components/foliage/foliage-card.tsx create mode 100644 mobile/src/components/foliage/foliage-map.tsx create mode 100644 mobile/src/components/foliage/parts.tsx create mode 100644 mobile/src/components/foliage/spot-list.tsx create mode 100644 mobile/src/lib/foliage.ts create mode 100644 shared/lib/foliage.ts diff --git a/docs/이벤트_추적.md b/docs/이벤트_추적.md index d1a01b8..910ef17 100644 --- a/docs/이벤트_추적.md +++ b/docs/이벤트_추적.md @@ -78,7 +78,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화 - 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다. - **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다. -- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 오늘 아이콘 줄: `today_icon`(`components/today/icons.tsx`). 사주: `saju_input`(`components/saju/birth-form.tsx`), `saju_view`(`saju/reading.tsx`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음). +- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 오늘 아이콘 줄: `today_icon`(`components/today/icons.tsx`). 사주: `saju_input`(`components/saju/birth-form.tsx`), `saju_view`(`saju/reading.tsx`). 단풍 지도: `foliage_open`(`app/foliage.tsx`), `foliage_spot`(`components/foliage/*`, 화면 `page`·피드 카드 `card`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음). - 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다. ## GA4 설정 diff --git a/frontend/src/b/foliage.ts b/frontend/src/b/foliage.ts index d4da2af..4df5af9 100644 --- a/frontend/src/b/foliage.ts +++ b/frontend/src/b/foliage.ts @@ -1,187 +1,16 @@ import { useLayoutEffect, useMemo, useState, type RefObject } from 'react' -import data from '../../seo/foliage_2026.json' -import { kst } from '@nalssigak/shared/lib' +import { foliageOn, foliageToday, type Kind } from '@nalssigak/shared/lib/foliage' -export type Kind = 'maple' | 'ginkgo' -export type Stage = 'before' | 'first' | 'peak' | 'gone' -type Raw = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string } -/** x·y 는 지도 그림 안 위치(0~1), own 은 산림청 예측 지점 자기 날짜인지(아니면 가까운 지점에서 빌린 날짜) */ -export type Spot = Omit & { stage: Stage; d: number; x: number; y: number; own: boolean } +// 데이터·단계·배치 계산은 앱과 같이 쓴다 (shared/lib/foliage.ts). 여기는 웹 화면에 붙는 것만 +export { headline, ICON_R, KIND, LAND_CX, labelBoxes, md, placeLabels, placeProvinces, provinceBox, PROVINCES, rankNow, spread, STAGE } from '@nalssigak/shared/lib/foliage' +export type { Box, Kind, Pt, Spot, Stage } from '@nalssigak/shared/lib/foliage' -// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값 -const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 } export const MAP_SRC = '/foliage/korea-map.webp' -// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다 -const FIRST_DAYS = 14 -const PEAK_DAYS = 3 -const PEAK_AFTER = 7 - -export const STAGE: Record = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' } -export const KIND: Record = { maple: '단풍', ginkgo: '은행' } - -const DAY = 86_400_000 -const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY) - -function stage(peak: string, today: string): Stage { - const d = days(today, peak) - if (d < -PEAK_AFTER) return 'gone' - if (d <= PEAK_DAYS) return 'peak' - return d <= FIRST_DAYS ? 'first' : 'before' -} - -const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size }) -// 처음 화면 가로 가운데: 명소 가운데(127.9°)로 잡으면 서해 섬까지 든 땅이 왼쪽으로 쏠려 보여 서쪽으로 당김 -export const LAND_CX = toXY(36, 127.65).x - -// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림 -export const PROVINCES = ( - [ - ['서울', 37.56, 126.98], - ['경기', 37.95, 127.05], - ['강원', 37.65, 128.35], - ['충북', 36.8, 127.75], - ['충남', 36.45, 126.85], - ['전북', 35.72, 127.1], - ['전남', 34.85, 126.9], - ['경북', 36.3, 128.75], - ['경남', 35.3, 128.2], - ['제주', 33.38, 126.55], - ] as const -).map(([name, lat, lon]) => ({ name, ...toXY(lat, lon) })) - -export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}` -const province = (m: Spot) => m.region.split(' ')[0].split('·') /** 오늘(한국 시각) 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false */ export function useFoliage() { - const [today] = useState(() => { - const t = kst(new Date()) - return `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}` - }) - return useMemo(() => { - const spots: Spot[] = (data.spots as Raw[]).map(({ basis, lat, lon, ...m }) => ({ - ...m, - stage: stage(m.peak, today), - d: days(today, m.peak), - ...toXY(lat, lon), - own: basis.startsWith('산림청'), - })) - // 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지 - const peaks = spots.map((m) => m.peak).sort() - const inSeason = days(peaks[0], today) >= -FIRST_DAYS && days(peaks[peaks.length - 1], today) <= PEAK_AFTER - return { today, spots, inSeason } - }, [today]) -} - -/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */ -export function headline(spots: Spot[]) { - const peak = spots.filter((m) => m.stage === 'peak') - if (peak.length) { - const count = new Map() - for (const p of peak.flatMap(province)) count.set(p, (count.get(p) ?? 0) + 1) - return `지금 절정: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}` - } - if (spots.some((m) => m.stage === 'gone')) return '올해 단풍이 지고 있어요' - const first = spots.reduce((a, b) => (b.peak < a.peak ? b : a)) - return `첫 절정은 ${province(first)[0]}, ${md(first.peak)}쯤` -} - -/** 지금 가기 좋은 순: 절정인 곳 중 절정 예상일이 오늘과 가까운 순, 같으면 자기 예측 날짜 먼저, 그다음 이름 순 */ -export const rankNow = (spots: Spot[]) => - spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name)) - -/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */ -export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: Pt[], labels: Box[] = [], R = 90) { - // 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳) - const placed: Box[] = [] - const free = (x: number, y: number) => - pts.every((p) => Math.abs(p.x - x) > p.r + 17 || Math.abs(p.y - y) > p.r + 10) && [...labels, ...placed].every((b) => !overlaps(provinceBox(x, y), b)) - return provs.map((v) => { - const at = pick(v) - placed.push(provinceBox(at.x, at.y)) - return at - }) - function pick(v: { name: string; x: number; y: number }) { - if (free(v.x, v.y)) return v - for (let d = 5; d <= R; d += 5) - for (let a = 0; a < 24; a++) { - const x = v.x + Math.cos((a / 24) * 2 * Math.PI) * d - const y = v.y + Math.sin((a / 24) * 2 * Math.PI) * d - if (free(x, y)) return { ...v, x, y } - } - return v - } -} -export function provinceBox(x: number, y: number): Box { - return { l: x - 16, t: y - 9, r: x + 16, b: y + 9 } -} - -/** placeLabels 결과를 상자로: 시·도 이름이 피해 갈 자리 */ -export const labelBoxes = (at: Record, size: Record) => - Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) })) - -export type Pt = { m: Spot; x: number; y: number; r: number } -const LABEL_GAP = 4 -export type Box = { l: number; t: number; r: number; b: number } -const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b - -/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */ -export function spread(pts: Pt[], gap = 1.5) { - for (let it = 0; it < 60; it++) { - let moved = false - for (let i = 0; i < pts.length; i++) - for (let j = i + 1; j < pts.length; j++) { - const a = pts[i] - const b = pts[j] - let dx = b.x - a.x - let dy = b.y - a.y - let d = Math.hypot(dx, dy) - const need = a.r + b.r + gap - if (d >= need) continue - if (d < 0.01) [dx, dy, d] = [Math.cos(i + j), Math.sin(i + j), 1] - const push = (need - d) / 2 - a.x -= (dx / d) * push - a.y -= (dy / d) * push - b.x += (dx / d) * push - b.y += (dy / d) * push - moved = true - } - if (!moved) break - } - return pts -} - -/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */ -export function placeLabels(order: Pt[], all: Pt[], size: Record, area: Box, blocked: Box[] = [], vertical: (p: Pt) => boolean = () => false) { - const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } })) - const taken = [...blocked.map((box) => ({ name: '', box })), ...dots] - const out: Record = {} - for (const p of order) { - const s = size[p.m.name] - if (!s || p.x < area.l || p.x > area.r || p.y < area.t || p.y > area.b) continue - // 옆 자리가 없을 때 vertical 인 명소(절정)만 위·아래도 써 본다 - const tries = [ - [p.r + 2, -s.h / 2], - [-s.w - p.r - 2, -s.h / 2], - ...(vertical(p) ? [[-s.w / 2, -s.h - p.r - 1], [-s.w / 2, p.r + 1]] : []), - ] - for (const [dx, dy] of tries) { - const r = { l: p.x + dx, t: p.y + dy, r: p.x + dx + s.w, b: p.y + dy + s.h } - if (r.l < area.l || r.t < area.t || r.r > area.r || r.b > area.b) continue - // 이름표끼리는 LABEL_GAP 만큼 띄워 손가락으로 옆 이름을 잘못 누르지 않게 - const pad = { l: r.l - LABEL_GAP, t: r.t - LABEL_GAP, r: r.r + LABEL_GAP, b: r.b + LABEL_GAP } - if (taken.some((o) => o.name !== p.m.name && overlaps(o.name ? r : pad, o.box))) continue - // 위·아래 자리는 이름표에서 가장 가까운 표시가 자기 것일 때만: 아니면 다른 점의 이름처럼 읽힌다 - const cx = (r.l + r.r) / 2 - const cy = (r.t + r.b) / 2 - const mine = Math.hypot(cx - p.x, cy - p.y) - if (dy !== -s.h / 2 && all.some((q) => q.m.name !== p.m.name && Math.hypot(cx - q.x, cy - q.y) < mine)) continue - taken.push({ name: '', box: r }) - out[p.m.name] = { left: r.l, top: r.t } - break - } - } - return out + const [today] = useState(foliageToday) + return useMemo(() => foliageOn(today), [today]) } /** 이름표 크기를 재 둔다: host 안 data-label 이 붙은 요소의 폭·높이 (host 크기가 바뀌면 다시) */ @@ -209,7 +38,6 @@ export const LABEL = "b-keep-bg absolute rounded-[7px] before:absolute before:-i export const LABEL_INK: Record = { maple: 'bg-[#ffffffeb] text-[#b5321f]', ginkgo: 'bg-[#ffffffeb] text-[#8a6508]' } // 지도 그림 색을 빼서 단풍 아이콘이 묻히지 않게 export const MAP_IMG = 'pointer-events-none absolute inset-0 size-full select-none mix-blend-multiply brightness-[1.08] saturate-[.3]' -export const ICON_R = 10 // 시·도 이름: 지도에 옅게 깔리는 글자 // 어두운 산 무늬 위에서도 읽히게 종이색 테두리를 두른다 export const PROVINCE = 'pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 font-jua text-[13px] leading-none whitespace-nowrap text-[#5c4a36]/85 [text-shadow:0_0_2px_#fff6ea,0_0_4px_#fff6ea,0_0_6px_#fff6ea]' diff --git a/mobile/src/app/(tabs)/index.tsx b/mobile/src/app/(tabs)/index.tsx index e20b9ca..d03b294 100644 --- a/mobile/src/app/(tabs)/index.tsx +++ b/mobile/src/app/(tabs)/index.tsx @@ -7,6 +7,7 @@ import { router, useLocalSearchParams } from 'expo-router'; import { Fragment, useEffect, useRef, type ReactNode } from 'react'; import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-native'; +import { FoliageCard } from '@/components/foliage/foliage-card'; import { MyGakRow } from '@/components/my-gak/my-gak'; import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card'; import { ShortsRail } from '@/components/shorts/rail'; @@ -17,6 +18,7 @@ import { TodayIcons } from '@/components/today/icons'; import { SeasonBand } from '@/components/today/rails'; import { StateBox } from '@/components/ui'; import { track } from '@/lib/analytics'; +import { useFoliage } from '@/lib/foliage'; import { fromShare } from '@/lib/my-gak'; import { useRegion } from '@/lib/region'; import { useSheet } from '@/lib/sheet'; @@ -73,6 +75,7 @@ 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 { inSeason } = useFoliage(); const scroll = useRef(null); const myGakY = useRef(0); const { open } = useSheet(); @@ -104,7 +107,7 @@ export default function TodayScreen() { onScroll={(e) => seen.onScroll(e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height)} > - scroll.current?.scrollTo({ y: myGakY.current, animated: true })} /> + scroll.current?.scrollTo({ y: myGakY.current, animated: true })} /> {/* 아이콘 줄 '내 각'이 여기로 내려온다 */} @@ -139,6 +142,8 @@ export default function TodayScreen() { boxClassName="inset-x-3 top-3.5" /> )} + {/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */} + {load !== 'loading' && posts.length > 0 && } {posts.map((p, i) => { const t = talkAt(i); const ev = eventNo.get(p.post_id); diff --git a/mobile/src/app/foliage.tsx b/mobile/src/app/foliage.tsx new file mode 100644 index 0000000..9747e98 --- /dev/null +++ b/mobile/src/app/foliage.tsx @@ -0,0 +1,85 @@ +import { headline, md, type Kind, type Spot } from '@nalssigak/shared/lib/foliage'; +import { useLocalSearchParams } from 'expo-router'; +import { useEffect, useMemo, useRef, useState } from 'react'; +import { Pressable, ScrollView, useWindowDimensions, View } from 'react-native'; +import { useCSSVariable } from 'uniwind'; + +import { FoliageMap, type FoliageMapHandle } from '@/components/foliage/foliage-map'; +import { ChosenBar, SpotList } from '@/components/foliage/spot-list'; +import { SendIcon } from '@/components/post/icons'; +import { ScreenHeader } from '@/components/screen-header'; +import { Text } from '@/components/text'; +import { Chips, Ic } from '@/components/ui'; +import { track } from '@/lib/analytics'; +import { useFoliage } from '@/lib/foliage'; +import { useShare } from '@/lib/share-image'; +import { SITE_URL } from '@/lib/site'; + +type Filter = 'all' | Kind; +const FILTERS: [Filter, string][] = [ + ['all', '전체'], + ['maple', '단풍'], + ['ginkgo', '은행'], +]; + +/** 단풍 지도: 명소 67곳을 지도에서 확대해 보고 아래 목록으로 고른다. ?spot= 으로 열면 그 명소로 (웹 FoliagePage) */ +export default function FoliageScreen() { + const params = useLocalSearchParams<{ spot?: string }>(); + const { today, spots } = useFoliage(); + const [filter, setFilter] = useState('all'); + const [sel, setSel] = useState(params.spot ?? null); + const mapRef = useRef(null); + const shotRef = useRef(null); + const shareView = useShare(); + const ink = String(useCSSVariable('--color-ink')); + const { width, height: winH } = useWindowDimensions(); + // 지도는 스크롤 밖에 고정: 가로만큼 정사각형, 화면이 낮으면 화면 높이의 45%까지 + const mapH = Math.max(280, Math.min(width * 1.05, winH * 0.45, 560)); + const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter]); + + useEffect(() => track('foliage_open', {}), []); + useEffect(() => { + if (sel) track('foliage_spot', { spot_name: sel, from: 'page' }); + }, [sel]); + + const chosen = spots.find((m) => m.name === sel); + const peakCount = spots.filter((m) => m.stage === 'peak').length; + const title = headline(spots); + const pick = (m: Spot) => { + setSel(m.name); + mapRef.current?.focus(m); + }; + const share = () => void shareView(shotRef, { title: chosen ? `${chosen.name} 단풍` : '단풍 지도', message: `${title} · 날씨각 단풍 지도 ${SITE_URL}/foliage` }); + + return ( + + + + + } + /> + + + + {`단풍 지도 · ${md(today)}`} + + {title} + + {/* 보내기는 지금 보이는 지도 그대로 찍어 보낸다 (웹은 따로 만든 공유 그림) */} + + + + + + + + + {`출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요${peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}`} + + + + ); +} diff --git a/mobile/src/components/foliage/foliage-card.tsx b/mobile/src/components/foliage/foliage-card.tsx new file mode 100644 index 0000000..78f7aa9 --- /dev/null +++ b/mobile/src/components/foliage/foliage-card.tsx @@ -0,0 +1,153 @@ +import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'; +import { headline, ICON_R, labelBoxes, md, nearest, placeLabels, placeProvinces, PROVINCES, rankNow, spread } from '@nalssigak/shared/lib/foliage'; +import { router } from 'expo-router'; +import { useEffect, useMemo, useState } from 'react'; +import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native'; + +import { Label, Legend, MapImage, MAP_INK, MAP_INK3, Marker, PAPER, Province, useLabelSizes } from '@/components/foliage/parts'; +import { Pager } from '@/components/post/pager'; +import { PostFrame } from '@/components/post/post-frame'; +import { Text } from '@/components/text'; +import { Ic } from '@/components/ui'; +import { track } from '@/lib/analytics'; +import { useFoliage } from '@/lib/foliage'; + +const RANK_N = 7; +// 지도 아래 고른 명소 줄(범례 자리) 높이 +const BAR_H = 60; +// 지도 그림은 땅이 왼쪽에 치우쳐 있어 오른쪽(빈 바다)으로 밀어 가운데에 맞춘다 +const SHIFT = 0.07; + +const goMap = (spot?: string) => router.push(spot ? { pathname: '/foliage', params: { spot } } : '/foliage'); + +/** + * 피드의 단풍 지도 카드 (웹 FoliageCard): 1장은 지금 절정인 곳만 잎으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. + * '지도 크게 보기'로 단풍 지도 화면. 단풍철이 아니면 그리지 않는다 + */ +export function FoliageCard({ post }: { post?: PostReaction | null }) { + const { today, spots, inSeason } = useFoliage(); + const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots]); + const [size, measure] = useLabelSizes(); + const [W, setW] = useState(0); + const [picked, setPicked] = useState(null); + const [index, setIndex] = useState(0); + + const pts = useMemo(() => spread(peak.map((m) => ({ m, x: m.x * W, y: m.y * W, r: ICON_R }))), [peak, W]); + const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W]); + const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size]); + + useEffect(() => { + if (picked) track('foliage_spot', { spot_name: picked, from: 'card' }); + }, [picked]); + + if (!inSeason) return null; + const toggle = (name: string) => setPicked(name === picked ? null : name); + // 잎이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다 + const tapMap = (e: GestureResponderEvent) => { + const best = nearest(pts, e.nativeEvent.locationX, e.nativeEvent.locationY); + setPicked(best && best !== picked ? best : null); + }; + const onLayout = (e: LayoutChangeEvent) => setW(e.nativeEvent.layout.width); + const sel = peak.find((m) => m.name === picked); + // 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로 + const ranked = rankNow(spots).slice(0, RANK_N); + const caption = peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined; + const pageH = W + 8 + BAR_H; + + const mapPage = ( + + + + {provs.map((v) => ( + + ))} + {pts.map((p) => ( + + ))} + {peak.map((m) => ( + + {/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 잎을 가리지 않게 */} + {sel ? ( + + + + + {sel.name} + + + {`${sel.region.split(' ')[0]} · 절정 예상 ${md(sel.peak)}`} + + + goMap(sel.name)} accessibilityRole="link" className="rounded-full px-3 py-1.5" style={{ backgroundColor: MAP_INK }}> + 지도에서 보기 › + + + ) : ( + + + + )} + + ); + + const rankPage = ( + + + 지금 가기 좋은 곳 + + + 절정 예상일이 오늘과 가까운 순서예요 + + + {ranked.map((m, i) => ( + goMap(m.name)} accessibilityRole="link" accessibilityLabel={`${i + 1}위 ${m.name}, 절정 예상 ${md(m.peak)}`} className="flex-row items-center gap-2.5 py-1.5"> + + {String(i + 1)} + + + + + {m.name} + + + {m.region} + + + + {md(m.peak)} + + + ))} + + + ); + + return ( + + {/* 밤에도 지도 카드는 밝은 종이 그대로 (웹 b-keep-bg) */} + + {`단풍 지도 · ${md(today)}`} + + {headline(spots)} + + + {W > 0 ? ( + + {[mapPage, rankPage]} + + ) : null} + + {`${index + 1}/2`} + + + goMap()} accessibilityRole="link" className="mt-2 w-full items-center rounded-full bg-white py-2" style={{ boxShadow: 'inset 0 -3px 0 rgba(40,48,74,0.08)' }}> + + 지도 크게 보기 › + + + + + ); +} diff --git a/mobile/src/components/foliage/foliage-map.tsx b/mobile/src/components/foliage/foliage-map.tsx new file mode 100644 index 0000000..fe6a254 --- /dev/null +++ b/mobile/src/components/foliage/foliage-map.tsx @@ -0,0 +1,272 @@ +import { ICON_R, LAND_CX, labelBoxes, nearest, placeLabels, placeProvinces, PROVINCES, spread, type Box, type Spot, type Stage } from '@nalssigak/shared/lib/foliage'; +import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type Ref } from 'react'; +import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native'; + +import { Label, MapImage, Marker, MAP_INK, PAPER, Province, useLabelSizes } from '@/components/foliage/parts'; +import { Text } from '@/components/text'; + +type Cam = { s: number; tx: number; ty: number }; + +const DOT_R: Record = { peak: ICON_R, first: 4, before: 3, gone: 3 }; +const MAX_ZOOM = 5; +const FIT_TOP = 30; +const FIT_BOTTOM = 14; +// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비) +const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3); +const LABEL_FROM = [1, 1.6, 2.5, 3.5]; +// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게 +const DOT_FROM: Record = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 }; +const ZOOM_BTNS = [ + ['+', '확대', 1.6], + ['−', '축소', 1 / 1.6], +] as const; + +export type FoliageMapHandle = { focus: (m: Spot) => void }; + +type Props = { spots: Spot[]; sel: string | null; onSelect: (name: string | null) => void; height: number; ref?: Ref }; + +/** + * 단풍 지도 페이지의 지도: 두 손가락으로 확대·이동, 한 손가락으로 이동, 누르면 가까운 명소 고르기, 두 번 누르면 확대 (웹 FoliagePage 지도). + * 앱은 지도를 스크롤 밖에 고정해 손짓이 페이지 스크롤과 다투지 않는다 + */ +export function FoliageMap({ spots, sel, onSelect, height, ref }: Props) { + const vpRef = useRef(null); + const origin = useRef({ x: 0, y: 0 }); + const [box, setBox] = useState({ W: 0, H: 0 }); + const [view, setView] = useState({ s: 1, tx: 0, ty: 0 }); + const viewRef = useRef(view); + useLayoutEffect(() => { + viewRef.current = view; + }, [view]); + const [size, measure] = useLabelSizes(); + + // 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데 + const fit = useMemo(() => { + const { W, H } = box; + if (!W || !spots.length) return { s: 1, tx: 0, ty: 0 }; + const xs = spots.map((m) => m.x); + const ys = spots.map((m) => m.y); + const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)]; + // 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만 + const h = H - FIT_TOP - FIT_BOTTOM; + // 가로는 땅 가운데(LAND_CX)에 맞추되 동·서 끝 명소가 다 들어오게 + const half = Math.max(LAND_CX - x0, x1 - LAND_CX) + 0.07; + const s = Math.min(W / (2 * half * W), h / ((y1 - y0) * W)); + return { s, tx: W / 2 - LAND_CX * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s }; + }, [box, spots]); + + const clamp = useCallback( + (v: Cam): Cam => { + const { W, H } = box; + const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s)); + const w = W * s; + // 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게 + const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx)); + const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty)); + return { s, tx, ty }; + }, + [box, fit], + ); + + const anim = useRef(0); + const set = useCallback((v: Cam) => { + cancelAnimationFrame(anim.current); + setView(v); + }, []); + const animateTo = useCallback( + (to: Cam) => { + cancelAnimationFrame(anim.current); + const from = viewRef.current; + const target = clamp(to); + const start = performance.now(); + const step = (now: number) => { + const k = Math.min(1, (now - start) / 280); + const e = 1 - (1 - k) ** 3; + setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e }); + if (k < 1) anim.current = requestAnimationFrame(step); + }; + anim.current = requestAnimationFrame(step); + }, + [clamp], + ); + const zoomAt = useCallback( + (f: number, cx: number, cy: number, smooth = false) => { + const v = viewRef.current; + const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f)); + const k = s / v.s; + const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k }); + if (smooth) animateTo(next); + else set(next); + }, + [fit, clamp, animateTo, set], + ); + const focus = useCallback( + (m: Spot) => { + const { W, H } = box; + const s = Math.max(viewRef.current.s, fit.s * 2.5); + animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s }); + }, + [box, fit, animateTo], + ); + useImperativeHandle(ref, () => ({ focus }), [focus]); + + // 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로. 그 뒤 크기가 바뀌면 지금 화면을 범위 안으로 + const started = useRef(false); + const linked = useRef(sel); + useEffect(() => { + if (!box.W) return; + if (started.current) { + set(clamp(viewRef.current)); + return; + } + started.current = true; + set(fit); + const m = spots.find((s) => s.name === linked.current); + if (m) focus(m); + }, [box, fit, spots, set, clamp, focus]); + useEffect(() => () => cancelAnimationFrame(anim.current), []); + + const pts = useMemo(() => { + const ratio = view.s / fit.s; + const visible = spots.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01); + return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] }))); + }, [spots, view, box.W, fit.s, sel]); + const ptsRef = useRef(pts); + useLayoutEffect(() => { + ptsRef.current = pts; + }, [pts]); + + const labelAt = useMemo(() => { + const ratio = view.s / fit.s; + const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m)); + // 오른쪽 위 +/− 단추 자리는 비운다 + const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]; + return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel); + }, [pts, size, sel, view.s, fit.s, box]); + const provs = useMemo( + () => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)), + [view, box.W, pts, labelAt, size], + ); + + // 손짓 상태: 두 손가락 거리·가운데, 한 손가락 시작점과 움직였는지, 마지막으로 누른 때(두 번 누르기) + const gesture = useRef<{ pinch: { d: number; x: number; y: number } | null; one: { x: number; y: number; moved: boolean } | null; lastTap: number }>({ pinch: null, one: null, lastTap: 0 }); + const local = (t: { pageX: number; pageY: number }) => ({ x: t.pageX - origin.current.x, y: t.pageY - origin.current.y }); + const pickAt = (x: number, y: number) => { + const best = nearest(ptsRef.current, x, y); + onSelect(best && best !== sel ? best : null); + }; + const begin = (e: GestureResponderEvent) => { + const g = gesture.current; + const ts = e.nativeEvent.touches; + if (ts.length >= 2) { + const [a, b] = [local(ts[0]), local(ts[1])]; + g.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; + g.one = null; + } else if (ts.length === 1) { + g.pinch = null; + g.one = { ...local(ts[0]), moved: false }; + } + }; + const onGrant = (e: GestureResponderEvent) => { + cancelAnimationFrame(anim.current); + // 지도 칸의 화면 위치: 손가락 좌표(pageX)를 지도 안 좌표로 바꾸는 데 쓴다 + vpRef.current?.measure((_x, _y, _w, _h, px, py) => { + origin.current = { x: px, y: py }; + }); + begin(e); + }; + const onMove = (e: GestureResponderEvent) => { + const g = gesture.current; + const ts = e.nativeEvent.touches; + if (ts.length >= 2) { + if (!g.pinch) return begin(e); + const [a, b] = [local(ts[0]), local(ts[1])]; + const d = Math.hypot(a.x - b.x, a.y - b.y); + const x = (a.x + b.x) / 2; + const y = (a.y + b.y) / 2; + const v = viewRef.current; + const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / g.pinch.d)); + const k = s / v.s; + set(clamp({ s, tx: x - (g.pinch.x - v.tx) * k, ty: y - (g.pinch.y - v.ty) * k })); + g.pinch = { d, x, y }; + return; + } + // 두 손가락에서 한 손가락이 떨어지면 남은 손가락으로 이어서 이동 (누르기로는 안 친다) + if (!g.one || g.pinch) { + if (ts.length === 1) g.one = { ...local(ts[0]), moved: true }; + g.pinch = null; + return; + } + const p = local(ts[0]); + if (Math.hypot(p.x - g.one.x, p.y - g.one.y) > 6) g.one.moved = true; + if (!g.one.moved) return; + const v = viewRef.current; + set(clamp({ s: v.s, tx: v.tx + p.x - g.one.x, ty: v.ty + p.y - g.one.y })); + g.one = { ...p, moved: true }; + }; + const onRelease = (e: GestureResponderEvent) => { + const g = gesture.current; + const tap = g.one && !g.one.moved ? g.one : null; + g.one = null; + g.pinch = null; + if (!tap) return; + // 두 번 누르기: 300ms 안에 또 누르면 확대 + if (e.nativeEvent.timestamp - g.lastTap < 300) { + g.lastTap = 0; + zoomAt(2, tap.x, tap.y, true); + } else { + g.lastTap = e.nativeEvent.timestamp; + pickAt(tap.x, tap.y); + } + }; + const onEnd = () => { + gesture.current.one = null; + gesture.current.pinch = null; + }; + + const onLayout = (e: LayoutChangeEvent) => { + const { width, height: h } = e.nativeEvent.layout; + setBox({ W: width, H: h }); + vpRef.current?.measure((_x, _y, _w, _h, px, py) => { + origin.current = { x: px, y: py }; + }); + }; + const markers = [...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak')); + + return ( + true} + onMoveShouldSetResponder={() => true} + onResponderTerminationRequest={() => false} + onResponderGrant={onGrant} + onResponderMove={onMove} + onResponderRelease={onRelease} + onResponderTerminate={onEnd} + className="overflow-hidden" + style={{ height, backgroundColor: PAPER }} + accessibilityLabel="단풍 지도" + > + {box.W > 0 ? : null} + {provs.map((v) => ( + + ))} + {markers.map((p) => ( + + ))} + {spots.map((m) => ( + + ); +} diff --git a/mobile/src/components/foliage/parts.tsx b/mobile/src/components/foliage/parts.tsx new file mode 100644 index 0000000..8aade0d --- /dev/null +++ b/mobile/src/components/foliage/parts.tsx @@ -0,0 +1,135 @@ +import type { Kind, LabelSize, Pt, Spot, Stage } from '@nalssigak/shared/lib/foliage'; +import { Image } from 'expo-image'; +import { useCallback, useRef, useState, type ReactNode } from 'react'; +import { Platform, Pressable, View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from 'react-native'; + +import { Text } from '@/components/text'; +import { Ic } from '@/components/ui'; +import { MAP_IMAGE } from '@/lib/foliage'; + +// 지도는 밤에도 밝은 종이 그대로 (웹 b-keep-bg) +export const PAPER = '#fff6ea'; +export const MAP_INK = '#28304a'; +export const MAP_INK3 = '#6b7189'; +const LABEL_INK: Record = { maple: '#b5321f', ginkgo: '#8a6508' }; + +/** + * 지도 그림. 웹은 채도를 빼서(saturate .3) 잎 아이콘이 묻히지 않게 한다. + * 안드로이드는 같은 filter, iOS 는 filter 의 채도를 못 써서 종이색을 반쯤 덮어 옅게 한다 + */ +export function MapImage({ style }: { style: StyleProp }) { + const android = Platform.OS === 'android'; + return ( + + + {!android && } + + ); +} + +const DOT: Record, { size: number; color: string }> = { + first: { size: 7, color: 'rgba(217,119,46,0.85)' }, + before: { size: 5, color: 'rgba(143,138,128,0.6)' }, + gone: { size: 5, color: 'rgba(143,138,128,0.6)' }, +}; + +/** 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(big 이면 점을 크게) */ +export function StageMark({ m, big }: { m: Spot; big?: boolean }) { + if (m.stage === 'peak') return ; + const dot = DOT[m.stage]; + const size = big ? 14 : dot.size; + return ; +} + +/** 지도 위 점·잎. 고른 명소는 속이 빈 고리만 둘러 옆 명소를 가리지 않게 */ +export function Marker({ p, sel }: { p: Pt; sel: boolean }) { + return ( + + {sel ? : null} + + + ); +} + +/** 시·도 이름: 지도에 옅게 깔리는 글자. 산 무늬 위에서도 읽히게 종이색 번짐을 두른다 */ +export function Province({ name, x, y }: { name: string; x: number; y: number }) { + return ( + + + {name} + + + ); +} + +/** + * 명소 이름표. 자리를 못 받았으면(at 없음) 숨긴 채 왼쪽 위에 두고 크기만 잰다 (웹 useLabelSize 대신 onLayout). + * tone: 고름(진한 바탕) · 절정(잎 색 글자) · 그 밖(회색 글자) + */ +export function Label({ m, at, sel, onPress, onLayout, accessibilityLabel }: { m: Spot; at?: { left: number; top: number }; sel?: boolean; onPress: () => void; onLayout: (e: LayoutChangeEvent) => void; accessibilityLabel: string }) { + const color = sel ? '#ffffff' : m.stage === 'peak' ? LABEL_INK[m.kind] : '#5b6075'; + return ( + + + {m.name} + + + ); +} + +/** 이름표 크기 모으기: Label 의 onLayout 을 받아 이름별 폭·높이. 한 프레임에 한 번만 다시 그린다 */ +export function useLabelSizes() { + const [size, setSize] = useState({}); + const acc = useRef({}); + const frame = useRef(0); + const measure = useCallback( + (name: string) => (e: LayoutChangeEvent) => { + const { width: w, height: h } = e.nativeEvent.layout; + const old = acc.current[name]; + if (old && Math.abs(old.w - w) < 0.5 && Math.abs(old.h - h) < 0.5) return; + acc.current = { ...acc.current, [name]: { w, h } }; + cancelAnimationFrame(frame.current); + frame.current = requestAnimationFrame(() => setSize(acc.current)); + }, + [], + ); + return [size, measure] as const; +} + +/** 범례: 절정 잎 둘, full 이면 첫 단풍·단풍 전 점까지 */ +export function Legend({ full, color }: { full?: boolean; color: string }) { + const item = (mark: ReactNode, label: string) => ( + + {mark} + + {label} + + + ); + return ( + + {item(, '단풍 절정')} + {item(, '은행 절정')} + {full ? item(, '첫 단풍') : null} + {full ? item(, '단풍 전') : null} + + ); +} diff --git a/mobile/src/components/foliage/spot-list.tsx b/mobile/src/components/foliage/spot-list.tsx new file mode 100644 index 0000000..908eb08 --- /dev/null +++ b/mobile/src/components/foliage/spot-list.tsx @@ -0,0 +1,93 @@ +import { md, STAGE, type Spot, type Stage } from '@nalssigak/shared/lib/foliage'; +import { Pressable, View } from 'react-native'; + +import { Legend, StageMark } from '@/components/foliage/parts'; +import { Text } from '@/components/text'; + +const GROUPS: [Stage, string][] = [ + ['peak', '지금 절정'], + ['first', '곧 절정'], + ['before', '아직'], + ['gone', '절정 지남'], +]; + +const CHIP: Partial> = { + peak: { bg: '#ffe3db', ink: '#b5321f' }, + first: { bg: '#ffe8d2', ink: '#a34f12' }, +}; + +/** 지도 아래 한 줄: 고른 명소가 있으면 그 명소 정보, 없으면 범례 (지도 위를 가리지 않게 범례 자리에) */ +export function ChosenBar({ chosen, legendColor }: { chosen?: Spot; legendColor: string }) { + if (!chosen) + return ( + + + + ); + const chip = CHIP[chosen.stage]; + return ( + + + + + + + + {chosen.name} + + + {STAGE[chosen.stage]} + + + + {`${chosen.region} · 절정 예상 ${md(chosen.peak)}`} + + + + ); +} + +/** 단계별 명소 목록 (지금 절정 · 곧 절정 · 아직 · 절정 지남). 누르면 지도에서 그 명소로 */ +export function SpotList({ spots, sel, onPick }: { spots: Spot[]; sel: string | null; onPick: (m: Spot) => void }) { + return ( + + {GROUPS.map(([g, title]) => { + const rows = spots.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak)); + if (!rows.length) return null; + return ( + + + {title} + {`${rows.length}곳`} + + + {rows.map((m) => ( + onPick(m)} + accessibilityRole="button" + accessibilityState={{ selected: m.name === sel }} + className="flex-row items-center gap-3 border-b border-line py-2.5 pl-1" + style={m.name === sel ? { backgroundColor: 'rgba(255,122,69,0.08)' } : undefined} + > + + + + + + {m.name} + + + {`${m.region} · ${m.own ? '절정 예상' : '가까운 지점 날짜'}`} + + + {md(m.peak)} + + ))} + + + ); + })} + + ); +} diff --git a/mobile/src/lib/foliage.ts b/mobile/src/lib/foliage.ts new file mode 100644 index 0000000..28d1969 --- /dev/null +++ b/mobile/src/lib/foliage.ts @@ -0,0 +1,13 @@ +import { foliageOn, foliageToday } from '@nalssigak/shared/lib/foliage'; +import { useMemo, useState } from 'react'; + +export { foliageInSeason } from '@nalssigak/shared/lib/foliage'; + +/** 단풍 지도 그림 (웹 public/foliage/korea-map.webp 를 그대로 묶는다, 정사각형) */ +export const MAP_IMAGE: number = require('../../../frontend/public/foliage/korea-map.webp'); + +/** 오늘(한국 시각) 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false (웹 useFoliage) */ +export function useFoliage() { + const [today] = useState(() => foliageToday()); + return useMemo(() => foliageOn(today), [today]); +} diff --git a/shared/lib/foliage.ts b/shared/lib/foliage.ts new file mode 100644 index 0000000..1cab152 --- /dev/null +++ b/shared/lib/foliage.ts @@ -0,0 +1,201 @@ +// 단풍 지도 데이터·계산 (웹 frontend/src/b/foliage.ts 와 앱 mobile/src/components/foliage 가 같이 쓴다). 화면 그리기는 각자 +import data from '../../frontend/seo/foliage_2026.json' +import { kst } from '.' + +export type Kind = 'maple' | 'ginkgo' +export type Stage = 'before' | 'first' | 'peak' | 'gone' +type Raw = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string } +/** x·y 는 지도 그림 안 위치(0~1), own 은 산림청 예측 지점 자기 날짜인지(아니면 가까운 지점에서 빌린 날짜) */ +export type Spot = Omit & { stage: Stage; d: number; x: number; y: number; own: boolean } + +// 지도 그림(frontend/public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값 +const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 } +// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다 +const FIRST_DAYS = 14 +const PEAK_DAYS = 3 +const PEAK_AFTER = 7 + +export const STAGE: Record = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' } +export const KIND: Record = { maple: '단풍', ginkgo: '은행' } +/** 절정 잎 아이콘 반지름(점끼리 밀어 낼 때) */ +export const ICON_R = 10 + +const DAY = 86_400_000 +const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY) + +function stage(peak: string, today: string): Stage { + const d = days(today, peak) + if (d < -PEAK_AFTER) return 'gone' + if (d <= PEAK_DAYS) return 'peak' + return d <= FIRST_DAYS ? 'first' : 'before' +} + +const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size }) +// 처음 화면 가로 가운데: 명소 가운데(127.9°)로 잡으면 서해 섬까지 든 땅이 왼쪽으로 쏠려 보여 서쪽으로 당김 +export const LAND_CX = toXY(36, 127.65).x + +// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림 +export const PROVINCES = ( + [ + ['서울', 37.56, 126.98], + ['경기', 37.95, 127.05], + ['강원', 37.65, 128.35], + ['충북', 36.8, 127.75], + ['충남', 36.45, 126.85], + ['전북', 35.72, 127.1], + ['전남', 34.85, 126.9], + ['경북', 36.3, 128.75], + ['경남', 35.3, 128.2], + ['제주', 33.38, 126.55], + ] as const +).map(([name, lat, lon]) => ({ name, ...toXY(lat, lon) })) + +export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}` +const province = (m: Spot) => m.region.split(' ')[0].split('·') + +/** 오늘(한국 시각) 날짜 'YYYY-MM-DD' */ +export function foliageToday(now: Date = new Date()) { + const t = kst(now) + return `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}` +} + +/** today 기준 명소 67곳과 단계. 단풍철이 아니면 inSeason 이 false */ +export function foliageOn(today: string) { + const spots: Spot[] = (data.spots as Raw[]).map(({ basis, lat, lon, ...m }) => ({ + ...m, + stage: stage(m.peak, today), + d: days(today, m.peak), + ...toXY(lat, lon), + own: basis.startsWith('산림청'), + })) + // 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지 + const peaks = spots.map((m) => m.peak).sort() + const inSeason = days(peaks[0], today) >= -FIRST_DAYS && days(peaks[peaks.length - 1], today) <= PEAK_AFTER + return { today, spots, inSeason } +} + +/** 오늘이 단풍철인지 (오늘 아이콘 줄의 단풍 지도 칸·피드 단풍 카드를 보일지) */ +export const foliageInSeason = (today: string = foliageToday()) => foliageOn(today).inSeason + +/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */ +export function headline(spots: Spot[]) { + const peak = spots.filter((m) => m.stage === 'peak') + if (peak.length) { + const count = new Map() + for (const p of peak.flatMap(province)) count.set(p, (count.get(p) ?? 0) + 1) + return `지금 절정: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}` + } + if (spots.some((m) => m.stage === 'gone')) return '올해 단풍이 지고 있어요' + const first = spots.reduce((a, b) => (b.peak < a.peak ? b : a)) + return `첫 절정은 ${province(first)[0]}, ${md(first.peak)}쯤` +} + +/** 지금 가기 좋은 순: 절정인 곳 중 절정 예상일이 오늘과 가까운 순, 같으면 자기 예측 날짜 먼저, 그다음 이름 순 */ +export const rankNow = (spots: Spot[]) => + spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name)) + +export type Pt = { m: Spot; x: number; y: number; r: number } +export type Box = { l: number; t: number; r: number; b: number } +export type LabelSize = Record +const LABEL_GAP = 4 +const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b + +/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */ +export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: Pt[], labels: Box[] = [], R = 90) { + // 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳) + const placed: Box[] = [] + const free = (x: number, y: number) => + pts.every((p) => Math.abs(p.x - x) > p.r + 17 || Math.abs(p.y - y) > p.r + 10) && [...labels, ...placed].every((b) => !overlaps(provinceBox(x, y), b)) + return provs.map((v) => { + const at = pick(v) + placed.push(provinceBox(at.x, at.y)) + return at + }) + function pick(v: { name: string; x: number; y: number }) { + if (free(v.x, v.y)) return v + for (let d = 5; d <= R; d += 5) + for (let a = 0; a < 24; a++) { + const x = v.x + Math.cos((a / 24) * 2 * Math.PI) * d + const y = v.y + Math.sin((a / 24) * 2 * Math.PI) * d + if (free(x, y)) return { ...v, x, y } + } + return v + } +} +export function provinceBox(x: number, y: number): Box { + return { l: x - 16, t: y - 9, r: x + 16, b: y + 9 } +} + +/** placeLabels 결과를 상자로: 시·도 이름이 피해 갈 자리 */ +export const labelBoxes = (at: Record, size: LabelSize) => + Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) })) + +/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */ +export function spread(pts: Pt[], gap = 1.5) { + for (let it = 0; it < 60; it++) { + let moved = false + for (let i = 0; i < pts.length; i++) + for (let j = i + 1; j < pts.length; j++) { + const a = pts[i] + const b = pts[j] + let dx = b.x - a.x + let dy = b.y - a.y + let d = Math.hypot(dx, dy) + const need = a.r + b.r + gap + if (d >= need) continue + if (d < 0.01) [dx, dy, d] = [Math.cos(i + j), Math.sin(i + j), 1] + const push = (need - d) / 2 + a.x -= (dx / d) * push + a.y -= (dy / d) * push + b.x += (dx / d) * push + b.y += (dy / d) * push + moved = true + } + if (!moved) break + } + return pts +} + +/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */ +export function placeLabels(order: Pt[], all: Pt[], size: LabelSize, area: Box, blocked: Box[] = [], vertical: (p: Pt) => boolean = () => false) { + const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } })) + const taken = [...blocked.map((box) => ({ name: '', box })), ...dots] + const out: Record = {} + for (const p of order) { + const s = size[p.m.name] + if (!s || p.x < area.l || p.x > area.r || p.y < area.t || p.y > area.b) continue + // 옆 자리가 없을 때 vertical 인 명소(절정)만 위·아래도 써 본다 + const tries = [ + [p.r + 2, -s.h / 2], + [-s.w - p.r - 2, -s.h / 2], + ...(vertical(p) ? [[-s.w / 2, -s.h - p.r - 1], [-s.w / 2, p.r + 1]] : []), + ] + for (const [dx, dy] of tries) { + const r = { l: p.x + dx, t: p.y + dy, r: p.x + dx + s.w, b: p.y + dy + s.h } + if (r.l < area.l || r.t < area.t || r.r > area.r || r.b > area.b) continue + // 이름표끼리는 LABEL_GAP 만큼 띄워 손가락으로 옆 이름을 잘못 누르지 않게 + const pad = { l: r.l - LABEL_GAP, t: r.t - LABEL_GAP, r: r.r + LABEL_GAP, b: r.b + LABEL_GAP } + if (taken.some((o) => o.name !== p.m.name && overlaps(o.name ? r : pad, o.box))) continue + // 위·아래 자리는 이름표에서 가장 가까운 표시가 자기 것일 때만: 아니면 다른 점의 이름처럼 읽힌다 + const cx = (r.l + r.r) / 2 + const cy = (r.t + r.b) / 2 + const mine = Math.hypot(cx - p.x, cy - p.y) + if (dy !== -s.h / 2 && all.some((q) => q.m.name !== p.m.name && Math.hypot(cx - q.x, cy - q.y) < mine)) continue + taken.push({ name: '', box: r }) + out[p.m.name] = { left: r.l, top: r.t } + break + } + } + return out +} + +/** 누른 자리에서 가장 가까운 명소 (잎이 작아 손가락으로 겨냥하기 어려워서). 반경 r 안에 없으면 null */ +export function nearest(pts: Pt[], x: number, y: number, r = 24) { + let best: string | null = null + let bestD = r + for (const p of pts) { + const d = Math.hypot(p.x - x, p.y - y) + if (d < bestD) [best, bestD] = [p.m.name, d] + } + return best +} diff --git a/shared/tsconfig.json b/shared/tsconfig.json index 06bc82e..04cbfb9 100644 --- a/shared/tsconfig.json +++ b/shared/tsconfig.json @@ -5,6 +5,7 @@ "module": "esnext", "moduleResolution": "bundler", "verbatimModuleSyntax": true, + "resolveJsonModule": true, "moduleDetection": "force", "noEmit": true, "skipLibCheck": true,