Compare commits

..
Author SHA1 Message Date
skkimandClaude 189d51f1ce chore: 앱 버전 1.1.0 (웹 기능 이식)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-05 11:38:40 +09:00
skkimandClaude 9a7e0ddc75 fix: 게임 웹뷰가 날씨각 사이트 안에서만 움직이게 — 로그인 토큰은 사이트 주소에서만 넣고, 다른 주소(외부 링크)는 휴대폰 브라우저로
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-05 11:34:14 +09:00
skkimandClaude e5cdfa2642 feat: 앱 단풍 지도 — /foliage 지도(두 손가락 확대·이동, 눌러 가까운 명소)·단계별 명소 목록, 단풍철 오늘 피드 맨 앞 카드(foliage_post 좋아요·댓글)와 아이콘. 명소 데이터·계산을 shared/lib/foliage.ts 로 (GA foliage_open·foliage_spot)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:52:23 +09:00
skkimandClaude 6daa2f4d2a feat: 앱 오늘 탭 아이콘 줄 — 날씨 사주(오늘 안 봤으면 빨간 점)·날씨 게임·쇼츠·내 각(그 줄로 내려감)·동네 이야기, 타로는 웹처럼 숨김 (GA today_icon)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:49:01 +09:00
skkimandClaude 02ebcda0ea feat: 앱 날씨 사주 — /saju 생년월일 입력(연·월·일 칩, 시각 −/+), 오늘 점수 링·할 일 카드, 사주 명식, 레벨로 열리는 이번 주·금전·연애·이달·올해, 궁합(Lv.5), 기기·계정 생년월일 저장, ?open= 으로 그 칸 (GA saju_input·saju_view)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:46:31 +09:00
skkimandClaude 47526c1cef feat: 앱 기념일 꾸밈 — 할로윈·빼빼로데이·크리스마스·추석 기간에만 하늘 네 귀퉁이 소품 (이야기 주제·게임 그림은 앞 커밋에서)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:43:42 +09:00
skkimandClaude 697c4bfb20 feat: 앱 쇼츠·구름 합치기 게임 — 오늘 피드 쇼츠 줄, /shorts 위아래로 넘겨 보기(유튜브 플레이어를 사이트 주소 기준 웹뷰로, 앞뒤 미리 받기, 눌러 소리), /game 은 웹 게임을 웹뷰로 띄우고 앱 지역·로그인을 넘김(react-native-webview) (GA shorts_open·shorts_view·shorts_sound)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:42:32 +09:00
skkimandClaude 5a88b08a44 feat: 앱 내 각 — 오늘 피드 내 각 줄, 만들기 창(있는 각 불러오기·아이콘·조건·시간대·미리보기 점수), 상세 창(시간대·조건별 점수, 링크 공유·지우기), 로그인 전 기기에 하나 저장 후 로그인하면 계정으로, ?my= 받은 각 열기 (GA my_gak_save)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:38:40 +09:00
skkimandClaude f6884fe9c9 chore: package-lock 은 expo-image-picker 항목만 더함 (로컬 npm 이 다시 쓴 libc·선택 의존성 변경은 되돌림)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:35:50 +09:00
skkimandClaude c15f045c64 feat: 앱 동네 이야기 — /talk 주제별 글·내 글, 오늘 피드 쓰기 칸과 포스트 두 장마다 사람 글, 사진 올리기(expo-image-picker, 카메라·마이크 권한 없음), 이야기 댓글·좋아요·신고·안 보기·지우기, 내 정보 내 글. 기념일 목록을 shared로 (GA talk_post·talk_comment·feed_item_view, like·report·block talk)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:35:23 +09:00
skkimandClaude e40a9a0539 feat: 앱 계정 레벨 — 하루 출석 각, 아바타 Lv 표시, 내 정보 레벨 카드, 내 레벨·레벨업 창, 공유하면 하루 한 번 각, 각을 주는 일 뒤 레벨 다시 받기. 아이콘 목록을 웹 아이콘 전부로 (GA sheet_open level·levelUp)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:26:21 +09:00
skkimandClaude 01b5f917b9 feat: 앱 오늘 피드를 웹과 맞춤 — 히어로 오늘/내일 전환·좋아요·댓글·보내기·점수 근거 창, 오늘의 각 카드(gak_post), 날씨각 카드(그림 슬라이드), 행사·TOP5 띠 없앰, 좋아요·댓글 로그인 없이 (GA hero_day_switch, like hero_post·gak_post)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 17:23:44 +09:00
skkim e8b8cc79b6 Merge branch 'fix/app-text-node-crash' into feat/app-web-parity 2026-11-04 16:54:28 +09:00
skkimandClaude 709dcf742e fix: 앱이 켜자마자 꺼지던 것 — 서버가 빈 문자열(노을 line 등)을 주면 '&&'가 빈 글자를 View 안에 그려 안드로이드에서 'Text strings must be rendered within a <Text>'로 종료됨. 문자열 조건을 !!로 감쌈
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 16:54:28 +09:00
skkimandClaude cab3336859 feat: 앱 GA4 이벤트 틀(track, 웹과 같은 이벤트 목록을 shared로) — 기존 앱 기능에 창_열기·각_보기·글_열기·로그인·지역_변경·좋아요·댓글·신고·차단·약관_동의·공유, 전송은 Firebase 연결 뒤. 탭 밖 화면용 루트 스택
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-04 16:52:08 +09:00
77 changed files with 4992 additions and 667 deletions

No files matched your search

+8 -1
View File
@@ -72,7 +72,14 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
- 점수 근거·댓글창 열기처럼 창으로 여는 기능은 따로 이벤트를 두지 않고 `sheet_open`의 `sheet`로 나눠 본다.
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
- 설치는 카드 노출 → 누름 → 설치 완료 → 홈 화면 실행 순서로 본다. 아이폰은 설치 완료를 알 수 없어 `app_launch`로 대신 본다.
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
- 새 이벤트는 `shared/lib/analytics.ts`의 `Events` 타입과 `GA_NAME` 에 먼저 더한다 (웹·앱이 같이 씀). 타입에 없는 이름은 빌드에서 걸린다.
## 앱 (안드로이드, `mobile/`)
- 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다.
- **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다.
- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 오늘 아이콘 줄: `today_icon`(`components/today/icons.tsx`). 사주: `saju_input`(`components/saju/birth-form.tsx`), `saju_view`(`saju/reading.tsx`). 단풍 지도: `foliage_open`(`app/foliage.tsx`), `foliage_spot`(`components/foliage/*`, 화면 `page`·피드 카드 `card`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음).
- 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다.
## GA4 설정
+6 -178
View File
@@ -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<Raw, 'basis' | 'lat' | 'lon'> & { 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<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' }
export const KIND: Record<Kind, string> = { 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<string, number>()
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<string, { left: number; top: number }>, size: Record<string, { w: number; h: number }>) =>
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<string, { w: number; h: number }>, 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<string, { left: number; top: number }> = {}
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<Kind, string> = { 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]'
+4 -101
View File
@@ -1,100 +1,7 @@
import { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib'
import { HOLIDAYS, holidayOn, type Holiday } from '@nalssigak/shared/lib/holiday'
/** 게임 8단계 그림을 바꾼다. 작은 것부터 큰 것 순서, 크기·색은 원래 단계 그대로 */
type GamePiece = { icon: string; name: string }
/**
* 기념일 꾸밈. 기간(KST, 양 끝 포함) 안에만 켜진다. 'MM-DD' 는 해마다, 'YYYY-MM-DD' 는 그해만(음력 기념일).
* 새 기념일: 여기에 한 줄 + TalkTopic(backend/common/enums.py) + 게임 그림(public/b/icons, lib.ts OWN) + 소품 그림(public/b/holiday, 투명 배경, b.css)
*/
export type Holiday = {
key: 'halloween' | 'pepero' | 'christmas' | 'chuseok'
name: string
ranges: readonly (readonly [string, string])[]
topic: TalkTopic
/** 글만 있는 사람 글 배경 (b.css b-bg-*) */
bg: string
game: readonly GamePiece[]
}
export const HOLIDAYS: readonly Holiday[] = [
{
key: 'halloween',
name: '할로윈',
ranges: [['10-30', '11-01']],
topic: TalkTopic.HALLOWEEN,
bg: 'night',
game: [
{ icon: 'candy', name: '사탕' },
{ icon: 'lollipop', name: '막대사탕' },
{ icon: 'spider', name: '거미' },
{ icon: 'spider_web', name: '거미줄' },
{ icon: 'bat', name: '박쥐' },
{ icon: 'ghost', name: '유령' },
{ icon: 'skull', name: '해골' },
{ icon: 'jack_o_lantern', name: '호박등' },
],
},
{
key: 'pepero',
name: '빼빼로데이',
ranges: [['11-11', '11-11']],
topic: TalkTopic.PEPERO,
bg: 'peach',
game: [
{ icon: 'pepero_choco', name: '초코' },
{ icon: 'pepero_almond', name: '아몬드' },
{ icon: 'pepero_strawberry', name: '딸기' },
{ icon: 'pepero_nude', name: '누드' },
{ icon: 'pepero_pair', name: '한 쌍' },
{ icon: 'pepero_bundle', name: '다발' },
{ icon: 'pepero_box', name: '한 상자' },
{ icon: 'pepero_basket', name: '바구니' },
],
},
{
key: 'christmas',
name: '크리스마스',
ranges: [['12-24', '12-25']],
topic: TalkTopic.CHRISTMAS,
bg: 'mint',
game: [
{ icon: 'xmas_candy_cane', name: '캔디케인' },
{ icon: 'xmas_ornament', name: '장식볼' },
{ icon: 'xmas_gingerbread', name: '진저쿠키' },
{ icon: 'xmas_santa_hat', name: '산타 모자' },
{ icon: 'xmas_stocking', name: '양말' },
{ icon: 'xmas_wreath', name: '리스' },
{ icon: 'xmas_santa', name: '산타' },
{ icon: 'christmas_tree', name: '트리' },
],
},
{
key: 'chuseok',
name: '추석',
ranges: [['2027-09-14', '2027-09-16']],
topic: TalkTopic.CHUSEOK,
bg: 'butter',
game: [
{ icon: 'chestnut', name: '밤' },
{ icon: 'pear', name: '배' },
{ icon: 'apple', name: '사과' },
{ icon: 'dango', name: '떡' },
{ icon: 'rabbit', name: '토끼' },
{ icon: 'maple', name: '단풍' },
{ icon: 'moon_viewing', name: '달맞이' },
{ icon: 'full_moon', name: '보름달' },
],
},
]
const pad = (n: number) => String(n).padStart(2, '0')
function inRange([from, to]: readonly [string, string], y: number, md: string) {
const day = from.length === 10 ? `${y}-${md}` : md
return from <= day && day <= to
}
// 기념일 목록·기간은 앱과 같이 쓴다 (shared/lib/holiday.ts)
export { HOLIDAYS, holidayByTopic, type Holiday } from '@nalssigak/shared/lib/holiday'
/** 미리 보기 기념일: 주소의 ?holiday= 를 탭이 닫힐 때까지 기억 */
function previewKey() {
@@ -107,9 +14,5 @@ function previewKey() {
export function currentHoliday(now = new Date()): Holiday | undefined {
const preview = previewKey()
if (preview) return HOLIDAYS.find((h) => h.key === preview)
const { y, mo, d } = kst(now)
const md = `${pad(mo)}-${pad(d)}`
return HOLIDAYS.find((h) => h.ranges.some((r) => inRange(r, y, md)))
return holidayOn(now)
}
export const holidayByTopic = (t?: number) => HOLIDAYS.find((h) => h.topic === t)
+3 -90
View File
@@ -1,51 +1,8 @@
import type { PinnedKey } from '../b/pinnedLike'
import type { Holiday } from '../b/holiday'
import { GA_NAME, type Events as SharedEvents } from '@nalssigak/shared/lib/analytics'
import type { SheetState } from '../b/sheetContext'
/** GA4로 보내는 이벤트와 값. 목록은 docs/이벤트_추적.md */
type Events = {
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
select_content: { content_type: 'article'; item_id: number; category: string }
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
login: { method: 'id' | 'google' | 'toss' }
sign_up: { method: 'id' | 'google' | 'toss' }
region_change: { region_name: string; method: 'list' | 'location' }
install_banner_view: Record<string, never>
install_click: { from: 'banner' | 'menu'; method: 'prompt' | 'guide' }
install_choice: { outcome: 'accepted' | 'dismissed' }
install_done: Record<string, never>
app_launch: { mode: 'standalone' }
/** index.html 첫 화면 스크립트가 gtag 로 바로 보낸다 */
boot_stuck: { reason: string; seconds: number; tries: number; app_started: boolean }
sheet_open: { sheet: SheetType }
like: { content_type: 'post' | 'comment' | 'talk' | PinnedKey; item_id: number }
comment: { post_id: number }
talk_comment: { talk_id: number }
report: { content_type: 'comment' | 'talk'; reason: number }
block: { content_type: 'comment' | 'talk' }
terms_agree: Record<string, never>
talk_post: { topic: number; with_image: boolean }
feed_item_view: { item_type: 'talk' | 'event'; position: number }
hero_day_switch: { day: 'today' | 'tomorrow' }
tomorrow_to_today: { region_name: string }
search_landing: { page: 'today' | 'tomorrow'; engine: 'google' | 'naver'; copy: 'new' | 'old' | 'none' }
shorts_open: { video_id: string }
shorts_view: { video_id: string; index: number }
shorts_sound: { on: boolean }
foliage_open: Record<string, never>
foliage_spot: { spot_name: string; from: 'page' | 'card' }
my_gak_save: { gak_name: string }
fortune_draw: { card: string }
day_log: { mood: number; went_out: boolean; card_hit: boolean | null }
today_icon: { icon: string }
saju_input: { with_time: boolean }
saju_view: { scene: string; score: number; strength: string; top_element: string }
game_start: { again: boolean; logged_in: boolean; wind_ms: number; theme: 'basic' | Holiday['key'] }
game_round: { round: number; score: number; logged_in: boolean }
game_over: { round: number; score: number; best: boolean; drops: number }
toss_intro_start: Record<string, never>
install_banner_close: Record<string, never>
}
/** 이벤트 목록은 앱과 같이 쓴다 (shared/lib/analytics.ts, docs/이벤트_추적.md) */
type Events = SharedEvents<SheetType>
type SheetType = Exclude<SheetState, null>['type']
@@ -55,50 +12,6 @@ declare global {
}
}
/** GA 에 찍히는 이벤트 이름 (한국어). 코드에서는 왼쪽 키로 부른다 */
const GA_NAME: Record<keyof Events, string> = {
view_gak: '각_보기',
select_content: '글_열기',
share: '공유',
login: '로그인',
sign_up: '회원가입',
region_change: '지역_변경',
install_banner_view: '설치배너_노출',
install_click: '설치_누름',
install_choice: '설치_선택',
install_done: '설치_완료',
app_launch: '앱_실행',
boot_stuck: '첫화면_멈춤',
sheet_open: '창_열기',
like: '좋아요',
comment: '댓글',
talk_comment: '이야기_댓글',
report: '신고',
block: '차단',
terms_agree: '약관_동의',
talk_post: '이야기_올림',
feed_item_view: '피드_항목_노출',
hero_day_switch: '오늘내일_전환',
tomorrow_to_today: '내일에서_오늘로',
search_landing: '검색_유입',
shorts_open: '쇼츠_열기',
shorts_view: '쇼츠_보기',
shorts_sound: '쇼츠_소리',
foliage_open: '단풍지도_열기',
foliage_spot: '단풍명소_보기',
my_gak_save: '내각_저장',
fortune_draw: '타로_뽑기',
day_log: '하루_기록',
today_icon: '오늘아이콘_누름',
saju_input: '사주_입력',
saju_view: '사주_결과',
game_start: '게임_시작',
game_round: '게임_라운드',
game_over: '게임_끝',
toss_intro_start: '토스소개_시작',
install_banner_close: '설치배너_닫기',
}
export function track<E extends keyof Events>(event: E, params: Events[E]) {
if (import.meta.env.DEV) return
window.gtag?.('event', GA_NAME[event], params)
+10 -2
View File
@@ -2,7 +2,7 @@
"expo": {
"name": "날씨각",
"slug": "nalssigak",
"version": "1.0.0",
"version": "1.1.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "nalssigak",
@@ -55,7 +55,15 @@
"locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요."
}
],
"@react-native-google-signin/google-signin"
"@react-native-google-signin/google-signin",
[
"expo-image-picker",
{
"photosPermission": "동네 이야기에 사진을 붙이려고 사진 앨범을 써요.",
"cameraPermission": false,
"microphonePermission": false
}
]
],
"experiments": {
"typedRoutes": true,
+2
View File
@@ -16,6 +16,7 @@
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-image": "~57.0.5",
"expo-image-picker": "~57.0.20",
"expo-linear-gradient": "~57.0.2",
"expo-linking": "~57.0.12",
"expo-location": "~57.0.21",
@@ -37,6 +38,7 @@
"react-native-svg": "15.15.4",
"react-native-view-shot": "5.1.0",
"react-native-web": "~0.21.0",
"react-native-webview": "13.16.1",
"react-native-worklets": "0.10.1",
"tailwindcss": "^4.3.3",
"uniwind": "^1.12.2"
+18
View File
@@ -0,0 +1,18 @@
import { Tabs } from 'expo-router/tabs';
import { TabBar } from '@/components/tab-bar';
import { TopBar } from '@/components/top-bar';
/** 아래 탭 다섯 개. 사주·게임 같은 화면은 탭 밖(루트 스택)에서 연다 */
export default function TabsLayout() {
return (
<Tabs initialRouteName="index" tabBar={(props) => <TabBar {...props} />} screenOptions={{ header: () => <TopBar />, sceneStyle: { backgroundColor: 'transparent' } }}>
{/* 메인인 오늘 탭을 가운데에 */}
<Tabs.Screen name="sky" />
<Tabs.Screen name="gak" />
<Tabs.Screen name="index" />
<Tabs.Screen name="week" />
<Tabs.Screen name="season" />
</Tabs>
);
}
File renamed without changes.
+178
View File
@@ -0,0 +1,178 @@
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { PostType } from '@nalssigak/shared/api/client/types.gen';
import { kst, loadOf } from '@nalssigak/shared/lib';
import { atSlot, PREVIEW } from '@nalssigak/shared/lib/today';
import { useQuery } from '@tanstack/react-query';
import { router, useLocalSearchParams } from 'expo-router';
import { Fragment, useEffect, useRef, type ReactNode } from 'react';
import { RefreshControl, ScrollView, View, type LayoutRectangle } from 'react-native';
import { FoliageCard } from '@/components/foliage/foliage-card';
import { MyGakRow } from '@/components/my-gak/my-gak';
import { isAppPost, PostCard, PostCardSkel } from '@/components/post/post-card';
import { ShortsRail } from '@/components/shorts/rail';
import { Composer, TalkPost } from '@/components/talk/talk';
import { GakCard } from '@/components/today/gak-card';
import { Hero } from '@/components/today/hero';
import { TodayIcons } from '@/components/today/icons';
import { SeasonBand } from '@/components/today/rails';
import { StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useFoliage } from '@/lib/foliage';
import { fromShare } from '@/lib/my-gak';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
import { useTopicTalks } from '@/lib/talk';
// 사람 글은 포스트 두 장마다 한 장씩 최신순으로 끼운다
const TALK_EVERY = 2;
type Spot = { item: 'talk' | 'event'; position: number; y: number; h: number };
/** 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보일 때 한 번 GA 로 보낸다 (웹 Seen) */
function useSeen() {
const spots = useRef(new Map<string, Spot>());
const sent = useRef(new Set<string>());
const view = useRef({ y: 0, h: 0 });
const check = () => {
const { y, h } = view.current;
if (!h) return;
for (const [key, s] of spots.current) {
if (sent.current.has(key) || !s.h) continue;
const shown = Math.min(y + h, s.y + s.h) - Math.max(y, s.y);
if (shown < s.h / 2) continue;
sent.current.add(key);
track('feed_item_view', { item_type: s.item, position: s.position });
}
};
const at = (item: Spot['item'], position: number) => (l: LayoutRectangle) => {
spots.current.set(`${item}:${position}`, { item, position, y: l.y, h: l.height });
check();
};
const onScroll = (y: number, h: number) => {
view.current = { y, h };
check();
};
return { at, onScroll };
}
export default function TodayScreen() {
const { region } = useRegion();
const feed = useQuery(getFeedOptions({ query: { region: region.code } }));
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }));
const { preview } = useSky();
const f = feed.data;
const posts = (f?.posts ?? []).filter(isAppPost);
const stories = atSlot(f?.stories ?? [], preview);
const sloted = preview != null && stories !== f?.stories;
const bands = f?.bands;
const nowAt = f?.hero?.now_at;
const load = loadOf(feed);
const talkList = useTopicTalks();
const talks = talkList.talks;
const talkAt = (i: number) => ((i + 1) % TALK_EVERY === 0 ? talks[(i + 1) / TALK_EVERY - 1] : undefined);
const talkFrom = Math.floor(posts.length / TALK_EVERY);
const eventNo = new Map(posts.filter((p) => p.post_type === PostType.EVENT).map((p, n) => [p.post_id, n + 1]));
const seen = useSeen();
const { inSeason } = useFoliage();
const scroll = useRef<ScrollView>(null);
const myGakY = useRef(0);
const { open } = useSheet();
const { my } = useLocalSearchParams<{ my?: string }>();
// 친구가 보낸 내 각 링크(?my=...)로 들어오면 내 동네 기준으로 보여 준다
useEffect(() => {
if (!my) return;
router.setParams({ my: undefined });
const g = fromShare(my);
if (g) open({ type: 'mix', shared: g });
}, [my, open]);
const refresh = () => Promise.all([feed.refetch(), today.refetch(), talkList.refetch()]);
// 웹처럼 9번째 글 뒤에 계절 이야기 띠를 넣고, 글이 모자라면 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null]];
return (
// 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다
<ScrollView
ref={scroll}
key={region.code}
contentContainerClassName="pb-6"
refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />}
style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}
keyboardShouldPersistTaps="handled"
scrollEventThrottle={200}
onLayout={(e) => seen.onScroll(0, e.nativeEvent.layout.height)}
onScroll={(e) => seen.onScroll(e.nativeEvent.contentOffset.y, e.nativeEvent.layoutMeasurement.height)}
>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<TodayIcons foliage={inSeason} onMyGak={() => scroll.current?.scrollTo({ y: myGakY.current, animated: true })} />
<ShortsRail />
<Composer />
{/* 아이콘 줄 '내 각'이 여기로 내려온다 */}
<View onLayout={(e) => (myGakY.current = e.nativeEvent.layout.y)}>
<MyGakRow />
</View>
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
{stories.some((g) => g.active) ? (
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
) : load === 'loading' ? (
<PostCardSkel />
) : (
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} boxClassName="inset-x-3 top-3 bottom-1" />
)}
{load === 'loading' && (
<>
<PostCardSkel />
<PostCardSkel />
</>
)}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
{load !== 'loading' && !posts.length && (
<StateBox
load="ready"
empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'}
hold={
<>
<PostCardSkel />
<PostCardSkel />
</>
}
boxClassName="inset-x-3 top-3.5"
/>
)}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
{posts.map((p, i) => {
const t = talkAt(i);
const ev = eventNo.get(p.post_id);
return (
<Fragment key={p.post_id}>
{ev ? (
<View onLayout={(e) => seen.at('event', ev)(e.nativeEvent.layout)}>
<PostCard post={p} />
</View>
) : (
<PostCard post={p} />
)}
{bandAt.find(([at]) => at === i + 1)?.[1]}
{t && (
<View onLayout={(e) => seen.at('talk', (i + 1) / TALK_EVERY)(e.nativeEvent.layout)}>
<TalkPost key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
</View>
)}
</Fragment>
);
})}
{/* 포스트가 모자라 끼울 자리가 없던 사람 글은 맨 뒤에 */}
{feed.isSuccess &&
talks.slice(talkFrom).map((t, n) => (
<View key={t.talk_id} onLayout={(e) => seen.at('talk', talkFrom + n + 1)(e.nativeEvent.layout)}>
<TalkPost t={t} />
</View>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</ScrollView>
);
}
File renamed without changes.
File renamed without changes.
@@ -9,7 +9,7 @@ import { DayStrip, EventRow, PickCard, PlaceCard, RankRow } from '@/components/w
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 { shareView } from '@/lib/share-image';
import { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
// 불러오는 동안에도 탭 줄 높이를 지키려고 같은 칩을 미리 그린다
@@ -46,6 +46,7 @@ export default function WeekScreen() {
const placeLoad = sel ? loadOf(places) : weekLoad === 'loading' ? 'loading' : 'ready';
const refresh = () => Promise.all([week.refetch(), events.refetch(), ranking.refetch(), sel ? places.refetch() : null]);
const shareView = useShare();
const pickShot = useRef<View>(null);
// 고른 날 추천 카드를 이미지로
const sendPlan = () => {
+7 -11
View File
@@ -3,7 +3,7 @@ import { BagelFatOne_400Regular } from '@expo-google-fonts/bagel-fat-one';
import { GowunBatang_400Regular } from '@expo-google-fonts/gowun-batang';
import { Jua_400Regular, useFonts } from '@expo-google-fonts/jua';
import { QueryClientProvider } from '@tanstack/react-query';
import { Tabs } from 'expo-router/tabs';
import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import { StatusBar } from 'expo-status-bar';
import { useEffect } from 'react';
@@ -11,11 +11,10 @@ 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';
import { LevelWatcher } from '@/lib/level';
import { queryClient } from '@/lib/query-client';
import { RegionProvider } from '@/lib/region';
import { SkyProvider, useSky } from '@/lib/sky';
@@ -28,14 +27,10 @@ function Shell() {
<View className="flex-1">
<SkyBg />
<StatusBar style={kind === 'night' ? 'light' : 'dark'} />
<Tabs initialRouteName="index" tabBar={(props) => <TabBar {...props} />} screenOptions={{ header: () => <TopBar />, sceneStyle: { backgroundColor: 'transparent' } }}>
{/* 메인인 오늘 탭을 가운데에 */}
<Tabs.Screen name="sky" />
<Tabs.Screen name="gak" />
<Tabs.Screen name="index" />
<Tabs.Screen name="week" />
<Tabs.Screen name="season" />
</Tabs>
{/* 탭 묶음 위에 사주·게임 같은 탭 밖 화면이 쌓인다. 하늘 배경이 비치게 화면 바탕은 투명 */}
<Stack screenOptions={{ headerShown: false, contentStyle: { backgroundColor: 'transparent' } }}>
<Stack.Screen name="(tabs)" />
</Stack>
<FirstLoad />
</View>
);
@@ -53,6 +48,7 @@ export default function RootLayout() {
<AuthProvider>
<RegionProvider>
<SheetProvider>
<LevelWatcher />
<Shell />
</SheetProvider>
</RegionProvider>
+85
View File
@@ -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<Filter>('all');
const [sel, setSel] = useState<string | null>(params.spot ?? null);
const mapRef = useRef<FoliageMapHandle>(null);
const shotRef = useRef<View>(null);
const shareView = useShare();
const ink = String(useCSSVariable('--color-ink'));
const { width, height: winH } = useWindowDimensions();
// 지도는 스크롤 밖에 고정: 가로만큼 정사각형, 화면이 낮으면 화면 높이의 45%까지
const mapH = Math.max(280, Math.min(width * 1.05, winH * 0.45, 560));
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter]);
useEffect(() => track('foliage_open', {}), []);
useEffect(() => {
if (sel) track('foliage_spot', { spot_name: sel, from: 'page' });
}, [sel]);
const chosen = spots.find((m) => m.name === sel);
const peakCount = spots.filter((m) => m.stage === 'peak').length;
const title = headline(spots);
const pick = (m: Spot) => {
setSel(m.name);
mapRef.current?.focus(m);
};
const share = () => void shareView(shotRef, { title: chosen ? `${chosen.name} 단풍` : '단풍 지도', message: `${title} · 날씨각 단풍 지도 ${SITE_URL}/foliage` });
return (
<View className="flex-1">
<ScreenHeader
title="단풍 지도"
right={
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="단풍 지도 보내기" className="size-10 items-center justify-center">
<SendIcon size={24} color={ink} />
</Pressable>
}
/>
<View className="px-4 pt-1 pb-2">
<View className="flex-row items-center gap-1">
<Ic name="maple" size={16} />
<Text className="text-[13px] font-extrabold text-ink2">{`단풍 지도 · ${md(today)}`}</Text>
</View>
<Text className="mt-0.5 font-jua text-[24px] leading-tight text-ink">{title}</Text>
</View>
{/* 보내기는 지금 보이는 지도 그대로 찍어 보낸다 (웹은 따로 만든 공유 그림) */}
<View ref={shotRef} collapsable={false}>
<FoliageMap ref={mapRef} spots={shown} sel={sel} onSelect={setSel} height={mapH} />
</View>
<ChosenBar chosen={chosen} legendColor={ink} />
<ScrollView className="flex-1" contentContainerClassName="pb-8">
<Chips items={FILTERS} value={filter} onChange={setFilter} />
<SpotList spots={shown} sel={sel} onPick={pick} />
<Text className="px-5 pt-4 text-[11.5px] leading-relaxed font-semibold text-ink3">
{`출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요${peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}`}
</Text>
</ScrollView>
</View>
);
}
+98
View File
@@ -0,0 +1,98 @@
import { getAccessToken } from '@nalssigak/shared/api/auth';
import { router } from 'expo-router';
import { useRef, useState } from 'react';
import { ActivityIndicator, Linking, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
import { ScreenHeader } from '@/components/screen-header';
import { Text } from '@/components/text';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
const SITE_ORIGIN = new URL(SITE_URL).origin;
/** 게임 웹뷰는 날씨각 사이트 안에서만 움직인다. 다른 주소(외부 링크)는 휴대폰 브라우저로 연다 */
function stayOnSite(url: string) {
if (url.startsWith(`${SITE_ORIGIN}/`) || url === SITE_ORIGIN || url === 'about:blank') return true;
if (/^https?:/.test(url)) Linking.openURL(url).catch((e: unknown) => console.warn('[game] 외부 주소를 열지 못함', url, e));
return false;
}
/**
* 웹 페이지가 뜨기 전에 넣는 스크립트: 앱의 지역·로그인을 웹 저장소에 옮기고,
* 게임 화면을 떠나는 이동(뒤로 버튼)과 '로그인하면 …' 버튼은 앱으로 알린다 (웹 구글 로그인은 앱 안 웹뷰에서 막힌다).
* 갱신 토큰은 넘기지 않는다: 웹이 갱신하면 앱이 가진 갱신 토큰이 쓸모없어질 수 있다.
* 날씨각 사이트에서 열렸을 때만 토큰을 넣는다 (다른 곳으로 넘어가면 아무것도 하지 않는다).
*/
function bridge(region: unknown, token: string | null) {
return `(function () {
if (location.origin !== ${JSON.stringify(SITE_ORIGIN)}) return;
try {
localStorage.setItem('nalssigak.b.region', ${JSON.stringify(JSON.stringify(region))});
${token ? `localStorage.setItem('nalssigak.accessToken', ${JSON.stringify(token)});` : `localStorage.removeItem('nalssigak.accessToken');`}
localStorage.removeItem('nalssigak.refreshToken');
} catch (e) {}
var post = function (t) { window.ReactNativeWebView.postMessage(t); };
var check = function () { if (location.pathname !== '/game') post('leave'); };
var push = history.pushState, replace = history.replaceState;
history.pushState = function () { push.apply(this, arguments); check(); };
history.replaceState = function () { replace.apply(this, arguments); check(); };
window.addEventListener('popstate', check);
document.addEventListener('click', function (e) {
var b = e.target && e.target.closest && e.target.closest('button');
if (b && b.textContent && b.textContent.trim().indexOf('로그인') === 0) { e.preventDefault(); e.stopPropagation(); post('login'); }
}, true);
})();
true;`;
}
/** 구름 합치기 게임: 웹 /game 을 그대로 띄운다 (물리 엔진·캔버스라 웹과 같은 화면, 사용자 결정 11/04) */
export default function GameScreen() {
const { region } = useRegion();
const { loggedIn } = useAuth();
const { open } = useSheet();
const { top, bottom } = useSafeAreaInsets();
const [failed, setFailed] = useState(false);
const left = useRef(false);
const onMessage = (e: WebViewMessageEvent) => {
if (e.nativeEvent.data === 'leave' && !left.current) {
left.current = true;
if (router.canGoBack()) router.back();
else router.replace('/');
}
if (e.nativeEvent.data === 'login') open({ type: 'login' });
};
if (failed)
return (
<View className="flex-1">
<ScreenHeader title="구름 합치기" />
<Text className="mx-6 mt-10 text-center text-[15px] font-bold text-ink2">게임을 불러오지 못했어요. 인터넷 연결을 확인하고 다시 들어와 주세요.</Text>
</View>
);
return (
<View className="flex-1 bg-[#cfe9ff]" style={{ paddingTop: top, paddingBottom: bottom }}>
{/* 로그인하면 토큰을 다시 넣어야 해서 로그인 여부로 새로 띄운다 */}
<WebView
key={`${region.code}:${loggedIn}`}
source={{ uri: `${SITE_URL}/game` }}
originWhitelist={[SITE_ORIGIN]}
onShouldStartLoadWithRequest={(req) => stayOnSite(req.url)}
injectedJavaScriptBeforeContentLoaded={bridge(region, getAccessToken())}
onMessage={onMessage}
onError={() => setFailed(true)}
startInLoadingState
renderLoading={() => <ActivityIndicator style={{ position: 'absolute', top: '45%', alignSelf: 'center' }} />}
overScrollMode="never"
bounces={false}
setSupportMultipleWindows={false}
style={{ backgroundColor: 'transparent' }}
/>
</View>
);
}
-71
View File
@@ -1,71 +0,0 @@
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
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 { isAppPost, 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';
import { useRegion } from '@/lib/region';
import { useSky } from '@/lib/sky';
export default function TodayScreen() {
const { region } = useRegion();
const feed = useQuery(getFeedOptions({ query: { region: region.code } }));
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }));
const { preview } = useSky();
const f = feed.data;
const posts = (f?.posts ?? []).filter(isAppPost);
const stories = atSlot(f?.stories ?? [], preview);
const sloted = preview != null && stories !== f?.stories;
const bands = f?.bands;
const nowAt = f?.hero?.now_at;
const load = loadOf(feed);
const refresh = () => Promise.all([feed.refetch(), today.refetch()]);
// 웹처럼 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
const bandAt: [number, ReactNode][] = [
[3, bands?.events?.length ? <EventsBand events={bands.events} /> : null],
[6, bands?.top5?.length ? <TopBand items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
[9, bands?.season?.length ? <SeasonBand news={bands.season} /> : null],
];
return (
// 지역마다 새로 그려 넘긴 슬라이드 위치가 남지 않게 한다
<ScrollView key={region.code} contentContainerClassName="pb-6" refreshControl={<RefreshControl refreshing={feed.isRefetching && !feed.isPlaceholderData} onRefresh={refresh} />} style={{ opacity: feed.isPlaceholderData ? 0.6 : 1 }}>
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more="/gak" />
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} boxClassName="inset-x-3 top-3 bottom-1" />}
{load === 'loading' && (
<>
<PostCardSkel />
<PostCardSkel />
</>
)}
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다. 다시 시도는 위 각 줄에 한 번만 */}
{load !== 'loading' && !posts.length && (
<StateBox
load="ready"
empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'}
hold={
<>
<PostCardSkel />
<PostCardSkel />
</>
}
boxClassName="inset-x-3 top-3.5"
/>
)}
{posts.map((p, i) => (
<Fragment key={p.post_id}>
<PostCard post={p} />
{bandAt.find(([at]) => at === i + 1)?.[1]}
</Fragment>
))}
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
</ScrollView>
);
}
+63
View File
@@ -0,0 +1,63 @@
import { useLocalSearchParams } from 'expo-router';
import { useMemo, useRef, useState } from 'react';
import { ScrollView, View } from 'react-native';
import { BirthForm } from '@/components/saju/birth-form';
import { OpenTarget } from '@/components/saju/parts';
import { Reading } from '@/components/saju/reading';
import { ScreenHeader } from '@/components/screen-header';
import { Text } from '@/components/text';
import { useAccountBirth, useBirth } from '@/lib/saju-birth';
type Pos = { base: number | null; panel: number | null; done: boolean };
function tryScroll(p: Pos, view: ScrollView | null) {
if (p.done || p.base == null || p.panel == null || !view) return;
p.done = true;
view.scrollTo({ y: Math.max(0, p.base + p.panel - 12), animated: true });
}
/** 날씨 사주(/saju): 오늘 점수와 할 일, 내 기운, 레벨로 열리는 칸. ?open=saju_love 처럼 열면 그 칸으로 내려간다 (웹 SajuPage, #hash) */
export default function SajuScreen() {
const params = useLocalSearchParams<{ open?: string }>();
const birth = useBirth();
const loading = useAccountBirth();
const [editing, setEditing] = useState(false);
const scroll = useRef<ScrollView>(null);
// 결과 묶음의 위치와 그 안에서 연 칸의 위치를 둘 다 알아야 내려갈 수 있다 (어느 쪽이 먼저 잡힐지 모른다)
const pos = useRef<Pos>({ base: null, panel: null, done: false });
const target = useMemo(
() => ({
id: params.open,
onLayout: (y: number) => {
pos.current.panel = y;
tryScroll(pos.current, scroll.current);
},
}),
[params.open],
);
return (
<View className="flex-1">
<ScreenHeader title="날씨 사주" />
<ScrollView ref={scroll} contentContainerClassName="pb-8" keyboardShouldPersistTaps="handled">
{loading && !birth ? (
<Text className="px-4 py-16 text-center font-semibold text-ink2">내 생년월일을 불러오는 중이에요…</Text>
) : !birth || editing ? (
<BirthForm initial={birth} onDone={() => setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} />
) : (
<View
onLayout={(e) => {
pos.current.base = e.nativeEvent.layout.y;
tryScroll(pos.current, scroll.current);
}}
>
<OpenTarget value={target}>
<Reading birth={birth} onEdit={() => setEditing(true)} />
</OpenTarget>
</View>
)}
</ScrollView>
</View>
);
}
+127
View File
@@ -0,0 +1,127 @@
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { ShortItem } from '@nalssigak/shared/api/client/types.gen';
import { useQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { router, useLocalSearchParams } from 'expo-router';
import { useEffect, useRef, useState } from 'react';
import { FlatList, Pressable, View, type ViewToken } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { ShortPlayer, type PlayerHandle } from '@/components/shorts/player';
import { thumb } from '@/components/shorts/rail';
import { Text } from '@/components/text';
import { track } from '@/lib/analytics';
const BAR = 48;
/** 쇼츠 화면: 그 영상부터 위아래로 넘겨 본다. 보이는 영상과 앞뒤만 소리 없이 미리 띄우고, 누르면 소리 켜기·끄기 (웹 ShortsPage) */
export default function ShortsScreen() {
const { id } = useLocalSearchParams<{ id?: string }>();
const q = useQuery(listShortsOptions());
const { top, bottom } = useSafeAreaInsets();
// 처음 들어온 영상만 시작점으로 쓴다
const [firstId] = useState(id);
const listed = q.data?.items ?? [];
const items: ShortItem[] = firstId && listed.length && !listed.some((s) => s.id === firstId) ? [{ id: firstId, title: '' }, ...listed] : listed;
const start = Math.max(0, items.findIndex((s) => s.id === firstId));
const [at, setAt] = useState(start);
const [sound, setSound] = useState(false);
const [ready, setReady] = useState<ReadonlySet<number>>(new Set());
const [box, setBox] = useState({ w: 0, h: 0 });
const players = useRef(new Map<number, PlayerHandle>());
const soundRef = useRef(false);
const atRef = useRef(start);
useEffect(() => {
if (firstId) track('shorts_open', { video_id: firstId });
}, [firstId]);
// 넘어온 영상만 처음부터 다시 틀고 소리를 맞춘다. 앞뒤는 소리만 끈다 (멈추면 유튜브 버튼이 떠서 멈추지 않는다)
useEffect(() => {
for (const [i, p] of players.current) {
if (i === at) {
p.command('seekTo', [0, true]);
p.command(soundRef.current ? 'unMute' : 'mute');
p.command('playVideo');
} else p.command('mute');
}
}, [at]);
// FlatList 는 이 함수가 바뀌면 안 되어 처음 한 번만 만든다
const [onViewable] = useState(() => ({ viewableItems }: { viewableItems: ViewToken<ShortItem>[] }) => {
const i = viewableItems[0]?.index;
if (i == null || i === atRef.current) return;
atRef.current = i;
setAt(i);
const s = viewableItems[0].item;
track('shorts_view', { video_id: s.id, index: i });
});
const toggleSound = () => {
const on = !soundRef.current;
soundRef.current = on;
setSound(on);
track('shorts_sound', { on });
players.current.get(at)?.command(on ? 'unMute' : 'mute');
};
const close = () => (router.canGoBack() ? router.back() : router.replace('/'));
// 9:16 을 칸 안에 맞춘다
const w = Math.min(box.w, (box.h * 9) / 16);
const h = (w * 16) / 9;
return (
<View className="flex-1 bg-[#1d2233]" style={{ paddingTop: top, paddingBottom: bottom }}>
{!!items[at] && <Image source={{ uri: thumb(items[at].id) }} style={{ position: 'absolute', inset: 0, opacity: 0.7, transform: [{ scale: 1.25 }] }} blurRadius={40} contentFit="cover" />}
<View className="absolute inset-0 bg-black/35" />
<View className="flex-row items-center justify-between px-3" style={{ height: BAR }}>
<Pressable onPress={close} hitSlop={8} accessibilityRole="button" accessibilityLabel="닫기" className="size-9 items-center justify-center rounded-full bg-white/15">
<Svg viewBox="0 0 24 24" width={18} height={18} fill="none" stroke="#fff" strokeWidth={2.4} strokeLinecap="round">
<Path d="M6 6l12 12M18 6L6 18" />
</Svg>
</Pressable>
<Pressable onPress={toggleSound} accessibilityRole="button" accessibilityState={{ selected: sound }} className="h-9 justify-center rounded-full bg-white/15 px-3.5">
<Text className="text-[13px] font-bold text-white">{sound ? '소리 끄기' : '소리 켜기'}</Text>
</Pressable>
</View>
<View className="flex-1" onLayout={(e) => setBox({ w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height })}>
{box.h > 0 && items.length > 0 && (
<FlatList
data={items}
keyExtractor={(s) => s.id}
pagingEnabled
showsVerticalScrollIndicator={false}
initialScrollIndex={start}
getItemLayout={(_, i) => ({ length: box.h, offset: box.h * i, index: i })}
onViewableItemsChanged={onViewable}
viewabilityConfig={{ itemVisiblePercentThreshold: 60 }}
windowSize={3}
renderItem={({ item: s, index: i }) => (
<View style={{ height: box.h }} className="items-center justify-center">
<View style={{ width: w, height: h }}>
<Image source={{ uri: thumb(s.id) }} style={{ position: 'absolute', inset: 0 }} contentFit="cover" />
{/* 릴스처럼 앞뒤 영상을 소리 없이 미리 받아 둔다. 첫 장면 전엔 표지가 보이게 숨긴다 */}
{Math.abs(i - at) <= 1 && (
<View pointerEvents="none" style={{ position: 'absolute', inset: 0, opacity: ready.has(i) ? 1 : 0 }}>
<ShortPlayer
id={s.id}
ref={(p) => {
if (p) players.current.set(i, p);
else players.current.delete(i);
}}
onPlaying={() => setReady((r) => (r.has(i) ? r : new Set(r).add(i)))}
/>
</View>
)}
{/* 누르면 소리 켜기·끄기, 위아래로 밀면 목록이 넘어간다 */}
<Pressable onPress={toggleSound} accessibilityLabel={sound ? '소리 끄기' : '소리 켜기'} style={{ position: 'absolute', inset: 0 }} />
</View>
</View>
)}
/>
)}
</View>
</View>
);
}
+2
View File
@@ -0,0 +1,2 @@
// 아이콘 줄 '쇼츠'(/shorts)는 첫 영상부터
export { default } from './[id]';
+71
View File
@@ -0,0 +1,71 @@
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen';
import { router, useLocalSearchParams } from 'expo-router';
import { FlatList, Pressable, RefreshControl, ScrollView, View } from 'react-native';
import { ScreenHeader } from '@/components/screen-header';
import { Composer, TalkCard } from '@/components/talk/talk';
import { Text } from '@/components/text';
import { Sec } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { useSheet } from '@/lib/sheet';
import { openTopics, TOPICS, useMyTalks, useTopicTalks } from '@/lib/talk';
type Tab = TalkTopic | 'all' | 'mine';
/** 주제별 사람 글: 위 주제 탭(한 줄 가로로 밀기, 끝에 '내 글'), 아래 글 목록. ?topic= · ?mine=1 로 연다 (웹 TalkPage) */
export default function TalkScreen() {
const params = useLocalSearchParams<{ topic?: string; mine?: string }>();
const { loggedIn } = useAuth();
const { open } = useSheet();
const raw = Number(params.topic);
const tab: Tab = params.mine ? 'mine' : TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : 'all';
const topicList = useTopicTalks(tab === 'all' || tab === 'mine' ? undefined : tab);
const mineList = useMyTalks(tab === 'mine' && loggedIn);
const { talks, loaded, more, loadMore } = tab === 'mine' ? mineList : topicList;
const tabs: (readonly [Tab, string])[] = [['all', '전체'], ...openTopics(), ['mine', '내 글']];
const go = (k: Tab) => router.setParams(k === 'mine' ? { mine: '1', topic: undefined } : k === 'all' ? { mine: undefined, topic: undefined } : { mine: undefined, topic: String(k) });
const head = (
<View>
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
<View accessibilityRole="tablist" accessibilityLabel="글 주제">
<ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerClassName="gap-1.5 px-4 pb-1">
{tabs.map(([k, label]) => (
<Pressable key={label} onPress={() => go(k)} accessibilityRole="tab" accessibilityState={{ selected: tab === k }} className={`rounded-full px-3 py-1.5 ${tab === k ? 'bg-ink-btn' : 'bg-card'}`}>
<Text className={`text-[13px] font-extrabold ${tab === k ? 'text-white' : 'text-ink2'}`}>{label}</Text>
</Pressable>
))}
</ScrollView>
</View>
<Composer />
{tab === 'mine' && !loggedIn ? (
<Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">
로그인하면 내가 쓴 글을 모아 볼 수 있어요.{' '}
<Text onPress={() => open({ type: 'login' })} className="font-extrabold text-orange">
로그인
</Text>
</Text>
) : (
loaded && !talks.length && <Text className="mx-4 mt-6 text-center text-[14px] font-semibold text-ink3">{tab === 'mine' ? '아직 쓴 글이 없어요. 위 칸에서 첫 글을 써 주세요.' : '아직 이 주제 글이 없어요. 위 칸에서 첫 글을 써 주세요.'}</Text>
)}
</View>
);
return (
<View className="flex-1">
<ScreenHeader title="동네 이야기" />
<FlatList
data={talks}
keyExtractor={(t) => `${t.talk_id}:${t.liked}:${t.like_count}`}
renderItem={({ item }) => <TalkCard t={item} />}
ListHeaderComponent={head}
contentContainerClassName="pb-8"
keyboardShouldPersistTaps="handled"
// 목록 끝이 가까워지면 다음 쪽을 받는다 (글이 많아도 버튼 없이 이어서)
onEndReached={() => more && loadMore()}
onEndReachedThreshold={1}
refreshControl={tab !== 'mine' ? <RefreshControl refreshing={topicList.refetching} onRefresh={() => topicList.refetch()} /> : undefined}
/>
</View>
);
}
@@ -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<string | null>(null);
const [index, setIndex] = useState(0);
const pts = useMemo(() => spread(peak.map((m) => ({ m, x: m.x * W, y: m.y * W, r: ICON_R }))), [peak, W]);
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W]);
const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size]);
useEffect(() => {
if (picked) track('foliage_spot', { spot_name: picked, from: 'card' });
}, [picked]);
if (!inSeason) return null;
const toggle = (name: string) => setPicked(name === picked ? null : name);
// 잎이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
const tapMap = (e: GestureResponderEvent) => {
const best = nearest(pts, e.nativeEvent.locationX, e.nativeEvent.locationY);
setPicked(best && best !== picked ? best : null);
};
const onLayout = (e: LayoutChangeEvent) => setW(e.nativeEvent.layout.width);
const sel = peak.find((m) => m.name === picked);
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
const ranked = rankNow(spots).slice(0, RANK_N);
const caption = peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined;
const pageH = W + 8 + BAR_H;
const mapPage = (
<View className="overflow-hidden" style={{ width: W, height: pageH }}>
<Pressable onPress={tapMap} accessibilityLabel="단풍 지도, 지금 절정인 곳" style={{ width: W, height: W, transform: [{ translateX: W * SHIFT }], backgroundColor: PAPER }}>
<MapImage style={{ left: 0, top: 0, width: W, height: W }} />
{provs.map((v) => (
<Province key={v.name} name={v.name} x={v.x} y={v.y} />
))}
{pts.map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === picked} />
))}
{peak.map((m) => (
<Label key={m.name} m={m} at={labelAt[m.name]} onPress={() => toggle(m.name)} onLayout={measure(m.name)} accessibilityLabel={`${m.name} 정보 보기`} />
))}
</Pressable>
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 잎을 가리지 않게 */}
{sel ? (
<View className="mt-2 flex-row items-center gap-3 rounded-[16px] bg-white px-3" style={{ height: BAR_H, boxShadow: 'inset 0 -3px 0 rgba(40,48,74,0.08)' }}>
<Ic name={sel.kind} size={32} />
<View className="min-w-0 flex-1">
<Text numberOfLines={1} className="font-jua text-[18px] leading-tight" style={{ color: MAP_INK }}>
{sel.name}
</Text>
<Text numberOfLines={1} className="text-[12px] font-bold" style={{ color: MAP_INK3 }}>
{`${sel.region.split(' ')[0]} · 절정 예상 ${md(sel.peak)}`}
</Text>
</View>
<Pressable onPress={() => goMap(sel.name)} accessibilityRole="link" className="rounded-full px-3 py-1.5" style={{ backgroundColor: MAP_INK }}>
<Text className="text-[12.5px] font-extrabold text-white">지도에서 보기 ›</Text>
</Pressable>
</View>
) : (
<View className="mt-2 items-start" style={{ height: BAR_H }}>
<Legend color={MAP_INK} />
</View>
)}
</View>
);
const rankPage = (
<View className="pl-1" style={{ width: W, height: pageH }}>
<Text className="font-jua text-[20px] leading-tight" style={{ color: MAP_INK }}>
지금 가기 좋은 곳
</Text>
<Text className="mt-0.5 text-[12px] font-bold" style={{ color: MAP_INK3 }}>
절정 예상일이 오늘과 가까운 순서예요
</Text>
<View className="mt-2 flex-1 justify-between">
{ranked.map((m, i) => (
<Pressable key={m.name} onPress={() => goMap(m.name)} accessibilityRole="link" accessibilityLabel={`${i + 1}위 ${m.name}, 절정 예상 ${md(m.peak)}`} className="flex-row items-center gap-2.5 py-1.5">
<Text className="w-6 text-center font-jua text-[22px]" style={{ color: i < 3 ? '#b5321f' : '#9a8f80' }}>
{String(i + 1)}
</Text>
<Ic name={m.kind} size={28} />
<View className="min-w-0 flex-1">
<Text numberOfLines={1} className="text-[15px] font-extrabold" style={{ color: MAP_INK }}>
{m.name}
</Text>
<Text numberOfLines={1} className="text-[12px] font-semibold" style={{ color: MAP_INK3 }}>
{m.region}
</Text>
</View>
<Text className="text-[14px] font-extrabold" style={{ color: MAP_INK, fontVariant: ['tabular-nums'] }}>
{md(m.peak)}
</Text>
</Pressable>
))}
</View>
</View>
);
return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" pinned={{ key: 'foliage_post', post }} caption={caption}>
{/* 밤에도 지도 카드는 밝은 종이 그대로 (웹 b-keep-bg) */}
<View className="px-4 pt-4 pb-3" style={{ backgroundColor: PAPER }}>
<Text className="text-[13px] font-extrabold opacity-75" style={{ color: MAP_INK }}>{`단풍 지도 · ${md(today)}`}</Text>
<Text className="mt-1 font-jua text-[24px] leading-tight" style={{ color: MAP_INK }}>
{headline(spots)}
</Text>
<View className="mt-1" onLayout={onLayout}>
{W > 0 ? (
<Pager width={W} height={pageH} onIndex={setIndex}>
{[mapPage, rankPage]}
</Pager>
) : null}
<View pointerEvents="none" className="absolute top-0 right-0 rounded-full px-[9px] py-[3px]" style={{ zIndex: 4, backgroundColor: 'rgba(30,36,56,0.55)' }} accessibilityElementsHidden>
<Text className="text-xs font-extrabold text-white">{`${index + 1}/2`}</Text>
</View>
</View>
<Pressable onPress={() => goMap()} accessibilityRole="link" className="mt-2 w-full items-center rounded-full bg-white py-2" style={{ boxShadow: 'inset 0 -3px 0 rgba(40,48,74,0.08)' }}>
<Text className="text-[14px] font-extrabold" style={{ color: MAP_INK }}>
지도 크게 보기 ›
</Text>
</Pressable>
</View>
</PostFrame>
);
}
@@ -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<Stage, number> = { peak: ICON_R, first: 4, before: 3, gone: 3 };
const MAX_ZOOM = 5;
const FIT_TOP = 30;
const FIT_BOTTOM = 14;
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3);
const LABEL_FROM = [1, 1.6, 2.5, 3.5];
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 };
const ZOOM_BTNS = [
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const;
export type FoliageMapHandle = { focus: (m: Spot) => void };
type Props = { spots: Spot[]; sel: string | null; onSelect: (name: string | null) => void; height: number; ref?: Ref<FoliageMapHandle> };
/**
* 단풍 지도 페이지의 지도: 두 손가락으로 확대·이동, 한 손가락으로 이동, 누르면 가까운 명소 고르기, 두 번 누르면 확대 (웹 FoliagePage 지도).
* 앱은 지도를 스크롤 밖에 고정해 손짓이 페이지 스크롤과 다투지 않는다
*/
export function FoliageMap({ spots, sel, onSelect, height, ref }: Props) {
const vpRef = useRef<View>(null);
const origin = useRef({ x: 0, y: 0 });
const [box, setBox] = useState({ W: 0, H: 0 });
const [view, setView] = useState<Cam>({ s: 1, tx: 0, ty: 0 });
const viewRef = useRef(view);
useLayoutEffect(() => {
viewRef.current = view;
}, [view]);
const [size, measure] = useLabelSizes();
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<Cam>(() => {
const { W, H } = box;
if (!W || !spots.length) return { s: 1, tx: 0, ty: 0 };
const xs = spots.map((m) => m.x);
const ys = spots.map((m) => m.y);
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
const h = H - FIT_TOP - FIT_BOTTOM;
// 가로는 땅 가운데(LAND_CX)에 맞추되 동·서 끝 명소가 다 들어오게
const half = Math.max(LAND_CX - x0, x1 - LAND_CX) + 0.07;
const s = Math.min(W / (2 * half * W), h / ((y1 - y0) * W));
return { s, tx: W / 2 - LAND_CX * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s };
}, [box, spots]);
const clamp = useCallback(
(v: Cam): Cam => {
const { W, H } = box;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s));
const w = W * s;
// 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게
const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx));
const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty));
return { s, tx, ty };
},
[box, fit],
);
const anim = useRef(0);
const set = useCallback((v: Cam) => {
cancelAnimationFrame(anim.current);
setView(v);
}, []);
const animateTo = useCallback(
(to: Cam) => {
cancelAnimationFrame(anim.current);
const from = viewRef.current;
const target = clamp(to);
const start = performance.now();
const step = (now: number) => {
const k = Math.min(1, (now - start) / 280);
const e = 1 - (1 - k) ** 3;
setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e });
if (k < 1) anim.current = requestAnimationFrame(step);
};
anim.current = requestAnimationFrame(step);
},
[clamp],
);
const zoomAt = useCallback(
(f: number, cx: number, cy: number, smooth = false) => {
const v = viewRef.current;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f));
const k = s / v.s;
const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k });
if (smooth) animateTo(next);
else set(next);
},
[fit, clamp, animateTo, set],
);
const focus = useCallback(
(m: Spot) => {
const { W, H } = box;
const s = Math.max(viewRef.current.s, fit.s * 2.5);
animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s });
},
[box, fit, animateTo],
);
useImperativeHandle(ref, () => ({ focus }), [focus]);
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로. 그 뒤 크기가 바뀌면 지금 화면을 범위 안으로
const started = useRef(false);
const linked = useRef(sel);
useEffect(() => {
if (!box.W) return;
if (started.current) {
set(clamp(viewRef.current));
return;
}
started.current = true;
set(fit);
const m = spots.find((s) => s.name === linked.current);
if (m) focus(m);
}, [box, fit, spots, set, clamp, focus]);
useEffect(() => () => cancelAnimationFrame(anim.current), []);
const pts = useMemo(() => {
const ratio = view.s / fit.s;
const visible = spots.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01);
return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] })));
}, [spots, view, box.W, fit.s, sel]);
const ptsRef = useRef(pts);
useLayoutEffect(() => {
ptsRef.current = pts;
}, [pts]);
const labelAt = useMemo(() => {
const ratio = view.s / fit.s;
const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m));
// 오른쪽 위 +/− 단추 자리는 비운다
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }];
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel);
}, [pts, size, sel, view.s, fit.s, box]);
const provs = useMemo(
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
[view, box.W, pts, labelAt, size],
);
// 손짓 상태: 두 손가락 거리·가운데, 한 손가락 시작점과 움직였는지, 마지막으로 누른 때(두 번 누르기)
const gesture = useRef<{ pinch: { d: number; x: number; y: number } | null; one: { x: number; y: number; moved: boolean } | null; lastTap: number }>({ pinch: null, one: null, lastTap: 0 });
const local = (t: { pageX: number; pageY: number }) => ({ x: t.pageX - origin.current.x, y: t.pageY - origin.current.y });
const pickAt = (x: number, y: number) => {
const best = nearest(ptsRef.current, x, y);
onSelect(best && best !== sel ? best : null);
};
const begin = (e: GestureResponderEvent) => {
const g = gesture.current;
const ts = e.nativeEvent.touches;
if (ts.length >= 2) {
const [a, b] = [local(ts[0]), local(ts[1])];
g.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
g.one = null;
} else if (ts.length === 1) {
g.pinch = null;
g.one = { ...local(ts[0]), moved: false };
}
};
const onGrant = (e: GestureResponderEvent) => {
cancelAnimationFrame(anim.current);
// 지도 칸의 화면 위치: 손가락 좌표(pageX)를 지도 안 좌표로 바꾸는 데 쓴다
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
origin.current = { x: px, y: py };
});
begin(e);
};
const onMove = (e: GestureResponderEvent) => {
const g = gesture.current;
const ts = e.nativeEvent.touches;
if (ts.length >= 2) {
if (!g.pinch) return begin(e);
const [a, b] = [local(ts[0]), local(ts[1])];
const d = Math.hypot(a.x - b.x, a.y - b.y);
const x = (a.x + b.x) / 2;
const y = (a.y + b.y) / 2;
const v = viewRef.current;
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / g.pinch.d));
const k = s / v.s;
set(clamp({ s, tx: x - (g.pinch.x - v.tx) * k, ty: y - (g.pinch.y - v.ty) * k }));
g.pinch = { d, x, y };
return;
}
// 두 손가락에서 한 손가락이 떨어지면 남은 손가락으로 이어서 이동 (누르기로는 안 친다)
if (!g.one || g.pinch) {
if (ts.length === 1) g.one = { ...local(ts[0]), moved: true };
g.pinch = null;
return;
}
const p = local(ts[0]);
if (Math.hypot(p.x - g.one.x, p.y - g.one.y) > 6) g.one.moved = true;
if (!g.one.moved) return;
const v = viewRef.current;
set(clamp({ s: v.s, tx: v.tx + p.x - g.one.x, ty: v.ty + p.y - g.one.y }));
g.one = { ...p, moved: true };
};
const onRelease = (e: GestureResponderEvent) => {
const g = gesture.current;
const tap = g.one && !g.one.moved ? g.one : null;
g.one = null;
g.pinch = null;
if (!tap) return;
// 두 번 누르기: 300ms 안에 또 누르면 확대
if (e.nativeEvent.timestamp - g.lastTap < 300) {
g.lastTap = 0;
zoomAt(2, tap.x, tap.y, true);
} else {
g.lastTap = e.nativeEvent.timestamp;
pickAt(tap.x, tap.y);
}
};
const onEnd = () => {
gesture.current.one = null;
gesture.current.pinch = null;
};
const onLayout = (e: LayoutChangeEvent) => {
const { width, height: h } = e.nativeEvent.layout;
setBox({ W: width, H: h });
vpRef.current?.measure((_x, _y, _w, _h, px, py) => {
origin.current = { x: px, y: py };
});
};
const markers = [...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak'));
return (
<View
ref={vpRef}
onLayout={onLayout}
onStartShouldSetResponder={() => true}
onMoveShouldSetResponder={() => true}
onResponderTerminationRequest={() => false}
onResponderGrant={onGrant}
onResponderMove={onMove}
onResponderRelease={onRelease}
onResponderTerminate={onEnd}
className="overflow-hidden"
style={{ height, backgroundColor: PAPER }}
accessibilityLabel="단풍 지도"
>
{box.W > 0 ? <MapImage style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} /> : null}
{provs.map((v) => (
<Province key={v.name} name={v.name} x={v.x} y={v.y} />
))}
{markers.map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<Label key={m.name} m={m} at={labelAt[m.name]} sel={m.name === sel} onPress={() => onSelect(m.name === sel ? null : m.name)} onLayout={measure(m.name)} accessibilityLabel={`${m.name} 고르기`} />
))}
<View className="absolute top-2.5 right-2.5 gap-2" style={{ zIndex: 4 }}>
{ZOOM_BTNS.map(([t, label, f]) => (
<Pressable key={t} onPress={() => zoomAt(f, box.W / 2, box.H / 2, true)} accessibilityRole="button" accessibilityLabel={label} className="size-9 items-center justify-center rounded-full bg-white" style={{ boxShadow: '0 2px 6px rgba(40,48,74,0.2)' }}>
<Text className="text-[20px] leading-6 font-bold" style={{ color: MAP_INK }}>
{t}
</Text>
</Pressable>
))}
</View>
</View>
);
}
+135
View File
@@ -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<Kind, string> = { maple: '#b5321f', ginkgo: '#8a6508' };
/**
* 지도 그림. 웹은 채도를 빼서(saturate .3) 잎 아이콘이 묻히지 않게 한다.
* 안드로이드는 같은 filter, iOS 는 filter 의 채도를 못 써서 종이색을 반쯤 덮어 옅게 한다
*/
export function MapImage({ style }: { style: StyleProp<ViewStyle> }) {
const android = Platform.OS === 'android';
return (
<View pointerEvents="none" style={[{ position: 'absolute' }, style, android ? { filter: [{ saturate: 0.3 }, { brightness: 1.08 }] } : null]}>
<Image source={MAP_IMAGE} style={{ width: '100%', height: '100%' }} contentFit="contain" accessibilityIgnoresInvertColors />
{!android && <View style={{ position: 'absolute', inset: 0, backgroundColor: PAPER, opacity: 0.5 }} />}
</View>
);
}
const DOT: Record<Exclude<Stage, 'peak'>, { size: number; color: string }> = {
first: { size: 7, color: 'rgba(217,119,46,0.85)' },
before: { size: 5, color: 'rgba(143,138,128,0.6)' },
gone: { size: 5, color: 'rgba(143,138,128,0.6)' },
};
/** 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(big 이면 점을 크게) */
export function StageMark({ m, big }: { m: Spot; big?: boolean }) {
if (m.stage === 'peak') return <Ic name={m.kind} size={big ? 32 : 20} />;
const dot = DOT[m.stage];
const size = big ? 14 : dot.size;
return <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: dot.color }} />;
}
/** 지도 위 점·잎. 고른 명소는 속이 빈 고리만 둘러 옆 명소를 가리지 않게 */
export function Marker({ p, sel }: { p: Pt; sel: boolean }) {
return (
<View pointerEvents="none" className="absolute size-8 items-center justify-center" style={{ left: p.x - 16, top: p.y - 16, zIndex: sel ? 3 : 1 }}>
{sel ? <View className="absolute size-8 rounded-full border-[2.5px]" style={{ borderColor: MAP_INK, backgroundColor: 'rgba(255,255,255,0.3)' }} /> : null}
<StageMark m={p.m} big={sel && p.m.stage !== 'peak'} />
</View>
);
}
/** 시·도 이름: 지도에 옅게 깔리는 글자. 산 무늬 위에서도 읽히게 종이색 번짐을 두른다 */
export function Province({ name, x, y }: { name: string; x: number; y: number }) {
return (
<View pointerEvents="none" className="absolute w-10 items-center" style={{ left: x - 20, top: y - 8 }} accessibilityElementsHidden importantForAccessibility="no-hide-descendants">
<Text className="font-jua text-[13px] leading-4" style={{ color: 'rgba(92,74,54,0.85)', textShadowColor: PAPER, textShadowRadius: 4 }}>
{name}
</Text>
</View>
);
}
/**
* 명소 이름표. 자리를 못 받았으면(at 없음) 숨긴 채 왼쪽 위에 두고 크기만 잰다 (웹 useLabelSize 대신 onLayout).
* tone: 고름(진한 바탕) · 절정(잎 색 글자) · 그 밖(회색 글자)
*/
export function Label({ m, at, sel, onPress, onLayout, accessibilityLabel }: { m: Spot; at?: { left: number; top: number }; sel?: boolean; onPress: () => void; onLayout: (e: LayoutChangeEvent) => void; accessibilityLabel: string }) {
const color = sel ? '#ffffff' : m.stage === 'peak' ? LABEL_INK[m.kind] : '#5b6075';
return (
<Pressable
onPress={onPress}
onLayout={onLayout}
disabled={!at}
hitSlop={{ top: 8, bottom: 8, left: 4, right: 4 }}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
accessibilityElementsHidden={!at}
importantForAccessibility={at ? 'auto' : 'no-hide-descendants'}
className="absolute rounded-[7px] px-[5px] py-px"
style={{
left: at?.left ?? 0,
top: at?.top ?? 0,
opacity: at ? 1 : 0,
zIndex: sel ? 3 : 2,
backgroundColor: sel ? MAP_INK : 'rgba(255,255,255,0.92)',
boxShadow: '0 1px 3px rgba(40,48,74,0.18)',
}}
>
<Text numberOfLines={1} className="text-[11.5px] leading-[15.5px] font-extrabold" style={{ color }}>
{m.name}
</Text>
</Pressable>
);
}
/** 이름표 크기 모으기: Label 의 onLayout 을 받아 이름별 폭·높이. 한 프레임에 한 번만 다시 그린다 */
export function useLabelSizes() {
const [size, setSize] = useState<LabelSize>({});
const acc = useRef<LabelSize>({});
const frame = useRef(0);
const measure = useCallback(
(name: string) => (e: LayoutChangeEvent) => {
const { width: w, height: h } = e.nativeEvent.layout;
const old = acc.current[name];
if (old && Math.abs(old.w - w) < 0.5 && Math.abs(old.h - h) < 0.5) return;
acc.current = { ...acc.current, [name]: { w, h } };
cancelAnimationFrame(frame.current);
frame.current = requestAnimationFrame(() => setSize(acc.current));
},
[],
);
return [size, measure] as const;
}
/** 범례: 절정 잎 둘, full 이면 첫 단풍·단풍 전 점까지 */
export function Legend({ full, color }: { full?: boolean; color: string }) {
const item = (mark: ReactNode, label: string) => (
<View key={label} className="flex-row items-center gap-1">
{mark}
<Text className="text-[12.5px] font-bold" style={{ color }}>
{label}
</Text>
</View>
);
return (
<View className="h-[52px] flex-row flex-wrap items-center justify-center gap-x-3 gap-y-1">
{item(<Ic name="maple" size={16} />, '단풍 절정')}
{item(<Ic name="ginkgo" size={16} />, '은행 절정')}
{full ? item(<View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: DOT.first.color }} />, '첫 단풍') : null}
{full ? item(<View style={{ width: 5, height: 5, borderRadius: 3, backgroundColor: DOT.before.color }} />, '단풍 전') : null}
</View>
);
}
@@ -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<Record<Stage, { bg: string; ink: string }>> = {
peak: { bg: '#ffe3db', ink: '#b5321f' },
first: { bg: '#ffe8d2', ink: '#a34f12' },
};
/** 지도 아래 한 줄: 고른 명소가 있으면 그 명소 정보, 없으면 범례 (지도 위를 가리지 않게 범례 자리에) */
export function ChosenBar({ chosen, legendColor }: { chosen?: Spot; legendColor: string }) {
if (!chosen)
return (
<View className="mx-3 mt-2 h-[60px] justify-center">
<Legend full color={legendColor} />
</View>
);
const chip = CHIP[chosen.stage];
return (
<View className="mx-3 mt-2 h-[60px] flex-row items-center gap-3 rounded-[18px] border-b-4 border-shade bg-card px-3.5">
<View className="size-8 items-center justify-center">
<StageMark m={chosen} big />
</View>
<View className="min-w-0 flex-1">
<View className="flex-row items-center gap-1.5">
<Text numberOfLines={1} className="shrink font-jua text-[18px] text-ink">
{chosen.name}
</Text>
<Text className={`overflow-hidden rounded-full px-1.5 py-px text-[11px] font-extrabold ${chip ? '' : 'bg-chip text-ink2'}`} style={chip ? { backgroundColor: chip.bg, color: chip.ink } : undefined}>
{STAGE[chosen.stage]}
</Text>
</View>
<Text numberOfLines={1} className="text-[12px] font-bold text-ink3">
{`${chosen.region} · 절정 예상 ${md(chosen.peak)}`}
</Text>
</View>
</View>
);
}
/** 단계별 명소 목록 (지금 절정 · 곧 절정 · 아직 · 절정 지남). 누르면 지도에서 그 명소로 */
export function SpotList({ spots, sel, onPick }: { spots: Spot[]; sel: string | null; onPick: (m: Spot) => void }) {
return (
<View className="px-4">
{GROUPS.map(([g, title]) => {
const rows = spots.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak));
if (!rows.length) return null;
return (
<View key={g} accessibilityLabel={title} className="pt-5">
<View className="flex-row items-baseline gap-1.5 px-1 pb-1.5">
<Text className="font-jua text-[19px] text-ink">{title}</Text>
<Text className="text-[13px] font-extrabold text-ink3">{`${rows.length}곳`}</Text>
</View>
<View className="border-t border-line">
{rows.map((m) => (
<Pressable
key={m.name}
onPress={() => onPick(m)}
accessibilityRole="button"
accessibilityState={{ selected: m.name === sel }}
className="flex-row items-center gap-3 border-b border-line py-2.5 pl-1"
style={m.name === sel ? { backgroundColor: 'rgba(255,122,69,0.08)' } : undefined}
>
<View className="size-7 items-center justify-center">
<StageMark m={m} big />
</View>
<View className="min-w-0 flex-1">
<Text numberOfLines={1} className="text-[15px] font-extrabold text-ink">
{m.name}
</Text>
<Text numberOfLines={1} className="text-[12px] font-semibold text-ink3">
{`${m.region} · ${m.own ? '절정 예상' : '가까운 지점 날짜'}`}
</Text>
</View>
<Text className={`pr-1 font-jua text-[18px] ${g === 'peak' ? 'text-orange' : 'text-ink2'}`}>{md(m.peak)}</Text>
</Pressable>
))}
</View>
</View>
);
})}
</View>
);
}
+1 -1
View File
@@ -35,7 +35,7 @@ export function GakGrid({ items, dim }: { items: IndexSummary[]; dim: boolean })
className={`${CELL} ${g.active ? '' : 'opacity-55'}`}
>
{g.active && <Text className="absolute top-[7px] left-[9px] font-jua text-[13px] text-ink3">{g.rank}</Text>}
{g.season && <Text className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</Text>}
{!!g.season && <Text className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">{g.season}</Text>}
<Ic name={g.icon} size={50} />
<Text numberOfLines={1} className="mt-1 font-jua text-[15px] text-ink">
{g.name}
+1 -1
View File
@@ -48,7 +48,7 @@ export function Podium({ top, dim }: { top: IndexSummary[]; dim: boolean }) {
</Text>
</View>
<Text className="font-bagel text-[30px] leading-[32px] text-orange">{g.score}</Text>
{g.summary && <Text className="text-center text-[11.5px] font-semibold text-ink2">{g.summary}</Text>}
{!!g.summary && <Text className="text-center text-[11.5px] font-semibold text-ink2">{g.summary}</Text>}
</Pressable>
);
})}
+362
View File
@@ -0,0 +1,362 @@
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, useState, type ReactNode } from 'react';
import { Pressable, ScrollView, TextInput, View } from 'react-native';
import { Body, useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Ic, Rail, Sec } from '@/components/ui';
import { gakName, MY_GAK_ICON, shareUrl, SLOT_WORD, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from '@/lib/my-gak';
import { useRegion } from '@/lib/region';
import { useShare } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
const v = s?.score;
return <Text className={`ml-auto font-bagel ${big ? 'text-[36px] leading-[38px]' : 'text-[28px] leading-[30px]'} ${v == null || v < 50 ? 'text-ink3' : 'text-orange'}`}>{v ?? '–'}</Text>;
}
function Reasons({ s }: { s?: MyGakScore }) {
if (!s?.slot) return <Text className="text-[12.5px] font-semibold text-ink3">예보를 불러오는 중이에요</Text>;
return (
<Text className="text-[12.5px] leading-snug font-semibold text-ink2">
<Text className="font-extrabold text-ink">{SLOT_WORD[s.slot as Slot]} </Text>
{s.reasons?.join(' · ')}
</Text>
);
}
// 조건 이름. 점수 응답의 factors 와 reasons 는 같은 순서다
const AXIS_NAME: Record<string, string> = { temp: '기온', rain: '비', wind: '바람', air: '미세먼지', humidity: '습도' };
// 조건 점수가 이보다 낮으면 '아쉬운 조건'으로 카드에 칩을 단다
const SHORT = 70;
/** 조건마다 이름·점수·실제 값 (실제 값은 근거 문구의 첫 마디: 체감 15°) */
function conditions(s?: MyGakScore) {
const notes = s?.reasons ?? [];
return Object.entries(s?.factors ?? {}).map(([axis, value], i) => ({ axis, label: AXIS_NAME[axis] ?? axis, value, note: notes[i] ?? '', short: (notes[i] ?? '').split(', ')[0] }));
}
/** 오늘 탭의 내 각 줄: 카드엔 아이콘·이름·점수·아쉬운 조건만, 누르면 상세 창 */
export function MyGakRow() {
const { open } = useSheet();
const { items } = useMyGak();
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? [];
return (
<>
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
<Rail>
{items.map((g, i) => {
const s = scores[i];
const miss = conditions(s)
.filter((c) => c.value < SHORT)
.slice(0, 2);
return (
<Pressable key={g.id ?? 'local'} onPress={() => open({ type: 'myGak', gak: g })} accessibilityLabel={`${g.name} ${s?.score ?? ''}점 자세히`} className="w-[200px] gap-2 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
<View className="flex-row items-start justify-between">
<Ic name={g.icon ?? MY_GAK_ICON} size={40} />
<Score s={s} big />
</View>
<View>
<Text className="font-jua text-[17px] leading-tight text-ink">{g.name}</Text>
<Text className="text-xs font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준` : '예보를 불러오는 중이에요'}</Text>
</View>
{!!s?.slot && (
<View className="flex-row flex-wrap gap-1">
{miss.length ? (
miss.map((c) => (
<Text key={c.axis} className="overflow-hidden rounded-full bg-[#ffe8dc] px-2 py-0.5 text-[11.5px] font-extrabold text-[#c2471b]">
{c.short}
</Text>
))
) : (
<Text className="overflow-hidden rounded-full bg-[#dff5ea] px-2 py-0.5 text-[11.5px] font-extrabold text-[#1f7a4f]">조건 다 맞아요</Text>
)}
</View>
)}
</Pressable>
);
})}
<Pressable onPress={() => open({ type: 'mix' })} accessibilityRole="button" className="w-[120px] items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-line p-3">
<Text className="font-jua text-[26px] leading-[28px] text-ink2">+</Text>
<Text className="font-jua text-[15px] text-ink2">내 각 만들기</Text>
</Pressable>
</Rail>
</>
);
}
/** 내 각 상세: 시간대별 점수, 조건별 점수와 실제 값, 공유하기·지우기 */
export function MyGakSheet({ gak, onDone }: { gak: MyGak; onDone: () => void }) {
const { remove } = useMyGak();
const s = useMyGakScores([gak.rule]).data?.scores?.[0];
const soft = useSoft();
const shareView = useShare();
const shot = useRef<View>(null);
const [confirm, setConfirm] = useState(false);
const rows = conditions(s);
// 받은 사람이 자기 동네 점수로 볼 수 있게 링크를 같이 보낸다
const share = () => void shareView(shot, { title: gak.name, message: `${gak.name} ${s?.score ?? ''}점 · 내 동네 점수 보기 ${shareUrl(gak)}` });
return (
<Body>
<View ref={shot} collapsable={false} className="bg-card">
<View className="flex-row items-center gap-3">
<Ic name={gak.icon ?? MY_GAK_ICON} size={56} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[22px] leading-tight text-ink">{gak.name}</Text>
<Text className="text-[12.5px] font-bold text-ink3">{s?.slot ? `${SLOT_WORD[s.slot as Slot]} 기준 점수` : '예보를 불러오는 중이에요'}</Text>
</View>
<Score s={s} big />
</View>
<View className="mt-3 flex-row gap-1.5" accessibilityLabel="시간대별 점수">
{SLOTS.map(([k, word]) => {
const v = s?.slots?.[k];
return (
<View key={k} className="flex-1 items-center rounded-2xl px-1 py-2" style={{ backgroundColor: s?.slot === k ? soft.warm : soft.soft }}>
<Text className="text-xs font-extrabold text-ink2">{word}</Text>
<Text className={`font-bagel text-xl ${v != null ? 'text-orange' : 'text-ink3'}`}>{v ?? '–'}</Text>
</View>
);
})}
</View>
<View className="mt-3.5 gap-2.5">
{rows.map((c) => (
<View key={c.axis}>
<View className="flex-row items-center gap-2.5">
<Text className="w-16 text-[13.5px] font-bold text-ink">{c.label}</Text>
<View className="h-[9px] flex-1 overflow-hidden rounded-full" style={{ backgroundColor: soft.bar }}>
<LinearGradient colors={['#ffc86e', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${c.value}%` }} />
</View>
<Text className="w-8 text-right text-xs font-bold text-ink2">{c.value}</Text>
</View>
<Text className="ml-[74px] text-[12.5px] font-semibold text-ink2">{c.note}</Text>
</View>
))}
</View>
</View>
<View className="mt-4 flex-row gap-2">
<Pressable onPress={share} className="flex-1 rounded-2xl bg-orange py-3">
<Text className="text-center font-jua text-[16px] text-white">공유하기</Text>
</Pressable>
{confirm ? (
<>
<Pressable
onPress={() => {
remove(gak);
onDone();
}}
className="rounded-2xl bg-[#fdecec] px-4 py-3"
>
<Text className="font-jua text-[16px] text-heart">지우기</Text>
</Pressable>
<Pressable onPress={() => setConfirm(false)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
<Text className="font-jua text-[16px] text-[#5a6380]">취소</Text>
</Pressable>
</>
) : (
<Pressable onPress={() => setConfirm(true)} className="rounded-2xl bg-[#eef4fc] px-4 py-3">
<Text className="font-jua text-[16px] text-[#5a6380]">지우기</Text>
</Pressable>
)}
</View>
{confirm && <Text className="mt-1.5 text-right text-[12.5px] font-bold text-ink2">지울까요?</Text>}
</Body>
);
}
function Row({ label, on, onToggle, disabled, children }: { label: string; on: boolean; onToggle: () => void; disabled?: boolean; children: ReactNode }) {
return (
<View className={`min-h-[44px] flex-row flex-wrap items-center gap-2 border-b border-line py-2 ${on ? '' : 'opacity-60'}`}>
<Pressable onPress={onToggle} disabled={disabled} accessibilityRole="checkbox" accessibilityState={{ checked: on }} className="w-[84px] flex-row items-center gap-1.5">
<View className={`size-4 items-center justify-center rounded-[4px] border-2 ${on ? 'border-orange bg-orange' : 'border-ink3'}`}>{on && <Text className="text-[10px] leading-3 font-extrabold text-white">✓</Text>}</View>
<Text className="text-[14px] font-extrabold text-ink">{label}</Text>
</Pressable>
{on ? <View className="min-w-0 flex-1 flex-row flex-wrap items-center gap-1.5">{children}</View> : <Text className="text-[13px] font-semibold text-ink3">상관없음</Text>}
</View>
);
}
/** 숫자: 휴대폰 숫자 자판엔 '-'가 없을 때가 있어 −/+ 버튼으로 바꾼다 */
function Num({ value, onChange, min, max, step = 1, label, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; step?: number; label: string; disabled?: boolean }) {
const soft = useSoft();
const set = (v: number) => onChange(Math.min(max, Math.max(min, v)));
return (
<View className="flex-row items-center overflow-hidden rounded-xl" style={{ backgroundColor: soft.soft }} accessibilityLabel={label}>
<Pressable onPress={() => set(value - step)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-2 py-1.5 disabled:opacity-30">
<Text className="text-[15px] font-extrabold text-ink2">−</Text>
</Pressable>
<Text className="min-w-[28px] text-center text-[13.5px] font-bold text-ink">{value}</Text>
<Pressable onPress={() => set(value + step)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-2 py-1.5 disabled:opacity-30">
<Text className="text-[15px] font-extrabold text-ink2">+</Text>
</Pressable>
</View>
);
}
function Choice<T extends string>({ value, options, onChange, label, disabled }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string; disabled?: boolean }) {
return (
<View className="flex-row gap-1" accessibilityRole="radiogroup" accessibilityLabel={label}>
{options.map(([k, word]) => (
<Pressable key={k} onPress={() => onChange(k)} disabled={disabled} accessibilityRole="radio" accessibilityState={{ checked: value === k }} className={`rounded-full px-3 py-1.5 ${value === k ? 'bg-orange' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[13.5px] font-bold ${value === k ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
</Pressable>
))}
</View>
);
}
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> };
const DEFAULT_RULE: Filled<MyGakRule> = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] };
type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity';
const condsOf = (r: MyGakRule): Record<Cond, boolean> => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity });
/** 내 각 아이콘 고르기: 있는 각 아이콘 그대로 */
function IconPicker({ value, onPick }: { value: string; onPick: (icon: string) => void }) {
const soft = useSoft();
const icons = [...new Set([MY_GAK_ICON, ...(usePresets().data ?? []).map((p) => p.icon)])];
return (
<View className="mt-3">
<Text className="font-jua text-[19px] text-ink">아이콘</Text>
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-1.5 px-4 pt-2 pb-1">
{icons.map((icon) => (
<Pressable key={icon} onPress={() => onPick(icon)} accessibilityRole="button" accessibilityState={{ selected: value === icon }} accessibilityLabel={`아이콘 ${icon}`} className={`size-12 items-center justify-center rounded-2xl ${value === icon ? 'bg-orange' : ''}`} style={value === icon ? undefined : { backgroundColor: soft.soft }}>
<Ic name={icon} size={32} />
</Pressable>
))}
</ScrollView>
</View>
);
}
/** 있는 각을 골라 그 각 조건으로 채운다 */
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
const soft = useSoft();
const items = usePresets().data ?? [];
if (!items.length) return null;
return (
<View className="mb-3">
<Text className="font-jua text-[19px] text-ink">있는 각에서 불러오기</Text>
<ScrollView horizontal showsHorizontalScrollIndicator={false} className="-mx-4" contentContainerClassName="gap-2.5 px-4 pt-2 pb-1">
{items.map((p) => (
<Pressable key={p.code} onPress={() => onPick(p)} accessibilityRole="button" accessibilityState={{ selected: picked === p.code }} className={`w-[68px] items-center gap-1 rounded-2xl px-1 py-2 ${picked === p.code ? 'bg-orange' : ''}`} style={picked === p.code ? undefined : { backgroundColor: soft.soft }}>
<Ic name={p.icon} size={36} />
<Text numberOfLines={1} className={`text-[12px] leading-tight font-extrabold ${picked === p.code ? 'text-white' : 'text-ink2'}`}>
{p.name}
</Text>
</Pressable>
))}
</ScrollView>
</View>
);
}
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
const { region } = useRegion();
const soft = useSoft();
const { create, pending, failed } = useMyGak();
const [name, setName] = useState(shared?.name ?? '');
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE);
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false });
const [picked, setPicked] = useState<string | null>(null);
const [icon, setIcon] = useState(shared?.icon ?? MY_GAK_ICON);
const lock = !!shared;
const pick = (p: MyGakPreset) => {
setPicked(p.code);
setName(p.name);
setIcon(p.icon);
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE);
setOn(condsOf(p.rule));
};
const set = <K extends keyof typeof vals>(k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }));
const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }));
const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial<MyGakRule>) };
const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1]);
const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0];
const title = gakName(name) || '이름 없는 각';
const toggleSlot = (s: Slot) =>
set(
'slots',
vals.slots.includes(s)
? vals.slots.filter((x) => x !== s)
: SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)),
);
return (
<Body>
{shared ? (
<Text className="text-[13px] font-bold text-ink2">친구가 보낸 각이에요. {region.name} 기준 점수예요</Text>
) : (
<>
<PresetPicker picked={picked} onPick={pick} />
<Text className="font-jua text-[19px] text-ink">이름</Text>
<TextInput value={name} onChangeText={setName} maxLength={11} placeholder="소맥, 야독, 새우깡" placeholderTextColor={soft.placeholder} accessibilityLabel="이름" className="mt-1.5 rounded-2xl px-3.5 py-2.5 text-[15px] text-ink" style={{ backgroundColor: soft.soft }} />
<IconPicker value={icon} onPick={setIcon} />
</>
)}
<Text className="mt-3 font-jua text-[19px] text-ink">조건</Text>
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')} disabled={lock}>
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [v, vals.temp[1]])} />
<Text className="text-[13.5px] font-bold text-ink">~</Text>
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} disabled={lock} onChange={(v) => set('temp', [vals.temp[0], v])} />
<Text className="text-[13.5px] font-bold text-ink">° 체감</Text>
</Row>
<Row label="비" on={on.rain} onToggle={() => toggle('rain')} disabled={lock}>
<Choice
label="비"
value={vals.rain}
disabled={lock}
onChange={(v) => set('rain', v)}
options={[
['dry', '안 와야'],
['wet', '와야'],
]}
/>
</Row>
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')} disabled={lock}>
<Text className="text-[13.5px] font-bold text-ink">초속</Text>
<Num label="바람 상한" value={vals.wind_max} min={1} max={20} disabled={lock} onChange={(v) => set('wind_max', v)} />
<Text className="text-[13.5px] font-bold text-ink">m 이하</Text>
</Row>
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')} disabled={lock}>
<Choice
label="미세먼지"
value={vals.air}
disabled={lock}
onChange={(v) => set('air', v)}
options={[
['good', '좋음만'],
['normal', '보통까지'],
]}
/>
</Row>
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')} disabled={lock}>
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />
<Text className="text-[13.5px] font-bold text-ink">~</Text>
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} step={5} disabled={lock} onChange={(v) => set('humidity', [vals.humidity[0], v])} />
<Text className="text-[13.5px] font-bold text-ink">%</Text>
</Row>
<View className="flex-row flex-wrap items-center gap-1.5 py-2.5">
<Text className="w-[84px] text-[14px] font-extrabold text-ink">시간대</Text>
{SLOTS.map(([k, word]) => (
<Pressable key={k} onPress={() => toggleSlot(k)} disabled={lock} accessibilityRole="button" accessibilityState={{ selected: vals.slots.includes(k) }} className={`rounded-full px-3 py-1.5 ${vals.slots.includes(k) ? 'bg-orange' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[13.5px] font-bold ${vals.slots.includes(k) ? 'text-white' : 'text-[#28304a]'}`}>{word}</Text>
</Pressable>
))}
</View>
<View className="mt-2 gap-1.5 rounded-[20px] p-3.5" style={{ backgroundColor: soft.soft }}>
<View className="flex-row items-center gap-2">
<Ic name={icon} size={32} />
<Text className="font-jua text-[20px] text-ink">{title}</Text>
<Score s={valid ? score : undefined} big />
</View>
{valid ? <Reasons s={score} /> : <Text className="text-[12.5px] font-semibold text-ink3">조건과 시간대를 하나 이상 골라요</Text>}
</View>
{failed && <Text className="mt-2 text-xs font-bold text-heart">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</Text>}
<Pressable disabled={!valid || !gakName(name) || pending} onPress={() => create({ name, icon, rule }, onDone)} className="mt-3.5 rounded-2xl bg-orange py-3 disabled:opacity-45">
<Text className="text-center font-jua text-[17px] text-white">{shared ? '내 각으로 가져오기' : '내 각으로 저장'}</Text>
</Pressable>
</Body>
);
}
+10 -1
View File
@@ -1,4 +1,4 @@
import Svg, { Path } from 'react-native-svg';
import Svg, { Circle, Path } from 'react-native-svg';
export const HEART = 'M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z';
@@ -27,3 +27,12 @@ export function SendIcon({ size, color }: P) {
</Svg>
);
}
export function CameraIcon({ size, color }: P) {
return (
<Svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
<Path d="M4 8.5A1.5 1.5 0 0 1 5.5 7h2.2l1.5-2h5.6l1.5 2h2.2A1.5 1.5 0 0 1 20 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 4 17.5z" />
<Circle cx={12} cy={13} r={3.5} />
</Svg>
);
}
+14 -11
View File
@@ -13,9 +13,9 @@ import { LikeBurst } from '@/components/post/like-burst';
import { Dots, Pager } from '@/components/post/pager';
import { slideBg, SlideView, type Slide } from '@/components/post/slides';
import { Ic, Skel } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { track } from '@/lib/analytics';
import { useSheet } from '@/lib/sheet';
import { shareView } from '@/lib/share-image';
import { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
const ACCOUNTS: Partial<Record<PostType, readonly [string, string]>> = {
@@ -34,12 +34,11 @@ const ACCOUNTS: Partial<Record<PostType, readonly [string, string]>> = {
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
[PostType.MOON]: ['오늘 밤 달', 'moon'],
[PostType.UV]: ['자외선', 'glasses'],
[PostType.CARD]: ['날씨각 카드', 'stars'],
};
const isSlide = (s: PostData['slides'][number]): s is Slide => s.kind !== 'image';
/** 앱이 그릴 줄 아는 글만 (웹 전용 글 종류·이미지 슬라이드가 든 글은 뺀다) */
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS && p.slides.every(isSlide);
/** 앱이 그릴 줄 아는 글 종류만 (히어로·띠처럼 피드 반응 칸으로만 오는 종류는 뺀다) */
export const isAppPost = (p: PostData) => p.post_type in ACCOUNTS;
type PostProps = { post: PostData };
@@ -117,7 +116,6 @@ function HeartPop() {
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;
@@ -135,6 +133,7 @@ function FullCard({ post }: PostProps) {
const comments = () => open({ type: 'comments', postId: post.post_id });
const shot = useRef<View>(null);
// 지금 보고 있는 슬라이드를 이미지로
const shareView = useShare();
const share = () => void shareView(shot, { title: post.title, message: `${post.title} · 날씨각 ${SITE_URL}` });
useEffect(() => {
@@ -144,8 +143,8 @@ function FullCard({ post }: PostProps) {
}, [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);
@@ -157,7 +156,11 @@ function FullCard({ post }: PostProps) {
(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()),
onSuccess: (res) => {
if (!res.result?.success) return revert();
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) });
if (on) track('like', { content_type: 'post', item_id: post.post_id });
},
onError: revert,
},
);
@@ -166,7 +169,7 @@ function FullCard({ post }: PostProps) {
const onTap = () => {
const now = Date.now();
if (now - lastTap.current < 320) {
if (liked && loggedIn) setPop((p) => p + 1);
if (liked) setPop((p) => p + 1);
else setLike(true);
}
lastTap.current = now;
@@ -190,7 +193,7 @@ function FullCard({ post }: PostProps) {
<View ref={shot} collapsable={false}>
{width > 0 && (
<Pager width={width} height={(width * 5) / 4} onIndex={setIndex}>
{post.slides.filter(isSlide).map((s, i) => (
{post.slides.map((s: Slide, i) => (
<SlideView key={i} slide={s} bg={slideBg(post, s)} />
))}
</Pager>
+79
View File
@@ -0,0 +1,79 @@
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen';
import type { PinnedKey } from '@nalssigak/shared/lib/analytics';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, type ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { useCSSVariable } from 'uniwind';
import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { usePinnedLike } from '@/lib/pinned-like';
import { useSheet } from '@/lib/sheet';
import { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
type Props = { title: string; account: string; avatar: string; caption?: string; more?: ReactNode; pinned?: { key: PinnedKey; post?: PostReaction | null }; children: ReactNode };
/** 오늘의 각처럼 포스트 틀(머리줄·버튼줄·글 한 줄)만 빌려 쓰는 카드 (웹 PostFrame). 좋아요·댓글은 피드의 반응 칸(pinned)에 붙는다 */
export function PostFrame({ title, account, avatar, caption, more, pinned, children }: Props) {
const { open } = useSheet();
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post);
const postId = pinned?.post?.post_id;
const shot = useRef<View>(null);
const shareView = useShare();
const share = () => void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` });
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<View className="size-[34px] rounded-full p-0.5">
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 17 }} />
<View className="flex-1 items-center justify-center rounded-full bg-card">
<Ic name={avatar} size={22} />
</View>
</View>
<View>
<Text className="text-sm leading-tight font-extrabold text-ink">날씨각</Text>
<Text className="text-xs font-semibold text-ink2">{account}</Text>
</View>
</View>
<View ref={shot} collapsable={false}>
{children}
</View>
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
{postId != null && (
<>
<Pressable onPress={like.toggle} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={like.liked ? heart : ink} filled={like.liked} />
</Pressable>
<Pressable onPress={() => open({ type: 'comments', postId })} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
<CommentIcon size={26} color={ink} />
</Pressable>
</>
)}
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
<SendIcon size={26} color={ink} />
</Pressable>
{more != null && <View className="ml-auto">{more}</View>}
</View>
{postId != null && (
<Text className={`px-3 py-0.5 text-sm font-extrabold ${like.failed ? 'text-heart' : 'text-ink'}`} accessibilityRole={like.failed ? 'alert' : undefined}>
{like.failed ? '좋아요를 반영하지 못했어요. 다시 해 주세요.' : `좋아요 ${like.count.toLocaleString()}개`}
</Text>
)}
{!!caption && (
<Text className="px-3 pt-0.5 pb-3 text-sm text-ink">
<Text className="font-extrabold">날씨각 </Text>
{caption}
</Text>
)}
{postId != null && (
<Pressable onPress={() => open({ type: 'comments', postId })}>
<Text className="px-3 pb-3 text-sm font-semibold text-ink3">{pinned?.post?.comment_count ? `댓글 ${pinned.post.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
)}
</View>
);
}
+10 -8
View File
@@ -1,4 +1,4 @@
import type { GakSlide, HoursSlide, PlanSlide, PostData, RowsSlide, SunsetSlide, WeekSlide } from '@nalssigak/shared/api/client/types.gen';
import type { GakSlide, HoursSlide, ImageSlide, PlanSlide, PostData, RowsSlide, SunsetSlide, WeekSlide } from '@nalssigak/shared/api/client/types.gen';
import { PostType, SlotTone } from '@nalssigak/shared/api/client/types.gen';
import { cardBg, clockShort } from '@nalssigak/shared/lib';
import type { SlideBg } from '@nalssigak/shared/lib/types';
@@ -14,10 +14,10 @@ import { MoonArt } from '@/components/moon';
import { Credit, Ic, Rows, Thumb } from '@/components/ui';
import { CARD_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { imageUri } from '@/lib/site';
import { apiUri, imageUri } from '@/lib/site';
import { useSky } from '@/lib/sky';
export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide;
export type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide | ImageSlide;
type Stops = readonly [string, string, ...string[]];
@@ -50,7 +50,7 @@ const HOUR_TONE: Record<string, { bg: string; edge: string }> = {
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
export function slideBg(post: PostData, slide: Slide): SlideBg {
if (slide.kind === 'hours') return 'sky';
if (slide.kind === 'hours' || slide.kind === 'image') return 'sky';
if (slide.kind === 'sunset') return 'dusk';
if (slide.kind === 'week') return 'mint';
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter';
@@ -170,7 +170,7 @@ export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
<Eyebrow light>{slide.eyebrow}</Eyebrow>
{/* 노을 탭 히어로와 같은 순서: 결론 → 가장 붉을 때 → 쉬운 이유 */}
<Big light>{slide.headline ?? slide.grade_label}</Big>
{slide.line && <Text className="mt-0.5 font-jua text-[18px] text-white">{slide.line}</Text>}
{!!slide.line && <Text className="mt-0.5 font-jua text-[18px] text-white">{slide.line}</Text>}
<View className="mt-3 flex-1 gap-2">
{slide.cuts.map((c, i) => (
<View key={c.kind} className="flex-1 overflow-hidden rounded-2xl px-3 py-2">
@@ -224,7 +224,7 @@ export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
</View>
))}
</View>
{slide.tip && <Text className="mt-auto overflow-hidden rounded-[14px] bg-ink-btn px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</Text>}
{!!slide.tip && <Text className="mt-auto overflow-hidden rounded-[14px] bg-ink-btn px-3 py-2.5 text-[13px] leading-snug font-bold text-white">{slide.tip}</Text>}
</Base>
);
if (slide.kind === 'plan') {
@@ -246,7 +246,7 @@ export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
{st.sub}
</Text>
</View>
{st.image && <Thumb image={st.image} icon={st.icon} iconSize={26} className="size-[46px] rounded-[10px]" />}
{!!st.image && <Thumb image={st.image} icon={st.icon} iconSize={26} className="size-[46px] rounded-[10px]" />}
</View>
))}
</View>
@@ -254,11 +254,13 @@ export function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
</Base>
);
}
// 카드뉴스: 관리자가 만든 4:5 그림 한 장 (/v1/card/... 는 API 서버 경로)
if (slide.kind === 'image') return <Image source={{ uri: apiUri(slide.url) }} accessibilityLabel={slide.alt ?? undefined} style={{ flex: 1 }} contentFit="cover" />;
if (slide.kind === 'rows' && slide.image)
return (
<View className="flex-1 justify-end">
<Image source={{ uri: imageUri(slide.image) }} style={StyleSheet.absoluteFill} contentFit="cover" />
{slide.image_credit && <Credit text={slide.image_credit} className="top-2.5 right-2.5" />}
{!!slide.image_credit && <Credit text={slide.image_credit} className="top-2.5 right-2.5" />}
<View className="px-5 pt-20 pb-3.5">
<LinearGradient colors={['rgba(16,20,34,0)', 'rgba(16,20,34,0.55)', 'rgba(16,20,34,0.85)']} locations={[0, 0.35, 1]} style={StyleSheet.absoluteFill} />
<Eyebrow light>{slide.eyebrow}</Eyebrow>
+108
View File
@@ -0,0 +1,108 @@
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { BIRTH_PLACES, placeName, useSaveBirth, validBirth, type Birth } from '@/lib/saju-birth';
import { Box, ChipGrid, DatePick, Stepper, type Ymd } from './pick';
const HOURS: [number, string][] = [[-1, '모름'], ...Array.from({ length: 24 }, (_, i): [number, string] => [i, `${i}시`])];
const PLACES: [string, string][] = BIRTH_PLACES.map(([k, n]) => [k, n]);
function Label({ children }: { children: string }) {
return <Text className="mb-1.5 text-[13px] font-extrabold text-ink2">{children}</Text>;
}
/** 생년월일·태어난 시각·지역 넣기 (웹 SajuPage BirthForm) */
export function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) {
const { loggedIn } = useAuth();
const save = useSaveBirth();
const [date, setDate] = useState<Ymd>({ y: initial?.y ?? null, m: initial?.m ?? null, d: initial?.d ?? null });
const [hour, setHour] = useState<number | null>(initial?.hour ?? null);
const [minute, setMinute] = useState(initial?.minute ?? 0);
const [place, setPlace] = useState(initial?.place ?? 'seoul');
const [open, setOpen] = useState<'hour' | 'place' | null>(null);
const [error, setError] = useState('');
const toggle = (k: 'hour' | 'place') => setOpen((o) => (o === k ? null : k));
const submit = () => {
const { y, m, d } = date;
if (y == null || m == null || d == null) return setError('생년월일을 모두 넣어 주세요');
if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요');
void save({ y, m, d, hour, minute: hour == null ? null : minute, place, gender: initial?.gender ?? null });
track('saju_input', { with_time: hour != null });
onDone();
};
return (
<View className="mx-4 mt-4 gap-4 rounded-[24px] border-b-[5px] border-shade bg-card p-5">
<View className="items-center">
<Ic name="yin_yang" size={56} />
<Text className="mt-2 text-center font-jua text-[20px] leading-snug text-ink">{'내 사주와 오늘 날씨로\n오늘 하루를 봐요'}</Text>
</View>
<View>
<Label>생년월일 (양력)</Label>
<DatePick
value={date}
onChange={(v) => {
setDate(v);
setError('');
}}
/>
</View>
<View>
<Label>{"태어난 시각 (모르면 '모름')"}</Label>
<View className="flex-row gap-1.5">
<Box label="시" value={hour == null ? '모름' : `${hour}시`} placeholder="모름" open={open === 'hour'} onPress={() => toggle('hour')} />
<Stepper label="분" value={minute} onChange={setMinute} min={0} max={59} unit="분" disabled={hour == null} />
</View>
{open === 'hour' && (
<View className="mt-1.5">
<ChipGrid
label="태어난 시"
items={HOURS}
value={hour ?? -1}
onPick={(h) => {
setHour(h < 0 ? null : h);
setOpen(null);
}}
wide
/>
</View>
)}
</View>
<View>
<Label>태어난 지역</Label>
<Box label="태어난 지역" value={placeName(place)} placeholder="서울" open={open === 'place'} onPress={() => toggle('place')} />
{open === 'place' && (
<View className="mt-1.5">
<ChipGrid
label="태어난 지역"
items={PLACES}
value={place}
onPick={(p) => {
setPlace(p);
setOpen(null);
}}
wide
/>
</View>
)}
<Text className="mt-1.5 text-xs font-semibold text-ink3">지역마다 해가 뜨는 시각이 달라 태어난 시각을 그만큼 고쳐서 봐요.</Text>
</View>
{!!error && <Text className="text-center text-[13px] font-bold text-[#d9442f]">{error}</Text>}
<Pressable onPress={submit} accessibilityRole="button" className="rounded-full bg-orange py-3.5">
<Text className="text-center text-[15px] font-extrabold text-white">오늘 날씨 사주 보기</Text>
</Pressable>
{!!onCancel && (
<Pressable onPress={onCancel} accessibilityRole="button" className="-mt-2 py-1">
<Text className="text-center text-[13px] font-extrabold text-ink3">취소</Text>
</Pressable>
)}
<Text className="text-center text-xs font-semibold text-ink3">{loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'}</Text>
</View>
);
}
+81
View File
@@ -0,0 +1,81 @@
import { matchMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { ResSajuMatch } from '@nalssigak/shared/api/client/types.gen';
import { useMutation } from '@tanstack/react-query';
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { useRegion } from '@/lib/region';
import { toBody, validBirth, type Birth } from '@/lib/saju-birth';
import { dayWord, Panel } from './parts';
import { DatePick, type Ymd } from './pick';
const pad = (n: number) => String(n).padStart(2, '0');
/** 궁합 (Lv.5): 상대 생년월일로 두 사주가 맞는 정도와 같이 나가기 좋은 날. 상대 생년월일은 저장하지 않는다 */
export function Match({ birth }: { birth: Birth }) {
const { region } = useRegion();
const soft = useSoft();
const [date, setDate] = useState<Ymd>({ y: null, m: null, d: null });
const [error, setError] = useState('');
const run = useMutation({ ...matchMutation() });
const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined;
const go = () => {
const { y, m, d } = date;
if (y == null || m == null || d == null) return setError('상대 생년월일을 모두 넣어 주세요');
if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요');
setError('');
run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${y}-${pad(m)}-${pad(d)}`, longitude: 126.98 } } });
};
return (
<Panel id="saju_match" icon="two_hearts" title="궁합">
{res ? (
<>
<View className="mb-1 flex-row items-center justify-between">
<Text className="text-xs font-bold text-ink3">
상대 {date.y}.{date.m}.{date.d}생
</Text>
<Pressable onPress={() => run.reset()} hitSlop={8} accessibilityRole="button">
<Text className="text-xs font-extrabold text-orange">다른 사람 보기</Text>
</Pressable>
</View>
<Text className="font-jua text-[19px] text-ink">
{res.title ?? ''} <Text className="font-bagel text-[17px] text-orange">{res.score ?? ''}점</Text>
</Text>
{res.lines?.map((l) => (
<Text key={l} className="mt-1 text-[13.5px] font-semibold text-ink">
{l}
</Text>
))}
{!!res.day && (
<Text className="mt-2 overflow-hidden rounded-xl px-3 py-2 text-[13.5px] font-bold text-ink" style={{ backgroundColor: soft.warm }}>
앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)}
{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
</Text>
)}
<Text className="mt-1.5 text-xs font-semibold text-ink3">상대 기운: {res.friend_scene ?? ''}</Text>
</>
) : (
<>
<Text className="mb-2 text-[13px] font-semibold text-ink2">상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.</Text>
<DatePick
label="상대 "
value={date}
onChange={(v) => {
setDate(v);
setError('');
}}
/>
<Pressable onPress={go} disabled={run.isPending} accessibilityRole="button" className="mt-2 rounded-xl bg-orange py-3 disabled:opacity-45">
<Text className="text-center text-[14px] font-extrabold text-white">보기</Text>
</Pressable>
{!!error && <Text className="mt-1.5 text-xs font-bold text-[#d9442f]">{error}</Text>}
{(run.isError || (!!run.data && !run.data.result?.success)) && <Text className="mt-1.5 text-xs font-bold text-[#d9442f]">궁합을 불러오지 못했어요. 다시 눌러 주세요.</Text>}
<Text className="mt-1.5 text-xs font-semibold text-ink3">상대 생년월일은 저장하지 않아요.</Text>
</>
)}
</Panel>
);
}
+139
View File
@@ -0,0 +1,139 @@
import type { ResSaju } from '@nalssigak/shared/api/client/types.gen';
import { Image } from 'expo-image';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { EL_ART, EL_COLOR, EL_WORD, Panel } from './parts';
const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' };
const STRENGTH_WORD: Record<string, string> = {
신강: '나를 돕는 기운이 센 사주. 태어난 달(월령)의 힘을 먼저 봐요',
중화: '나를 돕는 기운과 다른 기운이 비슷한 사주',
신약: '나를 돕는 기운이 약한 사주',
};
const TEN_GOD_WORD: Record<string, string> = {
비견: '나와 같은 기운',
겁재: '나와 같지만 겨루는 기운',
식신: '내가 만들어 내는 기운',
상관: '내가 드러내는 기운',
편재: '내가 크게 굴리는 재물',
정재: '내가 차곡차곡 모으는 재물',
편관: '나를 세게 다잡는 기운',
정관: '나를 바르게 이끄는 기운',
편인: '나를 돕는 남다른 지혜',
정인: '나를 돕는 배움·도움',
};
function Art({ el, size }: { el: string; size: number }) {
const src = EL_ART[el];
return src != null ? <Image source={src} style={{ width: size, height: size }} contentFit="contain" /> : null;
}
function Char({ c, ko, el, me }: { c: string; ko: string; el: string; me?: boolean }) {
const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb'];
return (
<View className="items-center rounded-xl py-1.5" style={{ backgroundColor: bg, borderWidth: me ? 2 : 0, borderColor: '#ff7a45' }}>
<Text className="font-batang text-[22px] leading-tight" style={{ color: fg }}>
{c}
</Text>
<Text className="text-[10.5px] font-extrabold" style={{ color: fg }}>
{ko}
</Text>
</View>
);
}
function Note({ term, word }: { term: string; word: string }) {
return (
<Text className="text-[12.5px] leading-relaxed font-semibold text-ink2">
<Text className="font-extrabold text-ink">{term}</Text> = {word}
</Text>
);
}
/** 사주 명식: 가장 센 기운, 오행 막대, 네 기둥, 용어 풀이 */
export function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
const soft = useSoft();
const me = r.me!;
const cols = [...me.pillars].reverse();
const els = Object.entries(me.elements ?? {});
const total = els.reduce((a, [, v]) => a + v, 0);
const gods = [...new Set(me.pillars.flatMap((p) => [p.stem_ten_god, p.branch_ten_god]).filter((g): g is string => !!g && g in TEN_GOD_WORD))];
const strength = me.strength ?? (me.strong == null ? null : me.strong ? '신강' : '신약');
const top = me.top_element;
return (
<Panel
icon={me.scene_icon}
title="사주 명식"
right={
<Pressable onPress={onEdit} hitSlop={8} accessibilityRole="button">
<Text className="text-xs font-extrabold text-orange">생년월일 바꾸기</Text>
</Pressable>
}
>
{!!top && !!strength && (
<View className="flex-row items-center gap-3">
<Art el={top} size={64} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[18px] leading-snug text-ink">
{EL_WORD[top]}({top}) 기운이 가장 센 {strength} 사주
</Text>
<Text className="mt-0.5 text-[13px] font-semibold text-ink2">
나를 돕는 기운 {Math.round((me.support ?? 0) * 100)}% · {me.scene}
</Text>
</View>
</View>
)}
{total > 0 && (
<>
<View className="mt-2.5 h-2.5 flex-row overflow-hidden rounded-full" accessibilityRole="image" accessibilityLabel={els.map(([k, v]) => `${k} ${Math.round(v)}`).join(', ')}>
{els.map(([k, v]) => (
<View key={k} style={{ width: `${(v / total) * 100}%`, backgroundColor: EL_COLOR[k]?.[0] }} />
))}
</View>
<View className="mt-1.5 flex-row justify-between">
{els.map(([k, v]) => (
<View key={k} className="flex-row items-center gap-0.5">
<Art el={k} size={20} />
<Text className="text-[12px] font-extrabold" style={{ color: EL_COLOR[k]?.[0] }}>
{k} {Math.round(v)}
</Text>
</View>
))}
</View>
</>
)}
<View className="mt-3 flex-row gap-1.5">
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
<View key={p?.position ?? `none-${i}`} className="flex-1 gap-1">
<Text className="text-center text-[11px] font-extrabold text-ink3">{p ? `${POS_WORD[p.position]}주` : '시주'}</Text>
{p ? (
<>
<Text className={`text-center text-[11.5px] font-extrabold ${p.position === 'day' ? 'text-orange' : 'text-ink2'}`}>{p.position === 'day' ? '나' : (p.stem_ten_god ?? '')}</Text>
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} me={p.position === 'day'} />
<Char c={p.branch} ko={p.branch_ko} el={p.branch_element} />
<Text className="text-center text-[11.5px] font-extrabold text-ink2">{p.branch_ten_god}</Text>
{p.position === 'month' && <Text className="text-center text-[10.5px] font-extrabold text-ink3">월령</Text>}
</>
) : (
<View className="flex-1 items-center justify-center rounded-xl px-1" style={{ backgroundColor: soft.soft }}>
<Text className="text-center text-[12px] font-extrabold text-ink3">시각 모름</Text>
</View>
)}
</View>
))}
</View>
<View className="mt-3 border-t border-line pt-2.5">
{!!strength && <Note term={strength} word={STRENGTH_WORD[strength] ?? ''} />}
{gods.map((g) => (
<Note key={g} term={g} word={TEN_GOD_WORD[g]} />
))}
<Note term="월령" word="태어난 달의 계절 기운. 명식에서 가장 크게 봐요" />
</View>
{(me.need?.length ?? 0) > 0 && <Text className="mt-2 text-[13px] font-bold text-ink">내 기운에 좋은 날씨: {me.need!.join(' · ')}</Text>}
{me.jeol_warning && <Text className="mt-1 text-xs font-semibold text-warn">태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.</Text>}
</Panel>
);
}
+171
View File
@@ -0,0 +1,171 @@
import type { ResSaju, SajuLock } from '@nalssigak/shared/api/client/types.gen';
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { progress, useLevel } from '@/lib/level';
import { useSaveBirth, type Birth } from '@/lib/saju-birth';
import { useSheet } from '@/lib/sheet';
import { dayWord, Panel } from './parts';
/** 앞으로 7일 흐름 (Lv.2) */
export function Week({ days }: { days: NonNullable<ResSaju['week']> }) {
const soft = useSoft();
return (
<Panel id="saju_week" icon="spiral_calendar" title="앞으로 7일 흐름">
<View className="gap-1">
{days.map((d) => (
<View key={d.day} className="flex-row items-center gap-2 rounded-xl px-2 py-1.5" style={d.best ? { backgroundColor: soft.warm } : undefined}>
<Text numberOfLines={1} className="w-[66px] text-[13px] font-bold text-ink">
{dayWord(d.day, d.weekday)}
</Text>
{d.icon ? <Ic name={d.icon} size={24} /> : <View className="size-6" />}
<Text numberOfLines={1} className="w-[52px] text-[13px] font-bold text-ink2">
{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}
</Text>
<Text numberOfLines={1} className="min-w-0 flex-1 text-[12.5px] font-bold text-ink2">
{d.title}
</Text>
<Text className={`font-bagel text-[15px] ${d.best ? 'text-orange' : 'text-ink'}`}>{d.score}</Text>
</View>
))}
</View>
<Text className="mt-1.5 text-xs font-semibold text-ink3">점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.</Text>
</Panel>
);
}
/** 금전운·일운 (Lv.3) */
export function Money({ money, work }: { money: string[]; work: string[] }) {
const lines = [...money.map((l) => ['money_bag', l]), ...work.map((l) => ['briefcase', l])];
return (
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
<View className="gap-1.5">
{lines.map(([icon, l]) => (
<View key={l} className="flex-row gap-2">
<Ic name={icon} size={20} />
<Text className="min-w-0 flex-1 text-[14px] font-semibold text-ink">{l}</Text>
</View>
))}
</View>
</Panel>
);
}
/** 앞으로 7일 연애운 (Lv.4). 성별을 고르면 이성 인연까지 */
export function Love({ love, birth }: { love: NonNullable<ResSaju['love']>; birth: Birth }) {
const soft = useSoft();
const save = useSaveBirth();
const pick = (g: 'M' | 'F' | null) => void save({ ...birth, gender: g });
return (
<Panel id="saju_love" icon="red_heart" title="앞으로 7일 연애운">
{love.good ? (
<View className="rounded-xl px-3 py-2.5" style={{ backgroundColor: soft.warm }}>
<Text className="text-xs font-extrabold text-heart">연애 기운이 좋은 날</Text>
<Text className="font-jua text-[17px] text-ink">
{dayWord(love.good.day, love.good.weekday)}
{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
</Text>
<Text className="text-[13px] font-semibold text-ink">{love.good.body}</Text>
<Text className="text-[11.5px] font-semibold text-ink3">{love.good.why}</Text>
</View>
) : (
<Text className="text-[13px] font-semibold text-ink2">앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.</Text>
)}
{!!love.caution && (
<Text className="mt-2 text-[13px] font-semibold text-ink">
조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} <Text className="text-ink3">· {love.caution.why}</Text>
</Text>
)}
{love.gender_known ? (
<Text className="mt-2.5 text-xs font-bold text-ink3">
{birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '}
<Text onPress={() => pick(null)} accessibilityRole="button" className="font-extrabold text-orange">
빼고 보기
</Text>
</Text>
) : (
<View className="mt-2.5 flex-row flex-wrap items-center gap-1.5">
<Text className="text-xs font-bold text-ink2">성별을 고르면 이성 인연(재성·관성)까지 봐요</Text>
{(
[
['M', '남성'],
['F', '여성'],
] as const
).map(([g, word]) => (
<Pressable key={g} onPress={() => pick(g)} accessibilityRole="button" className="rounded-full px-2.5 py-1" style={{ backgroundColor: soft.soft }}>
<Text className="text-xs font-bold text-ink2">{word}</Text>
</Pressable>
))}
</View>
)}
</Panel>
);
}
/** 이달·올해 (Lv.6·7) */
export function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResSaju['month']> }) {
return (
<Panel id={id} icon={icon} title={p.label}>
<Text className="font-jua text-[17px] text-ink">
{p.title} <Text className="text-[13px] text-ink3">({p.ten_god})</Text>
</Text>
<Text className="mt-0.5 text-[13.5px] font-semibold text-ink">{p.body}</Text>
{(p.months?.length ?? 0) > 0 && (
<Text className="mt-1.5 text-[13.5px] font-bold text-ink">
{p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}
</Text>
)}
{p.notes?.map((n) => (
<Text key={n} className="mt-1 text-xs font-semibold text-ink3">
{n}
</Text>
))}
</Panel>
);
}
/** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */
export function Locked({ locks }: { locks: SajuLock[] }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const soft = useSoft();
const level = useLevel().data;
if (!locks.length) return null;
const [next, ...rest] = [...locks].sort((a, b) => a.level - b.level);
const close = loggedIn && !!level && level.next_points != null && level.level + 1 === next.level;
return (
<View className="mx-4 rounded-[22px] px-4 py-3.5" style={{ backgroundColor: soft.soft }}>
<View className="flex-row items-center gap-3">
<Ic name="locked" size={32} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] text-ink">{loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}</Text>
<Text className="text-xs font-bold text-ink2">
{loggedIn ? (close && level ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"}
</Text>
</View>
<Pressable onPress={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} accessibilityRole="button" className="rounded-full bg-ink-btn px-3 py-1.5">
<Text className="text-xs font-extrabold text-white">{loggedIn ? '각 모으는 법' : '로그인'}</Text>
</Pressable>
</View>
{close && !!level && (
<View className="mt-2.5 h-1.5 overflow-hidden rounded-full bg-card">
<LinearGradient colors={['#ffb27a', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${Math.round(progress(level) * 100)}%`, borderRadius: 999 }} />
</View>
)}
<View className="mt-2.5 flex-row flex-wrap gap-1.5">
{(loggedIn ? rest : [next, ...rest]).map((l) => (
<View key={l.key} className="rounded-full bg-card px-2.5 py-1">
<Text className="text-[11.5px] font-extrabold text-ink2">
Lv.{l.level} {l.name}
</Text>
</View>
))}
</View>
</View>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { createContext, use, type ReactNode } from 'react';
import { View } from 'react-native';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
export const EL_COLOR: Record<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] };
export const EL_WORD: Record<string, string> = { 木: '나무', 火: '불', 土: '흙', 金: '쇠', 水: '물' };
// 오행 그림 (웹 public/saju). Metro 는 정적 require 만 묶을 수 있어 하나씩 적는다
export const EL_ART: Record<string, number> = {
木: require('../../../../frontend/public/saju/wood.webp'),
火: require('../../../../frontend/public/saju/fire.webp'),
土: require('../../../../frontend/public/saju/earth.webp'),
金: require('../../../../frontend/public/saju/metal.webp'),
水: require('../../../../frontend/public/saju/water.webp'),
};
/** 2026-11-04 + 수 → 11/4(수) */
export const dayWord = (iso: string, weekday: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}(${weekday})`;
/** ?open= 으로 연 칸: 그 칸이 자리를 잡으면 화면이 그 위치로 내려간다 (웹 #hash 스크롤) */
export const OpenTarget = createContext<{ id?: string; onLayout: (y: number) => void }>({ onLayout: () => {} });
/** 흰 판: 아이콘·제목·오른쪽 버튼 */
export function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) {
const target = use(OpenTarget);
const mine = !!id && target.id === id;
return (
<View onLayout={mine ? (e) => target.onLayout(e.nativeEvent.layout.y) : undefined} className="mx-4 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3.5">
<View className="mb-2 flex-row items-center gap-2">
<Ic name={icon} size={28} />
<Text className="font-jua text-[17px] text-ink">{title}</Text>
{right != null && <View className="ml-auto">{right}</View>}
</View>
{children}
</View>
);
}
+131
View File
@@ -0,0 +1,131 @@
import { useState } from 'react';
import { Pressable, View } from 'react-native';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
/** 고르는 칸: 누르면 아래에 칩이 펼쳐진다 (웹 input·select 대신. 숫자 자판 없이 눌러서 고른다) */
export function Box({ label, value, placeholder, open, onPress, disabled, flex = 1 }: { label: string; value: string | null; placeholder: string; open: boolean; onPress: () => void; disabled?: boolean; flex?: number }) {
const soft = useSoft();
return (
<Pressable
onPress={onPress}
disabled={disabled}
accessibilityRole="button"
accessibilityLabel={`${label} ${value ?? placeholder}`}
accessibilityState={{ expanded: open, disabled }}
className={`min-h-[48px] min-w-0 flex-row items-center justify-center gap-1 rounded-2xl px-2 py-2.5 ${disabled ? 'opacity-45' : ''}`}
style={{ flex, backgroundColor: soft.field, borderWidth: 1.5, borderColor: open ? '#ff7a45' : soft.fieldBorder }}
>
<Text numberOfLines={1} className={`text-[17px] font-bold ${value != null ? 'text-ink' : 'text-ink3'}`}>
{value ?? placeholder}
</Text>
<Text className="text-[11px] text-ink3">{open ? '▲' : '▼'}</Text>
</Pressable>
);
}
/** 칩 여러 개 중 하나 고르기 */
export function ChipGrid<K extends string | number>({ items, value, onPick, label, wide }: { items: [K, string][]; value: K | null; onPick: (k: K) => void; label: string; wide?: boolean }) {
const soft = useSoft();
return (
<View accessibilityRole="radiogroup" accessibilityLabel={label} className="flex-row flex-wrap gap-1.5 rounded-2xl p-2" style={{ backgroundColor: soft.soft }}>
{items.map(([k, word]) => {
const on = value === k;
return (
<Pressable key={String(k)} onPress={() => onPick(k)} accessibilityRole="radio" accessibilityState={{ checked: on }} className={`min-h-[40px] items-center justify-center rounded-xl px-1 ${wide ? 'w-[64px]' : 'w-[44px]'} ${on ? 'bg-orange' : 'bg-card'}`}>
<Text className={`text-[14px] font-bold ${on ? 'text-white' : 'text-ink'}`}>{word}</Text>
</Pressable>
);
})}
</View>
);
}
/** 연도: 먼저 10년 단위를 고르고 그 안에서 연도 */
function YearGrid({ value, onPick, label }: { value: number | null; onPick: (y: number) => void; label: string }) {
const thisYear = new Date().getFullYear();
const [decade, setDecade] = useState(value != null ? Math.floor(value / 10) * 10 : 1990);
const decades: [number, string][] = [];
for (let d = 1900; d <= thisYear; d += 10) decades.push([d, `${String(d).slice(2)}년대`]);
const years: [number, string][] = [];
for (let y = decade; y < decade + 10 && y <= thisYear; y++) years.push([y, String(y)]);
return (
<View className="gap-1.5">
<ChipGrid label={`${label} 10년 단위`} items={decades} value={decade} onPick={setDecade} wide />
<ChipGrid label={label} items={years} value={value} onPick={onPick} wide />
</View>
);
}
const MONTHS: [number, string][] = Array.from({ length: 12 }, (_, i) => [i + 1, `${i + 1}월`]);
const daysIn = (y: number | null, m: number | null) => (m == null ? 31 : new Date(y ?? 2000, m, 0).getDate());
export type Ymd = { y: number | null; m: number | null; d: number | null };
/** 생년월일(양력) 고르기: 연도 → 월 → 일 순서로 이어서 펼친다 */
export function DatePick({ value, onChange, label = '' }: { value: Ymd; onChange: (v: Ymd) => void; label?: string }) {
const [open, setOpen] = useState<'y' | 'm' | 'd' | null>(null);
const toggle = (k: 'y' | 'm' | 'd') => setOpen((o) => (o === k ? null : k));
const days: [number, string][] = Array.from({ length: daysIn(value.y, value.m) }, (_, i) => [i + 1, String(i + 1)]);
return (
<View className="gap-1.5">
<View className="flex-row gap-1.5">
<Box label={`${label}년`} value={value.y != null ? `${value.y}년` : null} placeholder="연도" open={open === 'y'} onPress={() => toggle('y')} flex={1.5} />
<Box label={`${label}월`} value={value.m != null ? `${value.m}월` : null} placeholder="월" open={open === 'm'} onPress={() => toggle('m')} />
<Box label={`${label}일`} value={value.d != null ? `${value.d}일` : null} placeholder="일" open={open === 'd'} onPress={() => toggle('d')} />
</View>
{open === 'y' ? (
<YearGrid
label={`${label}년`}
value={value.y}
onPick={(y) => {
onChange({ ...value, y });
setOpen(value.m == null ? 'm' : null);
}}
/>
) : open === 'm' ? (
<ChipGrid
label={`${label}월`}
items={MONTHS}
value={value.m}
onPick={(m) => {
onChange({ ...value, m });
setOpen(value.d == null ? 'd' : null);
}}
wide
/>
) : open === 'd' ? (
<ChipGrid
label={`${label}일`}
items={days}
value={value.d}
onPick={(d) => {
onChange({ ...value, d });
setOpen(null);
}}
/>
) : null}
</View>
);
}
/** 숫자: −/+ 버튼 (분) */
export function Stepper({ value, onChange, min, max, label, unit, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string; unit: string; disabled?: boolean }) {
const soft = useSoft();
const set = (v: number) => onChange(Math.min(max, Math.max(min, v)));
return (
<View className={`min-h-[48px] flex-1 flex-row items-center justify-between rounded-2xl ${disabled ? 'opacity-45' : ''}`} style={{ backgroundColor: soft.field, borderWidth: 1.5, borderColor: soft.fieldBorder }} accessibilityLabel={label}>
<Pressable onPress={() => set(value - 1)} onLongPress={() => set(value - 10)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-3.5 py-2">
<Text className="text-[18px] font-extrabold text-ink2">−</Text>
</Pressable>
<Text className="text-[17px] font-bold text-ink">
{value}
{unit}
</Text>
<Pressable onPress={() => set(value + 1)} onLongPress={() => set(value + 10)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-3.5 py-2">
<Text className="text-[18px] font-extrabold text-ink2">+</Text>
</Pressable>
</View>
);
}
+172
View File
@@ -0,0 +1,172 @@
import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { reading } from '@nalssigak/shared/api/client/sdk.gen';
import type { SajuCard } from '@nalssigak/shared/api/client/types.gen';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef } from 'react';
import { Pressable, View } from 'react-native';
import Svg, { Circle } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useLevel } from '@/lib/level';
import { useRegion } from '@/lib/region';
import { markSajuSeen, toBody, type Birth } from '@/lib/saju-birth';
import { useShare } from '@/lib/share-image';
import { SITE_URL } from '@/lib/site';
import { Match } from './match';
import { MeCard } from './me-card';
import { Locked, Love, Money, Period, Week } from './panels';
const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' };
function DecisionCard({ c }: { c: SajuCard }) {
return (
<View className="flex-row gap-3 rounded-[20px] border-b-4 border-shade bg-card px-4 py-3">
<Ic name={CARD_ICON[c.kind] ?? 'sparkles'} size={32} />
<View className="min-w-0 flex-1">
<Text className="text-[12px] font-extrabold text-orange">{c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}</Text>
<Text className="font-jua text-[17px] leading-snug text-ink">{c.kind === 'when' ? `${c.title} · ${c.sub ?? ''}` : c.body}</Text>
<Text className="mt-0.5 text-[12px] leading-snug font-semibold text-ink3">{(c.kind === 'when' ? c.body : c.sub) ?? ''}</Text>
</View>
</View>
);
}
const RING_R = 46;
const RING_LEN = 2 * Math.PI * RING_R;
function ScoreRing({ score }: { score: number }) {
const soft = useSoft();
return (
<View className="size-[116px] items-center justify-center" accessibilityLabel={`오늘의 점수 ${score}점`}>
<Svg viewBox="0 0 116 116" width={116} height={116} style={{ position: 'absolute', transform: [{ rotate: '-90deg' }] }}>
<Circle cx={58} cy={58} r={RING_R} fill="none" stroke={soft.bar} strokeWidth={11} />
<Circle cx={58} cy={58} r={RING_R} fill="none" stroke="#ff7a45" strokeWidth={11} strokeLinecap="round" strokeDasharray={`${(RING_LEN * score) / 100} ${RING_LEN}`} />
</Svg>
<Text className="font-bagel text-[40px] leading-[44px] text-ink">{score}</Text>
<Text className="text-[11px] font-extrabold text-ink3">오늘의 점수</Text>
</View>
);
}
function ScoreBar({ label, value, width, color, signed }: { label: string; value: number; width: number; color: string; signed?: boolean }) {
const soft = useSoft();
return (
<View className="mt-2">
<View className="flex-row justify-between">
<Text className="text-[12.5px] font-extrabold" style={{ color }}>
{label}
</Text>
<Text className="text-[12.5px] font-extrabold" style={{ color }}>
{`${signed ? (value >= 0 ? '+' : '−') : ''}${Math.abs(value)}점`}
</Text>
</View>
<View className="mt-1 h-2 overflow-hidden rounded-full" style={{ backgroundColor: soft.bar }}>
<View className="h-full rounded-full" style={{ width: `${width}%`, backgroundColor: color }} />
</View>
</View>
);
}
/** 오늘 점수와 할 일, 내 기운, 레벨로 열리는 이번 주·금전·연애·궁합·이달·올해 (웹 SajuPage Reading) */
export function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) {
const { region } = useRegion();
const { loggedIn } = useAuth();
const queryClient = useQueryClient();
const soft = useSoft();
const ink = String(useCSSVariable('--color-ink'));
const share = useShare();
const level = useLevel().data?.level;
const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined };
// 레벨이 오르면 키가 바뀌어 새로 열린 칸까지 다시 받는다. 사주를 보면 각이 쌓이니 레벨도 새로 받는다
const q = useQuery({
queryKey: ['saju', body, loggedIn, level],
staleTime: 10 * 60_000,
queryFn: async () => {
const { data } = await reading({ body });
if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju');
if (loggedIn) void queryClient.invalidateQueries({ queryKey: myLevelQueryKey() });
return data;
},
});
const shot = useRef<View>(null);
const r = q.data;
useEffect(() => {
if (!r?.today) return;
markSajuSeen();
track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score, strength: r.me?.strength ?? '', top_element: r.me?.top_element ?? '' });
}, [r]);
if (q.isPending) return <Text className="px-4 py-16 text-center font-semibold text-ink2">사주를 풀고 있어요…</Text>;
if (!r?.today || !r.me)
return (
<View className="items-center px-4 py-16">
<Text className="text-center font-semibold text-ink2">결과를 불러오지 못했어요.</Text>
<Pressable onPress={() => void q.refetch()} accessibilityRole="button" className="mt-3 rounded-full bg-ink-btn px-4 py-2">
<Text className="text-[13px] font-extrabold text-white">다시 시도</Text>
</Pressable>
</View>
);
const t = r.today;
const matchOpen = !!r.locks?.find((l) => l.key === 'saju_match')?.unlocked;
const title = `오늘 내 날씨 사주 ${t.score}점 · ${t.title}`;
return (
<View className="gap-3">
<View ref={shot} collapsable={false} className="mx-4 mt-3 rounded-[26px] border-b-[5px] border-shade bg-card p-4">
<Text className="text-[12.5px] font-extrabold text-ink3">
{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수
</Text>
<View className="mt-2 flex-row items-center gap-4">
<ScoreRing score={t.score} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[21px] leading-tight text-ink">{t.title}</Text>
<ScoreBar label="사주" value={t.saju_score} width={t.saju_score} color={ink} />
{t.weather_points != null && <ScoreBar label="날씨 영향" value={t.weather_points} width={Math.min(100, Math.abs(t.weather_points) * 3)} color={t.weather_points >= 0 ? '#1f7a4f' : '#e8663a'} signed />}
</View>
</View>
{(t.why?.length ?? 0) > 0 && (
<View className="mt-3 gap-1.5">
{t.why!.map((w) => {
const down = w.startsWith('↓');
return (
<Text key={w} className={`overflow-hidden rounded-xl px-3 py-2 text-[13px] leading-snug font-bold ${down ? 'text-warn' : 'text-ink'}`} style={{ backgroundColor: down ? soft.warm : soft.soft }}>
{w}
</Text>
);
})}
</View>
)}
</View>
<View className="mx-4 gap-2">
{t.cards.map((c) => (
<DecisionCard key={c.kind} c={c} />
))}
</View>
<MeCard r={r} onEdit={onEdit} />
{!!r.week && <Week days={r.week} />}
{!!r.money && <Money money={r.money} work={r.work ?? []} />}
{!!r.love && <Love love={r.love} birth={birth} />}
{matchOpen && <Match birth={birth} />}
{!!r.month && <Period id="saju_month" icon="spiral_calendar" p={r.month} />}
{!!r.year && <Period id="saju_year" icon="sunrise" p={r.year} />}
<Locked locks={(r.locks ?? []).filter((l) => !l.unlocked)} />
<View className="mx-4 flex-row items-center justify-between">
<Text className="text-xs font-semibold text-ink3">재미로 보는 날씨 사주</Text>
<Pressable onPress={() => void share(shot, { title, message: `${title} ${SITE_URL}/saju` })} accessibilityRole="button" className="rounded-full bg-ink-btn px-4 py-2">
<Text className="text-[13px] font-extrabold text-white">공유</Text>
</Pressable>
</View>
</View>
);
}
+31
View File
@@ -0,0 +1,31 @@
import { router } from 'expo-router';
import { Pressable, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { useCSSVariable } from 'uniwind';
import { Text } from '@/components/text';
import { useSky } from '@/lib/sky';
/** 탭 밖 화면(사주·이야기·게임 등) 머리줄: 뒤로 가기와 제목. 뒤로 갈 곳이 없으면(링크로 바로 열림) 오늘 탭으로 */
export function ScreenHeader({ title, right }: { title: string; right?: React.ReactNode }) {
const { top } = useSafeAreaInsets();
const { kind } = useSky();
const ink = String(useCSSVariable('--color-ink'));
const back = () => (router.canGoBack() ? router.back() : router.replace('/'));
return (
<View style={{ paddingTop: top, backgroundColor: kind === 'night' ? 'rgb(14 20 51 / 0.35)' : 'rgb(255 255 255 / 0.18)' }}>
<View className="h-[54px] flex-row items-center gap-1 px-2">
<Pressable onPress={back} hitSlop={8} accessibilityRole="button" accessibilityLabel="뒤로" className="size-10 items-center justify-center">
<Svg viewBox="0 0 24 24" width={24} height={24} fill="none" stroke={ink} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round">
<Path d="M15 5l-7 7 7 7" />
</Svg>
</Pressable>
<Text numberOfLines={1} className="flex-1 font-jua text-[21px] text-ink">
{title}
</Text>
{right}
</View>
</View>
);
}
+3 -3
View File
@@ -62,7 +62,7 @@ export function SeasonHead({ week: w, onPress }: { week: ResSeasonWeek; onPress:
<Text className="text-[13px] font-extrabold text-ink opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</Text>
<Text className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight text-ink">{w.headline}</Text>
{poem.length > 0 && <Text className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[37px] text-ink">{poem.join('\n')}</Text>}
{w.term_now && w.term_next && (
{!!w.term_now && !!w.term_next && (
<View className={`max-w-[70%] ${poem.length ? 'mt-2.5' : 'mt-auto'}`}>
<View className="flex-row justify-between">
<Text className="text-xs font-extrabold text-ink2">
@@ -88,7 +88,7 @@ export function ArticleRow({ article: a, onPress }: { article: ArticleSummary; o
return (
<Pressable onPress={onPress} className={ROW}>
<View className="flex-1">
{ARTICLE_LABEL[a.category] && (
{!!ARTICLE_LABEL[a.category] && (
<Text className="text-xs font-extrabold" style={{ color }}>
{ARTICLE_LABEL[a.category]}
</Text>
@@ -98,7 +98,7 @@ export function ArticleRow({ article: a, onPress }: { article: ArticleSummary; o
</View>
<Thumb image={a.image} icon={a.icon} iconSize={54} className="h-[84px] w-[84px] rounded-[18px]">
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
{a.image && a.image_credit && <Credit text={a.image_credit} />}
{!!a.image && !!a.image_credit && <Credit text={a.image_credit} />}
</Thumb>
</Pressable>
);
+12 -4
View File
@@ -2,11 +2,12 @@ import { getArticleOptions, getSeasonWeekOptions } from '@nalssigak/shared/api/c
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 { useEffect, useRef } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Credit, Ic, StateBox, Thumb } from '@/components/ui';
import { track } from '@/lib/analytics';
import { CARD_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
@@ -22,13 +23,20 @@ export function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitl
onTitle(a ? (ARTICLE_LABEL[a.category] ?? '') : '');
}, [a, onTitle]);
const tracked = useRef(0);
useEffect(() => {
if (!a || tracked.current === a.article_id) return;
tracked.current = a.article_id;
track('select_content', { content_type: 'article', item_id: a.article_id, category: ARTICLE_LABEL[a.category] ?? a.category });
}, [a]);
const load = loadOf(q);
if (!a) return <Body>{load === 'loading' ? <ArticleSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." hold={<ArticleSkel />} boxClassName="inset-0" />}</Body>;
return (
<Body>
<Thumb image={a.image} icon={a.icon} iconSize={96} className="mb-3.5 h-[150px] rounded-[20px]">
<LinearGradient colors={CARD_BG[night ? 'night' : 'day'][cardBg(a.icon, a.article_id)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
{a.image && a.image_credit && <Credit text={a.image_credit} />}
{!!a.image && !!a.image_credit && <Credit text={a.image_credit} />}
</Thumb>
<Text className="text-[13px] font-extrabold text-ink2">{articleMeta(a)}</Text>
<Text className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight text-ink">{a.title}</Text>
@@ -61,10 +69,10 @@ export function SeasonWeekSheet() {
<Text className="font-batang text-[17px] leading-[29px] text-ink">
{w.poem_lines?.join(' ')}
</Text>
{w.author && <Text className="text-xs font-semibold text-ink3">{w.author}</Text>}
{!!w.author && <Text className="text-xs font-semibold text-ink3">{w.author}</Text>}
</View>
)}
{w.term_now && w.term_next && (
{!!w.term_now && !!w.term_next && (
<Text className="mb-2.5 text-[15px] leading-[1.7] text-ink">
지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요.
</Text>
+69 -38
View File
@@ -1,5 +1,6 @@
import {
addCommentMutation,
addTalkCommentMutation,
agreeTermsMutation,
blockAuthorMutation,
deleteCommentMutation,
@@ -8,6 +9,8 @@ import {
listBlockedQueryKey,
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listTalkCommentsInfiniteOptions,
listTalkCommentsInfiniteQueryKey,
meQueryKey,
reportCommentMutation,
unlikeCommentMutation,
@@ -21,9 +24,10 @@ import { Text } from '@/components/text';
import { useCSSVariable } from 'uniwind';
import { Avatar, Skel, StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { useSheet, type CommentTarget } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { Body, ErrorLine, Field, HeartIcon, useSoft } from './parts';
@@ -37,7 +41,13 @@ const REPORT_REASONS = [
[ReportReason.PRIVACY, '개인정보 노출'],
[ReportReason.OTHER, '기타'],
] as const;
export const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments';
export const isCommentList = (q: { queryKey: readonly unknown[] }) => ['listComments', 'listTalkComments'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '');
const isTalkList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listTalks';
/** 댓글 목록 캐시 키: 지우기·신고 뒤 다시 받을 때 쓴다 */
function commentListKey(to: CommentTarget) {
return 'talkId' in to ? listTalkCommentsInfiniteQueryKey({ path: { talk_id: to.talkId } }) : listCommentsInfiniteQueryKey({ path: { post_id: to.postId } });
}
function Chip({ label, onPress, disabled, danger }: { label: string; onPress: () => void; disabled?: boolean; danger?: boolean }) {
const s = useSoft();
@@ -49,7 +59,7 @@ function Chip({ label, onPress, disabled, danger }: { label: string; onPress: ()
}
/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */
function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
function CommentMenu({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
@@ -59,9 +69,10 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
const block = useMutation(blockAuthorMutation());
const pending = report.isPending || block.isPending;
const finish = (notice: string) => ({
const finish = (notice: string, done: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true);
done();
setStep('closed');
onNotice(notice);
queryClient.invalidateQueries({ predicate: isCommentList });
@@ -71,7 +82,7 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
});
const go = (next: typeof step) => {
setFailed(false);
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } });
if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', ...to } });
setStep(next);
};
@@ -90,12 +101,12 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
)}
{step === 'report' &&
REPORT_REASONS.map(([reason, label]) => (
<Chip key={reason} label={label} disabled={pending} onPress={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))} />
<Chip key={reason} label={label} disabled={pending} onPress={() => report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.', () => track('report', { content_type: 'comment', reason })))} />
))}
{step === 'block' && (
<>
<Text className="w-full text-[13px] font-bold text-ink">{c.nickname}님 댓글을 더는 안 볼까요?</Text>
<Chip label="차단하기" danger disabled={pending} onPress={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))} />
<Chip label="차단하기" danger disabled={pending} onPress={() => block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.', () => track('block', { content_type: 'comment' })))} />
<Chip label="취소" disabled={pending} onPress={() => go('closed')} />
</>
)}
@@ -126,10 +137,8 @@ function CommentsSkel() {
);
}
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
function CommentRow({ c, to, onNotice }: { c: CommentData; to: CommentTarget; onNotice: (text: string) => void }) {
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);
@@ -140,8 +149,8 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
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);
@@ -158,11 +167,12 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
if (res.result?.success) {
setLiked(!!res.liked);
if (res.like_count != null) setCount(res.like_count);
if (next) track('like', { content_type: 'comment', item_id: c.comment_id });
return;
}
revert();
// 그 사이 지워진 댓글이면 알림 없이 목록을 다시 받아 사라지게 한다
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
if (res.result?.code === NOT_FOUND) queryClient.invalidateQueries({ queryKey: commentListKey(to) });
else setLikeFailed(true);
},
onError: () => {
@@ -181,13 +191,14 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
{
onSuccess: async (res) => {
if (!res.result?.success) return setRemoveFailed(true);
const key = listCommentsInfiniteQueryKey({ path: { post_id: postId } });
const key = commentListKey(to);
await queryClient.cancelQueries({ queryKey: key });
queryClient.setQueryData<InfiniteData<ResCommentList>>(key, (data) =>
data ? { ...data, pages: data.pages.map((p) => ({ ...p, comments: p.comments?.filter((x) => x.comment_id !== c.comment_id) })) } : data,
);
queryClient.invalidateQueries({ queryKey: key });
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
if ('talkId' in to) queryClient.invalidateQueries({ predicate: isTalkList });
else queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
},
onError: () => setRemoveFailed(true),
},
@@ -220,7 +231,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
)}
</Text>
{/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */}
{!c.mine && !c.official && <CommentMenu c={c} postId={postId} onNotice={onNotice} />}
{!c.mine && !c.official && <CommentMenu c={c} to={to} onNotice={onNotice} />}
</View>
</View>
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="댓글 좋아요" className="pt-1">
@@ -230,17 +241,31 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
);
}
export function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
/** 포스트 댓글, 또는 사람 글 댓글(로그인한 사람만 쓴다) */
export function CommentsSheet({ to, draft }: { to: CommentTarget; draft?: string }) {
const { region } = useRegion();
const { me } = useAuth();
const { open } = useSheet();
const { loggedIn, me } = useAuth();
const queryClient = useQueryClient();
const list = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
initialPageParam: { path: { post_id: postId } },
const talkId = 'talkId' in to ? to.talkId : undefined;
const postId = 'postId' in to ? to.postId : undefined;
// 둘 중 하나만 받는다
const postList = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId ?? 0 } }),
initialPageParam: { path: { post_id: postId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: postId != null,
});
const add = useMutation(addCommentMutation());
const talkList = useInfiniteQuery({
...listTalkCommentsInfiniteOptions({ path: { talk_id: talkId ?? 0 } }),
initialPageParam: { path: { talk_id: talkId ?? 0 } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
enabled: talkId != null,
});
const list = talkId != null ? talkList : postList;
const addPost = useMutation(addCommentMutation());
const addTalk = useMutation(addTalkCommentMutation());
const add = { isPending: addPost.isPending || addTalk.isPending };
const agree = useMutation(agreeTermsMutation());
const s = useSoft();
const [addFailed, setAddFailed] = useState(false);
@@ -260,25 +285,30 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
const body = text.trim();
if (!body || add.isPending) return;
setAddFailed(false);
add.mutate(
{ path: { post_id: postId }, body: { body } },
{
onSuccess: (res) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
setAddFailed(!res.result?.success);
if (!res.result?.success) return;
setText('');
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) });
const handlers = {
onSuccess: (res: { result?: { success?: boolean; desc?: string } }) => {
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true);
setAddFailed(!res.result?.success);
if (!res.result?.success) return;
setText('');
queryClient.invalidateQueries({ queryKey: commentListKey(to) });
if (talkId != null) {
track('talk_comment', { talk_id: talkId });
queryClient.invalidateQueries({ predicate: isTalkList });
} else if (postId != null) {
track('comment', { post_id: postId });
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) });
},
onError: () => setAddFailed(true),
}
},
);
onError: () => setAddFailed(true),
};
if (talkId != null) addTalk.mutate({ path: { talk_id: talkId }, body: { body } }, handlers);
else if (postId != null) addPost.mutate({ path: { post_id: postId }, body: { body, region: region.code } }, handlers);
};
// 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
// 댓글은 로그인 없이 '○○구 익명'으로 쓴다. 로그인했으면 약관에 동의해야 쓸 수 있고, 동의하면 쓰던 댓글을 바로 올린다
const submit = () => {
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } });
if (talkId != null && !me) return open({ type: 'login', then: { type: 'comments', ...to, draft: text } });
if (me && !me.terms_agreed) return setAskTerms(true);
send();
};
@@ -290,6 +320,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
onSuccess: (res) => {
if (!res.result?.success) return setAddFailed(true);
queryClient.setQueryData(meQueryKey(), res);
track('terms_agree', {});
setAskTerms(false);
send();
},
@@ -305,7 +336,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
<>
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
{comments.map((c) => (
<CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} onNotice={setNotice} />
<CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} to={to} onNotice={setNotice} />
))}
{list.hasNextPage && (
<Pressable onPress={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50">
@@ -351,9 +382,9 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin
{addFailed ? <ErrorLine className="h-4 text-xs leading-4" text="댓글을 올리지 못했어요. 다시 해 주세요." /> : <Text className="h-4 text-center text-xs leading-4 font-bold text-ink2">{notice}</Text>}
<View className="flex-row items-center gap-2.5 border-t border-line px-3 py-2.5">
<View className="flex-1">
<Field ref={inputRef} round value={text} onChangeText={setText} editable={!add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} accessibilityLabel="댓글" returnKeyType="send" onSubmitEditing={submit} />
<Field ref={inputRef} round value={text} onChangeText={setText} editable={!add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : talkId != null ? '로그인하고 댓글 달기…' : '댓글 달기…'} accessibilityLabel="댓글" returnKeyType="send" onSubmitEditing={submit} />
</View>
<Pressable onPress={submit} disabled={add.isPending || (loggedIn && !text.trim())} className="disabled:opacity-40">
<Pressable onPress={submit} disabled={add.isPending || !text.trim()} className="disabled:opacity-40">
<Text className="font-extrabold text-rain">{add.isPending ? '올리는 중…' : '게시'}</Text>
</Pressable>
</View>
+14 -5
View File
@@ -3,12 +3,13 @@ import type { Factor, ResIndexDetail } from '@nalssigak/shared/api/client/types.
import { loadOf } from '@nalssigak/shared/lib';
import { useQuery } from '@tanstack/react-query';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';
import { View } from 'react-native';
import { Text } from '@/components/text';
import Svg, { Circle, Line, Polygon, Text as SvgText, TSpan } from 'react-native-svg';
import { Ic, Skel, StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useRegion } from '@/lib/region';
import { useSky } from '@/lib/sky';
@@ -110,6 +111,14 @@ export function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: s
onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거');
}, [g, onTitle]);
// 지역이 바뀌어 다시 받아도 한 번만 보낸다
const tracked = useRef(0);
useEffect(() => {
if (!g || tracked.current === g.index_id) return;
tracked.current = g.index_id;
track('view_gak', { index_id: g.index_id, gak_name: g.name, score: g.score, rank: g.rank });
}, [g]);
const load = loadOf(q);
if (!g) return <Body>{load === 'loading' ? <GakSkel /> : <StateBox load={load} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={<GakSkel />} boxClassName="inset-0" />}</Body>;
const factors = d.factors ?? [];
@@ -121,7 +130,7 @@ export function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: s
<Ic name={g.icon} size={58} />
<View className="flex-1">
<Text className="font-jua text-[22px] text-ink">{g.name}</Text>
{d.description && <Text className="mt-0.5 text-[13.5px] font-semibold text-ink2">{d.description}</Text>}
{!!d.description && <Text className="mt-0.5 text-[13.5px] font-semibold text-ink2">{d.description}</Text>}
</View>
<Text className={`font-bagel text-[42px] ${g.active ? 'text-orange' : 'text-ink3'}`}>{g.score}</Text>
</View>
@@ -194,7 +203,7 @@ export function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: s
))}
</View>
<View className="mt-3.5 gap-1.5">
{d.zero_reason && (
{!!d.zero_reason && (
<Text className="text-[13px] font-semibold text-ink2">
<Text className="font-bold text-heart">오늘 걸린 조건:</Text> {d.zero_reason}
</Text>
@@ -204,12 +213,12 @@ export function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: s
<Text className="font-bold text-ink">계산 방법:</Text> 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요
</Text>
)}
{d.zero_rules && (
{!!d.zero_rules && (
<Text className="text-[13px] font-semibold text-ink2">
<Text className="font-bold text-ink">점수 깎이는 조건:</Text> {d.zero_rules}
</Text>
)}
{d.limit && (
{!!d.limit && (
<Text className="text-[13px] font-semibold text-ink2">
<Text className="font-bold text-ink">반영 못 한 것:</Text> {d.limit}
</Text>
+17 -5
View File
@@ -5,18 +5,25 @@ import { Text } from '@/components/text';
import Animated, { Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withTiming } from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { MixSheet, MyGakSheet } from '@/components/my-gak/my-gak';
import { track } from '@/lib/analytics';
import { SheetContext, useSheet, type SheetState } from '@/lib/sheet';
import { ArticleSheet, SeasonWeekSheet } from './article';
import { CommentsSheet } from './comments';
import { GakSheet } from './gak';
import { LevelSheet, LevelUpSheet } from './level';
import { LoginSheet } from './login';
import { MeSheet } from './me';
import { RegionSheet } from './region';
import { WeatherWhySheet } from './weather-why';
export function SheetProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<SheetState>(null);
const open = useCallback((s: Exclude<SheetState, null>) => setState(s), []);
const open = useCallback((s: Exclude<SheetState, null>) => {
track('sheet_open', { sheet: s.type });
setState(s);
}, []);
const close = useCallback(() => setState(null), []);
const api = useMemo(() => ({ open, close }), [open, close]);
@@ -31,7 +38,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
);
}
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const;
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', weatherWhy: '날씨 점수는 이렇게 나와요', level: '내 레벨', levelUp: '레벨이 올랐어요' } as const;
/** 판만 아래에서 올라온다 (웹 b-sheet: 0.26초, 40px 아래·흐릿하게에서) */
function Rise({ children }: { children: ReactNode }) {
@@ -62,7 +69,7 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () =>
const [articleTitle, setArticleTitle] = useState('');
const then = state?.type === 'login' ? state.then : undefined;
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type];
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : state.type === 'myGak' ? '내 각' : TITLES[state.type];
return (
<Modal visible={next != null} transparent animationType="fade" onRequestClose={onClose} statusBarTranslucent>
@@ -84,10 +91,15 @@ function SheetHost({ state: next, onClose }: { state: SheetState; onClose: () =>
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
{state.type === 'comments' && <CommentsSheet postId={state.postId} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
{state.type === 'comments' && <CommentsSheet to={'talkId' in state ? { talkId: state.talkId } : { postId: state.postId }} draft={state.draft} />}
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} why={state.why} />}
{state.type === 'me' && <MeSheet onDone={onClose} />}
{state.type === 'region' && <RegionSheet onDone={onClose} />}
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
{state.type === 'level' && <LevelSheet />}
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
{state.type === 'myGak' && <MyGakSheet gak={state.gak} onDone={onClose} />}
{state.type === 'levelUp' && <LevelUpSheet level={state.level} />}
</View>
</Rise>
)}
+138
View File
@@ -0,0 +1,138 @@
import { LinearGradient } from 'expo-linear-gradient';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic } from '@/components/ui';
import { HIDDEN, josa, levelIcon, nextUnlock, progress, useCloseAndGo, useLevel } from '@/lib/level';
import { useSheet } from '@/lib/sheet';
import { Body, useSoft } from './parts';
// 각을 주는 일 → 그 일을 하러 가는 곳, 숨긴 기능에 딸린 일 (서버 ACTIONS 키, 웹 level.tsx)
const ACTION_TO: Record<string, string> = { saju: '/saju', react: '/', talk: '/talk' };
const ACTION_FEATURE: Record<string, string> = { tarot: 'tarot', checkin: 'tarot' };
function Bar({ value }: { value: number }) {
const s = useSoft();
return (
<View className="h-2 overflow-hidden rounded-full" style={{ backgroundColor: s.bar }}>
<LinearGradient colors={['#ffb27a', '#ff7a45']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ height: '100%', width: `${Math.round(value * 100)}%`, borderRadius: 999 }} />
</View>
);
}
/** 내 정보 위쪽: 레벨·모은 각·다음 레벨에서 열리는 것. link 가 있으면 '각 모으는 법'으로 내 레벨 창을 연다 */
export function LevelCard({ link = true }: { link?: boolean }) {
const level = useLevel().data;
const { open } = useSheet();
const s = useSoft();
if (!level) return null;
const unlock = nextUnlock(level);
return (
<View accessibilityLabel="내 레벨" className="rounded-2xl px-3.5 py-3" style={{ backgroundColor: s.warm }}>
<View className="flex-row items-center gap-2">
<Ic name={levelIcon(level.level)} size={28} />
<Text className="font-jua text-[16px] text-ink">
Lv.{level.level} {level.name}
</Text>
<Text className="ml-auto font-bagel text-[15px] text-ink">{level.points}각</Text>
</View>
<View className="mt-2">
<Bar value={progress(level)} />
</View>
<View className="mt-1.5 flex-row items-center justify-between gap-2">
<Text className="shrink text-xs font-bold text-ink2">
{level.next_points == null
? '가장 높은 레벨이에요'
: unlock.length > 0
? `${level.next_points - level.points}각 더 모으면 ${josa(unlock.join(', '), '이', '가')} 열려요`
: `${level.next_points - level.points}각 더 모으면 Lv.${level.level + 1} ${level.next_name}`}
</Text>
{link && (
<Pressable onPress={() => open({ type: 'level' })} hitSlop={8} accessibilityRole="button">
<Text className="text-xs font-bold text-orange">각 모으는 법 ›</Text>
</Pressable>
)}
</View>
</View>
);
}
/** 내 레벨 창: 오늘 받을 수 있는 각, 레벨마다 열리는 것 */
export function LevelSheet() {
const level = useLevel().data;
const go = useCloseAndGo();
const s = useSoft();
if (!level) return null;
const steps = (level.unlocks ?? []).reduce<Record<number, string[]>>((m, u) => ({ ...m, [u.level]: [...(m[u.level] ?? []), u.name] }), {});
const actions = (level.today ?? []).filter((a) => !HIDDEN.has(ACTION_FEATURE[a.action] ?? a.action));
return (
<Body className="gap-4">
<LevelCard link={false} />
<View>
<Text className="mb-2 text-sm font-extrabold text-ink">오늘 받을 수 있는 각</Text>
<View className="rounded-2xl border-b-4 border-shade bg-card">
{actions.map((a, i) => {
const done = a.earned >= a.cap;
const to = ACTION_TO[a.action];
return (
<Pressable key={a.action} disabled={!to || done} onPress={() => to && go(to)} className={`flex-row items-center gap-2.5 px-3.5 py-2.5 ${i < actions.length - 1 ? 'border-b border-line' : ''}`}>
<View className={`size-5 items-center justify-center rounded-full ${done ? 'bg-[#1f9d62]' : 'bg-[#dfe5ef]'}`}>{done && <Text className="text-[11px] text-white">✓</Text>}</View>
<Text className={`text-[13.5px] font-bold ${done ? 'text-ink3 line-through' : 'text-ink'}`}>{a.name}</Text>
<Text className="ml-auto font-bagel text-[13px] text-orange">{done ? `오늘 ${a.earned}각 받음` : a.earned > 0 ? `${a.earned}/${a.cap}각` : `+${a.points}각`}</Text>
{!!to && !done && <Text className="text-ink3">›</Text>}
</Pressable>
);
})}
</View>
<Text className="mt-1.5 text-xs font-semibold text-ink3">{level.streak > 0 ? `${level.streak}일째 연속 출석 중 · 7일 연속이면 +50각` : '7일 연속 출석하면 +50각을 더 받아요'}</Text>
</View>
<View>
<Text className="mb-2 text-sm font-extrabold text-ink">레벨이 오르면 열려요</Text>
<View className="gap-1.5">
{(level.levels ?? []).map(({ level: lv, name, points }) => {
const reached = level.level >= lv;
return (
<View key={lv} className="flex-row items-center gap-2.5 rounded-xl px-2.5 py-2" style={lv === level.level ? { backgroundColor: s.warm } : undefined}>
<Ic name={levelIcon(lv)} size={28} style={reached ? undefined : { opacity: 0.4 }} />
<View className="min-w-0 flex-1">
<Text className="text-[13.5px] font-extrabold text-ink">
Lv.{lv} {name} <Text className="font-semibold text-ink3">· {points}각</Text>
</Text>
<Text className="text-xs font-semibold text-ink2">{lv === 1 ? '날씨각의 기본 기능 모두' : (steps[lv] ?? []).join(', ')}</Text>
</View>
</View>
);
})}
</View>
</View>
</Body>
);
}
/** 레벨이 오른 순간 */
export function LevelUpSheet({ level: lv }: { level: number }) {
const level = useLevel().data;
const { open } = useSheet();
const go = useCloseAndGo();
const unlocks = (level?.unlocks ?? []).filter((u) => u.level === lv);
const opened = unlocks.map((u) => u.name);
const name = level?.levels?.find((l) => l.level === lv)?.name;
return (
<Body className="items-center gap-2 px-6 pb-6">
<Ic name={levelIcon(lv)} size={96} />
<Text className="font-jua text-[28px] text-ink">
Lv.{lv} {name}
</Text>
{opened.length > 0 && <Text className="text-center text-[15px] font-bold text-ink2">이제 {josa(opened.join(', '), '을', '를')} 볼 수 있어요</Text>}
{unlocks.length > 0 && (
<Pressable onPress={() => go(`/saju?open=${unlocks[0].key}`)} className="mt-3 w-full rounded-full bg-orange py-3">
<Text className="text-center text-[15px] font-extrabold text-white">{opened[0]} 보러 가기</Text>
</Pressable>
)}
<Pressable onPress={() => open({ type: 'level' })} className={`w-full py-2 ${unlocks.length ? '' : 'mt-3 rounded-full bg-orange py-3'}`}>
<Text className={`text-center text-[14px] font-extrabold ${unlocks.length ? 'text-ink2' : 'text-white'}`}>내 레벨 보기</Text>
</Pressable>
</Body>
);
}
+4 -2
View File
@@ -4,13 +4,14 @@ import { useState } from 'react';
import { Pressable } from 'react-native';
import { Text } from '@/components/text';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { GoogleButton } from './google';
import { MeSheet } from './me';
import { Body, ErrorLine } from './parts';
export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
export function LoginSheet({ onDone, onLoggedIn, why }: { onDone: () => void; onLoggedIn: () => void; why?: 'level' }) {
const { me } = useAuth();
const [error, setError] = useState('');
@@ -20,6 +21,7 @@ export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLogge
return;
}
setTokens(res.access_token, res.refresh_token ?? null);
track(res.is_new ? 'sign_up' : 'login', { method: 'google' });
onLoggedIn();
};
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.');
@@ -28,7 +30,7 @@ export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLogge
return (
<Body className="gap-2.5">
<Text className="text-center text-sm font-semibold text-ink2">좋아요·댓글은 로그인한 뒤에 할 수 있어요.</Text>
<Text className="text-center text-sm font-semibold text-ink2">{why === 'level' ? '로그인하면 출석·사주·좋아요로 각이 쌓여 레벨이 올라요.' : '글쓰기는 로그인한 뒤에 할 수 있어요.'}</Text>
<GoogleButton
onResult={(res) => {
setError('');
+6 -1
View File
@@ -1,5 +1,6 @@
import { clearTokens } from '@nalssigak/shared/api/auth';
import { listBlockedOptions, listBlockedQueryKey, meQueryKey, unblockMutation, updateMeMutation, withdrawMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { AuthProvider } from '@nalssigak/shared/api/client/types.gen';
import { AVATAR_COLORS, CHARACTERS, MOODS } from '@nalssigak/shared/lib';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
@@ -7,9 +8,11 @@ import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Avatar, Ic } from '@/components/ui';
import { MyTalks } from '@/components/talk/talk';
import { useAuth } from '@/lib/auth';
import { isCommentList } from './comments';
import { LevelCard } from './level';
import { Body, Field, useSoft } from './parts';
/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */
@@ -132,8 +135,9 @@ export function MeSheet({ onDone }: { onDone: () => void }) {
<Body className="gap-3">
<View className="items-center gap-1.5">
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
<Text className="text-center text-sm font-semibold text-ink2">{me.login_id}(으)로 로그인했어요</Text>
<Text className="text-center text-sm font-semibold text-ink2">{me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</Text>
</View>
<LevelCard />
<View accessibilityLabel="내 캐릭터">
<Text className="mb-2 text-sm font-extrabold text-ink">내 캐릭터</Text>
<View className="flex-row flex-wrap gap-2">
@@ -199,6 +203,7 @@ export function MeSheet({ onDone }: { onDone: () => void }) {
</Pressable>
</View>
<Text className={`min-h-5 text-center text-[13px] font-bold ${saving ? 'text-ink2' : 'text-heart'}`}>{saving ? (saving.nickname == null ? '저장 중…' : '') : error}</Text>
<MyTalks />
<Pressable
onPress={() => {
logout();
+2
View File
@@ -6,6 +6,7 @@ import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Skel, StateBox } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
@@ -66,6 +67,7 @@ export function RegionSheet({ onDone }: { onDone: () => void }) {
accessibilityState={{ selected: here }}
onPress={() => {
setRegion(r);
track('region_change', { region_name: r.name, method: 'list' });
onDone();
}}
className="flex-row items-center justify-between border-b-[1.5px] border-line px-1 py-3"
@@ -0,0 +1,86 @@
import type { WeatherWhy } from '@nalssigak/shared/api/client/types.gen';
import { View } from 'react-native';
import { Text } from '@/components/text';
import { Body, useSoft } from './parts';
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[]; status?: { label: string; value: string; tone?: string; detail?: string | null }[] };
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게 (웹 weatherWhy.tsx)
const COLOR: Record<string, string> = { 기온: '#ff7a45', 비: '#4f97e3', 햇볕: '#ffb02e', 바람: '#5fb8b0', 습도: '#8e8cf0', 미세먼지: '#b59a86' };
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8';
// 상태 줄 항목마다 단계를 나누는 기준 (backend/services/hero_stats.py 와 같은 값)
const RULE: Record<string, string> = {
습도: '30% 아래는 건조, 60% 넘으면 습함이에요',
불쾌지수: '68 아래는 쾌적, 75부터 불쾌예요',
자외선: '3 아래는 낮음, 6부터 높음이에요',
미세먼지: '에어코리아 기준 등급이에요',
};
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
const s = useSoft();
return (
<Body>
<View className="flex-row items-baseline gap-2">
<Text className="font-bagel text-[44px] leading-[48px] text-ink">{d.score}</Text>
<Text className="font-jua text-[17px] text-ink2">{d.label} 날씨 점수</Text>
</View>
<View className="mt-3 h-7 flex-row gap-[3px] overflow-hidden rounded-[10px]" accessibilityRole="image" accessibilityLabel={d.why.map((w) => `${w.label} 비중 ${w.weight}% 중 ${w.score}점`).join(', ')}>
{d.why.map((w) => (
<View key={w.label} className="h-full" style={{ width: `${w.weight}%`, backgroundColor: s.bar }}>
<View className="absolute inset-y-0 left-0" style={{ width: `${w.score}%`, backgroundColor: colorOf(w.label) }} />
</View>
))}
</View>
<Text className="mt-1.5 text-[12.5px] font-semibold text-ink3">칸 넓이는 비중, 채운 만큼이 얻은 점수예요</Text>
<View className="mt-3 gap-1.5">
{d.why.map((w) => (
<View key={w.label} className="flex-row items-center gap-3 rounded-2xl px-3.5 py-2.5" style={{ backgroundColor: s.soft }}>
<View className="size-3 rounded-full" style={{ backgroundColor: colorOf(w.label) }} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">
{w.label} <Text className="font-sans text-[12px] font-bold text-ink3">비중 {w.weight}%</Text>
</Text>
<Text className="text-[13px] font-semibold text-ink2">{w.note}</Text>
</View>
<Text className="font-jua text-[20px] text-ink">{w.score}</Text>
</View>
))}
</View>
{!!d.status?.length && (
<>
<Text className="mt-5 font-jua text-[17px] text-ink">지금 상태</Text>
<View className="mt-2 gap-1.5">
{d.status.map((x) => (
<View key={x.label} className="flex-row items-center gap-3 rounded-2xl px-3.5 py-2.5" style={{ backgroundColor: s.soft }}>
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">{x.label}</Text>
{!!RULE[x.label] && <Text className="text-[12.5px] font-semibold text-ink3">{RULE[x.label]}</Text>}
</View>
<View className="items-end">
<Text className={`font-jua text-[18px] leading-tight ${x.tone === 'warn' ? 'text-[#d4552a]' : 'text-ink'}`}>
{x.value}
</Text>
{x.detail?.split(' · ').map((v) => (
<Text key={v} className="text-[12px] font-bold text-ink2">
{v}
</Text>
))}
</View>
</View>
))}
</View>
</>
)}
<Text className="mt-3 text-[13px] leading-relaxed font-semibold text-ink2">조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.</Text>
</Body>
);
}
+53
View File
@@ -0,0 +1,53 @@
import { useImperativeHandle, useRef, type Ref } from 'react';
import { WebView } from 'react-native-webview';
import { SITE_URL } from '@/lib/site';
const YT_ORIGIN = 'https://www.youtube-nocookie.com';
export type PlayerFunc = 'playVideo' | 'seekTo' | 'mute' | 'unMute';
export type PlayerHandle = { command: (func: PlayerFunc, args?: unknown[]) => void };
function embed(id: string) {
const q = new URLSearchParams({ autoplay: '1', mute: '1', playsinline: '1', loop: '1', playlist: id, controls: '0', rel: '0', modestbranding: '1', enablejsapi: '1', origin: SITE_URL });
return `${YT_ORIGIN}/embed/${id}?${q}`;
}
/**
* 유튜브 플레이어를 날씨각 주소를 기준으로 한 작은 문서 안 iframe 으로 띄운다.
* 앱 웹뷰에서 embed 주소를 바로 열면 보낸 곳(Referer)이 없어 유튜브가 막는다. 웹과 같이 IFrame API 메시지로 재생 상태를 받고 명령한다
*/
function html(id: string) {
return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:transparent;overflow:hidden}iframe{border:0;width:100%;height:100%}</style></head>
<body><iframe id="f" src="${embed(id)}" allow="autoplay; encrypted-media"></iframe>
<script>
var f = document.getElementById('f');
f.addEventListener('load', function () { f.contentWindow.postMessage(JSON.stringify({ event: 'listening', id: ${JSON.stringify(id)} }), '${YT_ORIGIN}'); });
window.addEventListener('message', function (e) {
if (e.origin !== '${YT_ORIGIN}') return;
try { var m = JSON.parse(e.data); if (m.info && m.info.playerState === 1) window.ReactNativeWebView.postMessage('playing'); } catch (x) {}
});
window.cmd = function (func, args) { f.contentWindow.postMessage(JSON.stringify({ event: 'command', func: func, args: args || [] }), '${YT_ORIGIN}'); };
</script></body></html>`;
}
/** 소리 없이 자동재생하는 쇼츠 플레이어. 첫 장면이 나오면 onPlaying (그 전엔 위에 표지를 덮어 둔다) */
export function ShortPlayer({ id, onPlaying, ref }: { id: string; onPlaying: () => void; ref?: Ref<PlayerHandle> }) {
const view = useRef<WebView>(null);
useImperativeHandle(ref, () => ({
command: (func, args = []) => view.current?.injectJavaScript(`window.cmd && window.cmd(${JSON.stringify(func)}, ${JSON.stringify(args)}); true;`),
}));
return (
<WebView
ref={view}
source={{ html: html(id), baseUrl: SITE_URL }}
originWhitelist={['*']}
onMessage={(e) => e.nativeEvent.data === 'playing' && onPlaying()}
mediaPlaybackRequiresUserAction={false}
allowsInlineMediaPlayback
scrollEnabled={false}
setSupportMultipleWindows={false}
style={{ backgroundColor: 'transparent' }}
/>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { listShortsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { useQuery } from '@tanstack/react-query';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { Link } from 'expo-router';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Rail } from '@/components/ui';
const SKELS = [0, 1, 2, 3];
export const thumb = (id: string) => `https://i.ytimg.com/vi/${id}/hqdefault.jpg`;
/** 오늘 화면 히어로 아래 쇼츠 줄. 누르면 쇼츠 화면에서 위아래로 넘겨 본다. 앱은 데이터를 아끼려고 줄에서는 표지만 (웹은 첫 카드를 소리 없이 재생) */
export function ShortsRail() {
const q = useQuery(listShortsOptions());
const items = q.data?.items ?? [];
if (q.isPending)
return (
<Rail>
{SKELS.map((i) => (
<View key={i} className="aspect-[9/16] w-[120px] rounded-xl bg-skel" />
))}
</Rail>
);
if (!items.length) return null;
return (
<View accessibilityLabel="날씨각 쇼츠">
<Rail>
{items.map((s) => (
<Link key={s.id} href={{ pathname: '/shorts/[id]', params: { id: s.id } }} asChild>
<Pressable accessibilityLabel={`${s.title} 보기`} className="aspect-[9/16] w-[120px] overflow-hidden rounded-xl bg-[#1d2233]">
<Image source={{ uri: thumb(s.id) }} style={{ position: 'absolute', inset: 0 }} contentFit="cover" />
<LinearGradient colors={['transparent', 'rgba(0,0,0,0.65)']} locations={[0.55, 1]} style={{ position: 'absolute', inset: 0 }} />
<Text numberOfLines={3} className="absolute inset-x-2 bottom-2 text-[12px] leading-[16px] font-bold text-white">
{s.title}
</Text>
</Pressable>
</Link>
))}
</Rail>
</View>
);
}
+29 -2
View File
@@ -1,7 +1,9 @@
import type { TimeKind } from '@nalssigak/shared/lib';
import { holidayOn, type Holiday } from '@nalssigak/shared/lib/holiday';
import { Image } from 'expo-image';
import { LinearGradient } from 'expo-linear-gradient';
import { useEffect } from 'react';
import { StyleSheet, View, type DimensionValue } from 'react-native';
import { useEffect, useState } from 'react';
import { StyleSheet, useWindowDimensions, View, type DimensionValue } from 'react-native';
import Animated, { cancelAnimation, Easing, interpolate, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
import { useSky } from '@/lib/sky';
@@ -77,6 +79,30 @@ export function Shoot({ top, left, len, dur, dl }: ShootSpec) {
}
/** 화면 전체 하늘: 시간대별 색이 서서히 바뀌고, 밤에는 별이 반짝이고 별똥별이 떨어진다 */
// 기념일 소품: 투명 배경 그림을 화면 네 귀퉁이에 (웹 b.css .b-sky-holiday, frontend/public/b/holiday, 4:5 그림)
const PROPS: Record<Holiday['key'], [number, number, number, number]> = {
halloween: [require('../../../frontend/public/b/holiday/halloween-tl.webp'), require('../../../frontend/public/b/holiday/halloween-tr.webp'), require('../../../frontend/public/b/holiday/halloween-bl.webp'), require('../../../frontend/public/b/holiday/halloween-br.webp')],
pepero: [require('../../../frontend/public/b/holiday/pepero-tl.webp'), require('../../../frontend/public/b/holiday/pepero-tr.webp'), require('../../../frontend/public/b/holiday/pepero-bl.webp'), require('../../../frontend/public/b/holiday/pepero-br.webp')],
christmas: [require('../../../frontend/public/b/holiday/christmas-tl.webp'), require('../../../frontend/public/b/holiday/christmas-tr.webp'), require('../../../frontend/public/b/holiday/christmas-bl.webp'), require('../../../frontend/public/b/holiday/christmas-br.webp')],
chuseok: [require('../../../frontend/public/b/holiday/chuseok-tl.webp'), require('../../../frontend/public/b/holiday/chuseok-tr.webp'), require('../../../frontend/public/b/holiday/chuseok-bl.webp'), require('../../../frontend/public/b/holiday/chuseok-br.webp')],
};
const CORNERS = [{ top: 0, left: 0 }, { top: 0, right: 0 }, { bottom: 0, left: 0 }, { bottom: 0, right: 0 }] as const;
/** 기념일 기간에만 네 귀퉁이 소품. 폰은 반씩 나눠 폭을 채우고 넓은 화면은 300 으로. 밤엔 조금 어둡게 */
function HolidayProps({ night }: { night: boolean }) {
const [holiday] = useState(holidayOn);
const { width } = useWindowDimensions();
if (!holiday) return null;
const w = Math.min(width / 2, 300);
return (
<>
{PROPS[holiday.key].map((src, i) => (
<Image key={i} source={src} style={{ position: 'absolute', ...CORNERS[i], width: w, aspectRatio: 4 / 5, opacity: night ? 0.8 : 1 }} contentFit="contain" />
))}
</>
);
}
export function SkyBg() {
const { kind } = useSky();
const reduce = useReducedMotion();
@@ -85,6 +111,7 @@ export function SkyBg() {
{KINDS.map((k) => (
<Layer key={k} kind={k} on={k === kind} reduce={reduce} />
))}
<HolidayProps night={kind === 'night'} />
{kind === 'night' && STARS.map((s, i) => <Star key={i} star={s} reduce={reduce} />)}
{kind === 'night' && SHOOTS.map((s, i) => <Shoot key={i} {...s} />)}
</View>
+426
View File
@@ -0,0 +1,426 @@
import { addTalkMutation, blockTalkAuthorMutation, deleteTalkMutation, likeTalkMutation, reportTalkMutation, unlikeTalkMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen';
import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen';
import { holidayByTopic } from '@nalssigak/shared/lib/holiday';
import { useMutation } from '@tanstack/react-query';
import { Image } from 'expo-image';
import * as ImagePicker from 'expo-image-picker';
import { LinearGradient } from 'expo-linear-gradient';
import { useRef, useState } from 'react';
import { Pressable, TextInput, View } from 'react-native';
import { useCSSVariable } from 'uniwind';
import { CameraIcon, CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { useSoft } from '@/components/sheets/parts';
import { Text } from '@/components/text';
import { Avatar } from '@/components/ui';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { CARD_BG } from '@/lib/colors';
import { useRegion } from '@/lib/region';
import { useShare } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { openTopics, talkImage, talkMeta, useMyTalks, useRefreshTalks } from '@/lib/talk';
const BODY_MAX = 100;
const PHOTO_MAX = 10 * 1024 * 1024;
// 서버 ErrorType 이름 → 안내
const WRITE_ERRORS: Record<string, string> = {
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
INVALID_INPUT: '100자 안으로 써 주세요.',
};
const REASONS = [
[TalkReport.ABUSE, '욕설·비하'],
[TalkReport.SPAM, '광고·도배'],
[TalkReport.PRIVACY, '개인정보 노출'],
[TalkReport.ETC, '기타'],
] as const;
type Photo = { uri: string; name: string; type: string };
/** 고른 사진을 올려 주소를 받는다. 앱의 사진은 Blob 이 아니라 {uri} 라서 FormData 를 직접 만든다 */
async function uploadPhoto(photo: Photo) {
const form = new FormData();
form.append('file', photo as unknown as Blob);
const { data } = await uploadTalkImage({ body: { file: photo as unknown as Blob }, bodySerializer: () => form });
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload');
return data.image;
}
/** 이야기 쓰는 칸: 로그인해야 쓴다. 주제·사진(하나)을 붙여 올린다 */
export function Composer() {
const { region } = useRegion();
const { loggedIn, me } = useAuth();
const { open } = useSheet();
const s = useSoft();
const [ink2] = useCSSVariable(['--color-ink2']).map(String);
const refresh = useRefreshTalks();
const add = useMutation(addTalkMutation());
const [text, setText] = useState('');
const [topic, setTopic] = useState<TalkTopic>(TalkTopic.LOCAL);
const [error, setError] = useState<string | null>(null);
const [photo, setPhoto] = useState<Photo | null>(null);
const [uploading, setUploading] = useState(false);
const busy = add.isPending || uploading;
const place = region.name.split(' ').at(-1);
const pick = async () => {
if (!loggedIn) return open({ type: 'login' });
try {
const res = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ['images'], quality: 0.85 });
const a = res.canceled ? undefined : res.assets[0];
if (!a) return;
if (a.fileSize && a.fileSize > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.');
setError(null);
setPhoto({ uri: a.uri, name: a.fileName ?? 'photo.jpg', type: a.mimeType ?? 'image/jpeg' });
} catch (e) {
console.error('[talk] pick photo', e);
setError('사진을 고르지 못했어요. 다시 해 주세요.');
}
};
const submit = async () => {
if (!loggedIn) return open({ type: 'login' });
const body = text.trim();
if (!body || busy) return;
setError(null);
let image: string | undefined;
if (photo) {
setUploading(true);
try {
image = await uploadPhoto(photo);
} catch (e) {
console.error('[talk] photo upload', e);
return setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.');
} finally {
setUploading(false);
}
}
add.mutate(
{ body: { region_code: region.code, body, image, topic } },
{
onSuccess: (res) => {
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.');
track('talk_post', { topic, with_image: !!image });
setText('');
setPhoto(null);
setTopic(TalkTopic.LOCAL);
refresh();
},
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
},
);
};
return (
<View className="mx-3 mt-3.5 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
{/* 로그인 전엔 칸을 눌러도 키보드 대신 로그인 창 */}
<Pressable disabled={loggedIn} onPress={() => open({ type: 'login' })}>
<TextInput
value={text}
onChangeText={setText}
editable={loggedIn && !busy}
maxLength={BODY_MAX}
multiline
numberOfLines={2}
placeholder={`지금 ${place} 날씨 어때요?`}
placeholderTextColor={s.placeholder}
accessibilityLabel="동네 이야기 쓰기"
className="min-h-[60px] rounded-2xl px-3 py-2.5 text-[14.5px] text-ink"
style={{ backgroundColor: s.soft, textAlignVertical: 'top' }}
pointerEvents={loggedIn ? 'auto' : 'none'}
/>
</Pressable>
{photo && (
<View className="mt-2 w-[96px]">
<Image source={{ uri: photo.uri }} style={{ width: 96, aspectRatio: 4 / 5, borderRadius: 12 }} contentFit="cover" accessibilityLabel="올릴 사진" />
<Pressable onPress={() => setPhoto(null)} accessibilityRole="button" accessibilityLabel="사진 빼기" className="absolute -top-1.5 -right-1.5 size-6 items-center justify-center rounded-full bg-ink-btn">
<Text className="text-[13px] font-extrabold text-white">×</Text>
</Pressable>
</View>
)}
<View className="mt-2 flex-row flex-wrap gap-1.5" accessibilityRole="radiogroup" accessibilityLabel="글 주제">
{openTopics().map(([k, label]) => (
<Pressable key={k} onPress={() => setTopic(k)} accessibilityRole="radio" accessibilityState={{ checked: topic === k }} className={`rounded-full px-2.5 py-1 ${topic === k ? 'bg-ink-btn' : ''}`} style={topic === k ? undefined : { backgroundColor: s.soft }}>
<Text className={`text-[12.5px] font-extrabold ${topic === k ? 'text-white' : 'text-ink2'}`}>{label}</Text>
</Pressable>
))}
</View>
<View className="mt-1.5 flex-row items-center gap-2">
{/* 주제 칩과 헷갈리지 않게 글자 대신 카메라 아이콘 */}
<Pressable onPress={pick} disabled={busy} hitSlop={6} accessibilityRole="button" accessibilityLabel="사진 붙이기" className="size-8 items-center justify-center rounded-full disabled:opacity-40" style={{ backgroundColor: s.soft }}>
<CameraIcon size={18} color={ink2} />
</Pressable>
<Text numberOfLines={1} className="min-w-0 flex-1 text-xs font-bold text-ink3">
{me ? `${me.nickname} · ${place} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}
</Text>
<Text className="text-xs font-bold text-ink3">
{text.length}/{BODY_MAX}
</Text>
<Pressable onPress={submit} disabled={busy || (loggedIn && !text.trim())} accessibilityRole="button" className="rounded-full bg-orange px-3.5 py-1.5 disabled:opacity-40">
<Text className="text-[13px] font-extrabold text-white">{busy ? '올리는 중…' : '올리기'}</Text>
</Pressable>
</View>
{!!error && (
<Text accessibilityRole="alert" className="mt-1 text-xs font-bold text-heart">
{error}
</Text>
)}
</View>
);
}
type Menu = 'closed' | 'open' | 'confirm' | 'report' | 'done';
/** 좋아요: 로그인 없이 된다. 화면을 먼저 바꾸고, 실패하면 되돌린다 */
function useTalkLike(t: TalkData) {
const [liked, setLiked] = useState(t.liked);
const [count, setCount] = useState(t.like_count);
const like = useMutation(likeTalkMutation());
const unlike = useMutation(unlikeTalkMutation());
const toggle = () => {
if (like.isPending || unlike.isPending) return;
const next = !liked;
setLiked(next);
setCount((n) => n + (next ? 1 : -1));
const revert = () => {
setLiked(!next);
setCount(t.like_count);
};
(next ? like : unlike).mutate(
{ path: { talk_id: t.talk_id } },
{
onSuccess: (res) => {
if (!res.result?.success || res.like_count == null) return revert();
if (next) track('like', { content_type: 'talk', item_id: t.talk_id });
setCount(res.like_count);
},
onError: revert,
},
);
};
return { liked, count, toggle };
}
function Chip({ label, danger, onPress, disabled }: { label: string; danger?: boolean; onPress: () => void; disabled?: boolean }) {
return (
<Pressable onPress={onPress} disabled={disabled} className={`rounded-full px-3 py-1 ${danger ? 'bg-[#fdecec]' : 'bg-[#eef4fc]'}`}>
<Text className={`text-[12.5px] font-extrabold ${danger ? 'text-heart' : 'text-[#28304a]'}`}>{label}</Text>
</Pressable>
);
}
/** 글 메뉴(⋯)를 눌렀을 때 나오는 버튼 줄: 내 글은 지우기, 남의 글은 안 보기·신고 */
function TalkMenu({ t, menu, setMenu, className }: { t: TalkData; menu: Menu; setMenu: (m: Menu) => void; className?: string }) {
const { loggedIn } = useAuth();
const { open } = useSheet();
const refresh = useRefreshTalks();
const remove = useMutation(deleteTalkMutation());
const report = useMutation(reportTalkMutation());
const block = useMutation(blockTalkAuthorMutation());
const [failed, setFailed] = useState(false);
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
const after = (done?: () => void) => ({
onSuccess: (res: { result?: { success?: boolean } }) => {
if (!res.result?.success) return setFailed(true);
done?.();
setMenu('done');
refresh();
},
onError: () => setFailed(true),
});
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }));
return (
<View className={`flex-row flex-wrap items-center gap-1.5 ${className ?? ''}`} accessibilityLabel="글 메뉴">
{menu === 'done' ? (
<Text className="text-[12.5px] font-extrabold text-[#1f9d62]">처리했어요</Text>
) : t.mine && menu === 'confirm' ? (
<>
<Text className="text-[12.5px] font-extrabold text-ink2">지울까요?</Text>
<Chip label="지우기" danger disabled={remove.isPending} onPress={() => remove.mutate({ path: { talk_id: t.talk_id } }, after())} />
<Chip label="취소" onPress={() => setMenu('closed')} />
</>
) : t.mine ? (
<Chip label="지우기" danger onPress={() => setMenu('confirm')} />
) : menu === 'report' ? (
REASONS.map(([reason, label]) => <Chip key={reason} label={label} disabled={report.isPending} onPress={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after(() => track('report', { content_type: 'talk', reason })))} />)
) : (
<>
<Chip label="이 사람 글 안 보기" disabled={block.isPending} onPress={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after(() => track('block', { content_type: 'talk' }))))} />
<Chip label="신고하기" danger onPress={() => guard(() => setMenu('report'))} />
</>
)}
{failed && <Text className="text-[12.5px] font-extrabold text-heart">못 했어요. 다시 해 주세요</Text>}
</View>
);
}
function MenuButton({ menu, setMenu }: { menu: Menu; setMenu: (m: Menu) => void }) {
return (
<Pressable onPress={() => setMenu(menu === 'closed' ? 'open' : 'closed')} hitSlop={12} accessibilityRole="button" accessibilityState={{ expanded: menu !== 'closed' }} accessibilityLabel="글 메뉴">
<Text className="text-[15px] font-extrabold tracking-[1px] text-ink3">⋯</Text>
</Pressable>
);
}
function MineBadge() {
return (
<Text className="overflow-hidden rounded-full bg-[#ffe8dc] px-1.5 text-[11px] font-extrabold text-[#c2471b]">
{' 내 글 '}
</Text>
);
}
/** 한 줄 글: 목록·내 정보의 내 글 */
function TalkRow({ t, last }: { t: TalkData; last?: boolean }) {
const { liked, count, toggle } = useTalkLike(t);
const [menu, setMenu] = useState<Menu>('closed');
const [heart, ink3] = useCSSVariable(['--color-heart', '--color-ink3']).map(String);
const src = talkImage(t);
return (
<View className={`flex-row items-start gap-2.5 py-2.5 ${last ? '' : 'border-b border-line'}`}>
<Avatar character={t.character} color={t.color} mood={t.mood} />
<View className="min-w-0 flex-1">
<Text className="text-xs font-bold text-ink3">
<Text className="font-extrabold text-ink">{t.nickname} </Text>
{t.mine && (
<>
<MineBadge />{' '}
</>
)}
{talkMeta(t)}
</Text>
<Text className="mt-0.5 text-[14.5px] text-ink">{t.body}</Text>
{!!src && <Image source={{ uri: src }} style={{ marginTop: 8, width: '100%', aspectRatio: 4 / 5, borderRadius: 16, backgroundColor: '#eef4fc' }} contentFit="cover" />}
<Text className="mt-0.5 text-xs font-bold text-ink3">
{t.ago} · 좋아요 {count}개
</Text>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="mt-1.5" />}
</View>
{/* 글 메뉴(⋯)는 하트 옆 오른쪽 위에: 아래 줄 끝에 두면 말줄임표처럼 읽힌다 */}
<View className="flex-row items-start gap-4">
<MenuButton menu={menu} setMenu={setMenu} />
<Pressable onPress={toggle} hitSlop={12} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요" className="pt-1">
<HeartIcon size={16} color={liked ? heart : ink3} filled={liked} />
</Pressable>
</View>
</View>
);
}
// 사진 없는 글을 크게 띄울 때 주제별 바탕
const TOPIC_BG: Partial<Record<TalkTopic, string>> = { [TalkTopic.SKY]: 'peach', [TalkTopic.RAIN]: 'sky', [TalkTopic.FOLIAGE]: 'butter', [TalkTopic.OUTFIT]: 'lilac' };
/** 오늘 피드에 끼우는 사람 글: 운영 포스트와 같은 틀. 사진이 없으면 글을 4:5 칸에 크게. 두 번 누르면 좋아요 */
export function TalkPost({ t }: { t: TalkData }) {
const { open } = useSheet();
const { liked, count, toggle } = useTalkLike(t);
const [menu, setMenu] = useState<Menu>('closed');
const [ink, heart] = useCSSVariable(['--color-ink', '--color-heart']).map(String);
const shot = useRef<View>(null);
const lastTap = useRef(0);
const shareView = useShare();
const src = talkImage(t);
const bg = (t.topic && (TOPIC_BG[t.topic] ?? holidayByTopic(t.topic)?.bg)) || 'mint';
const title = `${t.nickname}의 글`;
const share = () => void shareView(shot, { title, message: `${t.body} · 날씨각 ${SITE_URL}` });
const comments = () => open({ type: 'comments', talkId: t.talk_id });
const onTap = () => {
const now = Date.now();
if (now - lastTap.current < 320 && !liked) toggle();
lastTap.current = now;
};
return (
<View className="mt-3.5 border-y border-line bg-card" accessibilityLabel={title}>
<View className="flex-row items-center gap-2.5 px-3 py-2.5">
<Avatar character={t.character} color={t.color} mood={t.mood} />
<View className="min-w-0 flex-1">
<Text className="text-sm leading-tight font-extrabold text-ink">
{t.nickname}
{t.mine && (
<>
{' '}
<MineBadge />
</>
)}
</Text>
<Text numberOfLines={1} className="text-xs font-semibold text-ink2">
{talkMeta(t)}
</Text>
</View>
<MenuButton menu={menu} setMenu={setMenu} />
</View>
{menu !== 'closed' && <TalkMenu t={t} menu={menu} setMenu={setMenu} className="px-3 pb-2.5" />}
<Pressable onPress={onTap} className="aspect-[4/5] overflow-hidden">
<View ref={shot} collapsable={false} className="flex-1">
{src ? (
<Image source={{ uri: src }} style={{ flex: 1, backgroundColor: '#eef4fc' }} contentFit="cover" />
) : (
// 포스트 안은 밤에도 낮 색 (웹 b-day)
<View className="flex-1 items-center justify-center px-7">
<LinearGradient colors={CARD_BG.day[bg] ?? CARD_BG.day.mint} style={{ position: 'absolute', inset: 0 }} />
<Text className={`text-center font-jua text-[26px] leading-snug ${bg === 'night' ? 'text-white' : 'text-[#28304a]'}`}>{t.body}</Text>
</View>
)}
</View>
</Pressable>
<View className="flex-row items-center gap-3.5 px-3 pt-2.5 pb-1">
<Pressable onPress={toggle} hitSlop={8} accessibilityRole="button" accessibilityState={{ selected: liked }} accessibilityLabel="좋아요">
<HeartIcon size={26} color={liked ? heart : ink} filled={liked} />
</Pressable>
<Pressable onPress={comments} hitSlop={8} accessibilityRole="button" accessibilityLabel="댓글 보기">
<CommentIcon size={26} color={ink} />
</Pressable>
<Pressable onPress={share} hitSlop={8} accessibilityRole="button" accessibilityLabel="보내기">
<SendIcon size={26} color={ink} />
</Pressable>
</View>
<Text className="px-3 py-0.5 text-sm font-extrabold text-ink">좋아요 {count.toLocaleString()}개</Text>
{!!src && (
<Text className="px-3 py-0.5 text-sm text-ink">
<Text className="font-extrabold">{t.nickname} </Text>
{t.body}
</Text>
)}
<Pressable onPress={comments}>
<Text className="px-3 pt-[3px] text-sm font-semibold text-ink3">{t.comment_count ? `댓글 ${t.comment_count}개 모두 보기` : '첫 댓글 남기기'}</Text>
</Pressable>
<Text className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-ink3">{t.ago}</Text>
</View>
);
}
/** 이야기 탭 목록의 글 한 장 */
export function TalkCard({ t }: { t: TalkData }) {
return (
<View className="mx-3 mt-3 rounded-[20px] border-b-4 border-shade bg-card px-3" accessibilityLabel={`${t.nickname}의 글`}>
<TalkRow t={t} last />
</View>
);
}
/** 내 정보 창의 내가 쓴 글 */
export function MyTalks() {
const { talks, loaded, more, loadMore } = useMyTalks();
const s = useSoft();
if (!loaded) return null;
return (
<View accessibilityLabel="내 글">
<Text className="mb-1 text-sm font-extrabold text-ink">내 글</Text>
{talks.length ? talks.map((t, i) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} last={i === talks.length - 1} />) : <Text className="text-[13px] font-semibold text-ink3">아직 쓴 글이 없어요</Text>}
{more && (
<Pressable onPress={() => loadMore()} className="mt-1 rounded-[14px] py-2.5" style={{ backgroundColor: s.soft }}>
<Text className="text-center text-[13.5px] font-extrabold text-ink2">더 보기</Text>
</Pressable>
)}
</View>
);
}
+53
View File
@@ -0,0 +1,53 @@
import type { PostReaction, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { MEDALS } from '@nalssigak/shared/lib';
import { Link } from 'expo-router';
import { Pressable, View } from 'react-native';
import { PostFrame } from '@/components/post/post-frame';
import { Text } from '@/components/text';
import { Grad, Ic } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
/** 오늘의 각 1~5위를 포스트 틀에 담은 카드 (웹 GakCard). 좋아요·댓글은 gak_post 에 붙는다 */
export function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
const { open } = useSheet();
const top = items.filter((g) => g.active).slice(0, 5);
return (
<PostFrame
title={`오늘의 각 · ${place}`}
account="오늘의 각"
avatar="rabbit"
caption="누르면 계산 근거를 보여 줘요"
pinned={{ key: 'gak_post', post }}
more={
<Link href="/gak" className="text-[13px] font-bold text-ink2">
전체 보기
</Link>
}
>
{/* 웹 b-band-2. 포스트 안은 밤에도 낮 색 */}
<Grad colors={['#fff6d8', '#f7fbff']} className="px-4 pt-3.5 pb-3">
<Text className="font-jua text-[19px] text-ink">
오늘의 각 · {place} {at}
</Text>
<View className="mt-2 gap-1.5">
{top.map((g, i) => (
<Pressable key={g.index_id} onPress={() => open({ type: 'gak', indexId: g.index_id })} accessibilityRole="button" accessibilityLabel={`${i + 1}위 ${g.name} ${g.score}점, 계산 근거 보기`} className="flex-row items-center gap-2.5 rounded-[18px] border-b-4 border-shade bg-card px-3 py-2">
{i < 3 ? <Ic name={MEDALS[i]} size={24} /> : <Text className="w-6 text-center font-jua text-ink3">{i + 1}</Text>}
<Ic name={g.icon} size={34} />
<View className="min-w-0 flex-1">
<Text className="font-jua text-[16px] leading-tight text-ink">{g.name}</Text>
{!!g.summary && (
<Text numberOfLines={1} className="text-xs font-semibold text-ink2">
{g.summary}
</Text>
)}
</View>
<Text className="font-bagel text-[22px] text-orange">{g.score}</Text>
</Pressable>
))}
</View>
</Grad>
</PostFrame>
);
}
+138 -28
View File
@@ -1,8 +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 { getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { Hero as HeroData, PostReaction, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { kindOfHour, kst, loadOf, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib';
import { KINDS, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today';
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText';
import { useEffect, useState, type ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Pressable, View, type DimensionValue, type ViewStyle } from 'react-native';
import { Text } from '@/components/text';
import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated';
@@ -11,9 +13,15 @@ import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg';
import { Fall } from '@/components/fall';
import { MoonArt } from '@/components/moon';
import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons';
import { Shoot, type ShootSpec } from '@/components/sky-bg';
import { Ic, Skel } from '@/components/ui';
import { track } from '@/lib/analytics';
import { usePinnedLike } from '@/lib/pinned-like';
import { useRegion } from '@/lib/region';
import { useShare } from '@/lib/share-image';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
import { useSky } from '@/lib/sky';
type Mode = 'now' | TimeKind;
@@ -103,18 +111,32 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
return <Text className="opacity-50">?</Text>;
}
type Props = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load };
type Props = { hero?: HeroData | null; post?: PostReaction | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load };
export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
export function Hero({ hero, post, today, ranked, feedLoad, todayLoad }: Props) {
const { open } = useSheet();
const { region } = useRegion();
const like = usePinnedLike('hero_post', post);
const shot = useRef<View>(null);
// 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다 (웹 TodayPage Hero)
const [tmr, setTmr] = useState(false);
const [tmrKind, setTmrKind] = useState<TimeKind>('day');
const tomorrowQ = useQuery({ ...getWeatherTodayOptions({ query: { region: region.code, day: 'tomorrow' } }), enabled: tmr });
const ahead = hero?.tomorrow;
const { preview, setServerKind, setPreview } = useSky();
const mode: Mode = preview ?? 'now';
const t = kst(useNow());
const mode: Mode = tmr ? tmrKind : (preview ?? 'now');
const clock = useNow();
const t = kst(tmr ? new Date(clock.getTime() + 86400000) : clock);
const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi);
const kind = mode === 'now' ? nowKind : mode;
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind]);
const slots = today?.slots ?? [];
// 내일을 볼 땐 배경·글자색도 내일 고른 칸을 따른다
useEffect(() => {
if (tmr) setPreview(tmrKind);
}, [tmr, tmrKind, setPreview]);
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? [];
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad;
// 지금은 가장 가까운 3시간 칸. 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
const slotOf = (k: Mode) => {
if (k === 'now') {
@@ -127,20 +149,67 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s);
};
const weather = weatherOf(slotOf(mode));
const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]];
const score = slotScore ?? hero?.weather_score;
const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active);
const top1 = slotTop ?? hero?.top1;
const slotScore = mode === 'now' ? undefined : (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[mode]];
const score = tmr ? slotScore : (slotScore ?? hero?.weather_score);
// 점수를 누르면 보고 있는 시간대(지금이면 지금 구간)의 날씨 점수 근거
const whyKey = mode === 'now' ? SLOT_KEY[nowKind] : SLOT_KEY[mode];
const why = (tmr ? ahead?.weather_why : hero?.weather_why)?.[whyKey];
const whyLabel = tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label;
const slotTop = mode === 'now' || tmr ? undefined : ranked.find((g) => g.active);
const top1 = tmr ? ahead?.top1 : (slotTop ?? hero?.top1);
const dark = kind === 'sunset' || kind === 'night';
const moon = dark && hero?.moon_name && hero.moon_pct != null ? { pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null;
const moon = !tmr && dark && hero?.moon_name && hero.moon_pct != null ? { pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null;
// 말풍선 머리말: 지금은 / 낮은 / 내일은 / 내일 낮은
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label;
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null;
const status = hero?.status ?? [];
const tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}`;
const bubble = tmr
? top1
? top1.score >= 70
? `${tmrWhen}은 ${top1.name}!`
: `${tmrWhen}은 쉬어 가요`
: null
: slotTop
? slotTop.score >= 70
? `${when}은 ${slotTop.name}!`
: `${when}은 쉬어 가요`
: hero
? (hero.bubble ?? '지금은 쉬어 가요')
: failed(feedLoad)
? '앗, 날씨를 못 불러왔어요'
: null;
// 내일은 최저·최고 기온과 고른 시간대 습도
const temps = slots.flatMap((x) => (x.temp_c != null ? [x.temp_c] : []));
const humidity = tmr && mode !== 'now' ? slotOf(mode)?.humidity : null;
const status = tmr
? [
...(temps.length
? [
{ label: '최저', value: deg(Math.min(...temps)), tone: 'info' },
{ label: '최고', value: deg(Math.max(...temps)), tone: 'info' },
]
: []),
...(humidity != null ? [{ label: '습도', value: `${humidity}%`, tone: 'info' }] : []),
]
: (hero?.status ?? []);
const openWhy = () => why && score != null && open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } });
const switchDay = (v: boolean) => {
// 내일로 넘어갈 땐 지금 보던 시간대 그대로 시작해 배경이 튀지 않게
if (v && !tmr) setTmrKind(kind);
if (v !== tmr) track('hero_day_switch', { day: v ? 'tomorrow' : 'today' });
setTmr(v);
};
const shareView = useShare();
const share = () => {
const title = `${region.name} ${tmr ? '내일' : '오늘'} 날씨`;
void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` });
};
const gray = !dark && weather !== 'clear' && weather !== 'partly';
const rain = weather === 'rain' || weather === 'sleet';
const snow = weather === 'snow' || weather === 'sleet';
const orb = ORB[kind === 'sunset' ? 'sunset' : kind === 'night' ? 'night' : 'sun'];
const text = dark ? 'text-white' : 'text-[#28304a]';
const icon = dark ? '#ffffff' : '#28304a';
const strip = dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)';
// 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐·삭)이면 흰 글씨
const orbText: { color: string; textShadowColor?: string; textShadowRadius?: number } = !moon
? { color: orb.text }
@@ -149,7 +218,7 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
: { color: '#fff', textShadowColor: 'rgba(10,14,40,0.6)', textShadowRadius: 8 };
return (
<View className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
<View ref={shot} collapsable={false} className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
<LinearGradient colors={HERO_BG[gray ? 'gray' : kind]} locations={kind === 'night' ? [0, 0.6, 1] : [0, 0.5, 1]} style={{ position: 'absolute', inset: 0 }} />
{kind === 'night' && STARS.map((s, i) => <View key={i} className="absolute size-[3px] rounded-full bg-white" style={{ left: s.left, top: s.top, opacity: s.opacity }} />)}
{kind === 'night' && SHOOTS.map((s, i) => <Shoot key={i} {...s} />)}
@@ -159,9 +228,42 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
{snow && FLAKES.map((p, i) => <Particle key={`s${i}`} {...p} snow light={dark} />)}
</View>
)}
<Text className={`text-[14px] font-bold opacity-80 ${text}`}>
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</Text>
<View className="z-[3] flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
<View className="flex-row rounded-full p-[3px]" style={{ backgroundColor: strip }} accessibilityRole="radiogroup" accessibilityLabel="오늘 또는 내일 날씨">
{(
[
[false, '오늘'],
[true, '내일'],
] as const
).map(([v, l]) => (
<Pressable key={l} onPress={() => switchDay(v)} accessibilityRole="radio" accessibilityState={{ checked: tmr === v }} className={`rounded-full px-2.5 py-0.5 ${tmr === v ? 'bg-white' : ''}`}>
<Text className={`font-jua text-[13px] ${tmr === v ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{l}</Text>
</Pressable>
))}
</View>
<Text className={`text-[13px] font-bold opacity-80 ${text}`}>
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</Text>
</View>
<View className="flex-row items-center">
{post && (
<>
<Pressable onPress={like.toggle} hitSlop={6} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel={like.failed ? '좋아요를 반영하지 못했어요. 다시 눌러 주세요' : '오늘 날씨 좋아요'} className={`h-8 flex-row items-center gap-1 px-[5px] ${like.liked ? '' : 'opacity-80'}`}>
<HeartIcon size={22} color={like.liked ? '#ff3b5c' : icon} filled={like.liked} />
{like.count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{like.count.toLocaleString()}</Text>}
</Pressable>
<Pressable onPress={() => open({ type: 'comments', postId: post.post_id })} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 댓글" className="h-8 flex-row items-center gap-1 px-[5px] opacity-80">
<CommentIcon size={22} color={icon} />
{post.comment_count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{post.comment_count.toLocaleString()}</Text>}
</Pressable>
</>
)}
<Pressable onPress={share} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 보내기" className="h-8 flex-row items-center px-[5px] opacity-80">
<SendIcon size={22} color={icon} />
</Pressable>
</View>
</View>
<View className="h-[146px] items-center">
<Fall d={0} f={5600} amp={8}>
<View className="mt-2 size-32 items-center justify-center" style={moon ? undefined : { boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}>
@@ -183,12 +285,15 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
<Rect x="-1" y="-1" width="2" height="2" rx="1" fill="url(#orb)" opacity={gray ? 0.85 : 1} />
</Svg>
)}
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text>
{/* 점수 근거가 있으면 해를 눌러도 근거 창 */}
<Pressable disabled={!why || score == null} onPress={openWhy} className="items-center" accessibilityLabel={why && score != null ? `${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기` : undefined}>
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text>
</Pressable>
</View>
</Fall>
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
@@ -217,19 +322,24 @@ export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
</Text>
</Text>
))}
{why && score != null && (
<Text onPress={openWhy} accessibilityRole="button" accessibilityLabel={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} style={{ color: dark ? '#ffb38a' : '#d4552a' }}>
{' '}· 점수 근거 ›
</Text>
)}
</Text>
)}
</View>
<View className="mt-2.5 flex-row gap-1 rounded-[18px] p-[3px]" style={{ backgroundColor: dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)' }} accessibilityRole="tablist" accessibilityLabel="하루 흐름, 누르면 그 시간대 하늘로">
{KINDS.map((k) => {
const isNow = k === nowKind;
const isNow = !tmr && k === nowKind;
const s = slotOf(isNow ? 'now' : k);
const on = k === kind;
return (
<Pressable key={k} accessibilityRole="tab" accessibilityState={{ selected: on }} onPress={() => setPreview(isNow ? null : k)} className={`flex-1 items-center rounded-[14px] py-1.5 ${on ? 'bg-white' : ''}`} style={on ? { boxShadow: '0 4px 12px rgb(40 48 74 / 0.1)' } : undefined}>
<Pressable key={k} accessibilityRole="tab" accessibilityState={{ selected: on }} onPress={() => (tmr ? setTmrKind(k) : setPreview(isNow ? null : k))} className={`flex-1 items-center rounded-[14px] py-1.5 ${on ? 'bg-white' : ''}`} style={on ? { boxShadow: '0 4px 12px rgb(40 48 74 / 0.1)' } : undefined}>
<Text className={`text-[13px] font-bold ${on ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{isNow ? '지금' : PREVIEW[k].label}</Text>
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} size={22} style={{ marginVertical: 2 }} />
<Text className={`font-jua text-[15px] ${on ? 'text-[#28304a]' : text}`}>{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</Text>
<Text className={`font-jua text-[15px] ${on ? 'text-[#28304a]' : text}`}>{heroVal(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</Text>
</Pressable>
);
})}
+61
View File
@@ -0,0 +1,61 @@
import { router, type Href } from 'expo-router';
import type { ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Rail } from '@/components/ui';
import { track } from '@/lib/analytics';
import { HIDDEN } from '@/lib/level';
import { useSajuSeenToday } from '@/lib/saju-birth';
type Item = { key: string; label: string; icon: string; badge?: ReactNode; to?: Href; onPress?: () => void };
const Dot = () => <View className="absolute -top-0.5 -right-0.5 size-[11px] rounded-full border-2 border-white bg-[#ff4d4f]" />;
function Tile({ it }: { it: Item }) {
return (
<>
<View className="size-[52px] items-center justify-center rounded-[17px] border-b-4 border-shade bg-card">
<Ic name={it.icon} size={32} />
{it.badge}
</View>
<Text className="mt-1.5 text-[11.5px] font-extrabold text-ink2">{it.label}</Text>
</>
);
}
/** 오늘 탭 히어로 아래 아이콘 줄: 누르면 그 화면으로 가거나 내 각 줄로 내려간다. 오늘 아직 안 본 사주엔 빨간 점 (웹 todayIcons.tsx, 타로는 웹처럼 숨김) */
export function TodayIcons({ foliage, onMyGak }: { foliage: boolean; onMyGak: () => void }) {
const sajuSeen = useSajuSeenToday();
const all: Item[] = [
{ key: 'saju', label: '날씨 사주', icon: 'yin_yang', badge: sajuSeen ? null : <Dot />, to: '/saju' },
{ key: 'game', label: '날씨 게임', icon: 'game', to: '/game' },
...(foliage ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' as Href }] : []),
{ key: 'shorts', label: '쇼츠', icon: 'clapper', to: '/shorts' },
{ key: 'myGak', label: '내 각', icon: 'rabbit', onPress: onMyGak },
{ key: 'talk', label: '동네 이야기', icon: 'speech', to: '/talk' },
];
const items = all.filter((it) => !HIDDEN.has(it.key));
return (
<View accessibilityLabel="바로 가기" className="pb-2">
<Rail>
{items.map((it) => (
<Pressable
key={it.key}
onPress={() => {
track('today_icon', { icon: it.key });
if (it.to) router.push(it.to);
else it.onPress?.();
}}
accessibilityRole={it.to ? 'link' : 'button'}
accessibilityLabel={it.label}
className="w-[60px] items-center"
>
<Tile it={it} />
</Pressable>
))}
</Rail>
</View>
);
}
+4 -90
View File
@@ -1,62 +1,18 @@
import type { BandArticle, BandEvent, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { cardBg, MEDALS } from '@nalssigak/shared/lib';
import type { BandArticle } from '@nalssigak/shared/api/client/types.gen';
import { cardBg } from '@nalssigak/shared/lib';
import { LinearGradient } from 'expo-linear-gradient';
import { Link, type Href } from 'expo-router';
import type { Href } from 'expo-router';
import type { ReactNode } from 'react';
import { Pressable, View } from 'react-native';
import { Text } from '@/components/text';
import { Ic, Rail, Sec, Skel, Thumb } from '@/components/ui';
import { Rail, Sec, Thumb } from '@/components/ui';
import { CARD_BG, BAND_BG } from '@/lib/colors';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
const CARD = 'overflow-hidden rounded-[22px] border-b-[5px] border-shade bg-card';
/** 오늘의 각 순위: 동그라미 + 이름 + 점수. 지금 시간대가 아닌 각은 흐리게 */
export function Stories({ items }: { items: TopIndex[] }) {
const { open } = useSheet();
return (
<Rail>
{items.map((g, i) => (
<Pressable key={g.index_id} onPress={() => open({ type: 'gak', indexId: g.index_id })} accessibilityLabel={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={`w-[72px] items-center gap-1 ${g.active ? '' : 'opacity-55'}`}>
<View className="size-[68px]">
{!g.active || g.score < 50 ? (
<View className="absolute inset-0 rounded-full bg-[#d6deea]" />
) : (
<LinearGradient colors={['#ff7a45', '#ffc86e', '#8fcaff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={{ position: 'absolute', inset: 0, borderRadius: 34 }} />
)}
<View className="m-[3px] flex-1 items-center justify-center rounded-full border-[3px] border-page bg-page">
<Ic name={g.icon} size={42} />
</View>
{i < 3 && g.active && <Ic name={MEDALS[i]} size={25} style={{ position: 'absolute', right: -4, bottom: -4 }} />}
</View>
<Text numberOfLines={1} className="font-jua text-[13px] text-ink">
{g.name}
</Text>
{g.active ? <Text className="font-bagel text-[12.5px] leading-[14px] text-orange">{g.score}</Text> : <Text className="text-[11px] leading-[14px] font-extrabold text-ink3">지금 아님</Text>}
</Pressable>
))}
</Rail>
);
}
const SKELS = Array.from({ length: 6 }, (_, i) => i);
export function StoriesSkel() {
return (
<Rail>
{SKELS.map((i) => (
<View key={i} className="w-[72px] items-center gap-1.5">
<View className="size-[68px] rounded-full bg-skel" />
<Skel className="w-12" />
<Skel className="w-6" />
</View>
))}
</Rail>
);
}
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: Href; children: ReactNode }) {
const { kind } = useSky();
return (
@@ -75,48 +31,6 @@ function useCardBg() {
return CARD_BG[kind === 'night' ? 'night' : 'day'];
}
export function EventsBand({ events }: { events: BandEvent[] }) {
const bg = useCardBg();
return (
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
<Rail>
{events.map((e, i) => (
<Link key={e.event_id} href="/week" asChild>
<Pressable className={`w-[200px] ${CARD}`}>
<Thumb image={e.image} icon={e.icon} iconSize={76} className="h-[116px]">
<LinearGradient colors={bg[cardBg(e.icon, i)]} style={{ position: 'absolute', inset: 0, zIndex: -1 }} />
<View className={`absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] ${e.status_label === '진행 중' ? 'bg-[#1f9d62]' : 'bg-orange'}`}>
<Text className="text-[11.5px] font-extrabold text-white">{e.status_label}</Text>
</View>
</Thumb>
<Text className="px-3 pt-2.5 pb-3 font-jua text-[16.5px] leading-snug text-ink">{e.name}</Text>
</Pressable>
</Link>
))}
</Rail>
</Band>
);
}
export function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
const { open } = useSheet();
return (
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
<Rail>
{items.slice(0, 5).map((g, i) => (
<Pressable key={g.index_id} onPress={() => open({ type: 'gak', indexId: g.index_id })} className="w-[138px] gap-1 rounded-[22px] border-b-[5px] border-shade bg-card p-3">
{i < 3 ? <Ic name={MEDALS[i]} size={26} style={{ position: 'absolute', top: 8, left: 8 }} /> : <Text className="absolute top-2.5 left-3 font-jua text-ink3">{i + 1}위</Text>}
<Ic name={g.icon} size={58} style={{ alignSelf: 'center' }} />
<Text className="font-jua text-base text-ink">{g.name}</Text>
<Text className="font-bagel text-[22px] leading-[24px] text-orange">{g.score}</Text>
{g.summary && <Text className="text-xs font-semibold text-ink2">{g.summary}</Text>}
</Pressable>
))}
</Rail>
</Band>
);
}
export function SeasonBand({ news }: { news: BandArticle[] }) {
const bg = useCardBg();
const { open } = useSheet();
+13
View File
@@ -11,6 +11,7 @@ import { useCSSVariable } from 'uniwind';
import { PinIcon } from '@/components/svg';
import { Avatar, Ic, Skel } from '@/components/ui';
import { useAuth } from '@/lib/auth';
import { useLevel } from '@/lib/level';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
@@ -35,6 +36,17 @@ function SeasonChip() {
);
}
/** 아바타 옆 작은 레벨 표시 */
function LevelBadge() {
const level = useLevel().data;
if (!level) return null;
return (
<View pointerEvents="none" className="absolute -right-1.5 -bottom-1.5 rounded-full border-2 border-white bg-ink-btn px-1.5">
<Text className="text-[9.5px] leading-4 font-extrabold text-white">Lv.{level.level}</Text>
</View>
);
}
/** 오른쪽 끝: 내 정보(아바타) 또는 로그인 버튼 */
function Account() {
const { open } = useSheet();
@@ -44,6 +56,7 @@ function Account() {
return (
<Pressable onPress={() => open({ type: 'me' })} accessibilityLabel={`내 정보, ${me.nickname}`} className="shrink-0 rounded-full" style={{ boxShadow: '0 6px 12px rgb(40 48 74 / 0.12)' }}>
<Avatar character={me.character} color={me.color} mood={me.mood} size={36} />
<LevelBadge />
</Pressable>
);
return (
+20
View File
@@ -0,0 +1,20 @@
import { GA_NAME, type Events as SharedEvents } from '@nalssigak/shared/lib/analytics';
import type { SheetState } from '@/lib/sheet';
/** 이벤트 목록은 웹과 같이 쓴다 (shared/lib/analytics.ts, docs/이벤트_추적.md) */
type Events = SharedEvents<Exclude<SheetState, null>['type']>;
type Sender = (name: string, params: Record<string, unknown>) => void;
let sender: Sender | null = null;
/** GA4 로 실제로 보내는 함수를 단다. Firebase Analytics(google-services.json)를 붙이면 앱 시작 때 부른다. 그 전에는 보내지 않는다 */
export function setAnalyticsSender(next: Sender | null) {
sender = next;
}
export function track<E extends keyof Events>(event: E, params: Events[E]) {
if (__DEV__) return;
sender?.(GA_NAME[event], { ...params, platform: 'app' });
}
+3 -1
View File
@@ -1,8 +1,10 @@
import { configureApi } from '@nalssigak/shared/api/setup';
import * as SecureStore from 'expo-secure-store';
import { API_URL } from '@/lib/site';
configureApi({
baseUrl: process.env.EXPO_PUBLIC_API_BASE_URL ?? 'http://localhost:9810',
baseUrl: API_URL,
storage: {
getItem: (key) => SecureStore.getItem(key),
setItem: (key, value) => SecureStore.setItem(key, value),
+13
View File
@@ -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]);
}
+67 -2
View File
@@ -1,4 +1,4 @@
// frontend/public 의 아이콘을 그대로 쓴다. Metro 는 정적 require 만 묶을 수 있어 이름마다 적는다
// frontend/public 의 아이콘을 그대로 쓴다 (공용 public/icons, 웹 전용 public/b/icons). Metro 는 정적 require 만 묶을 수 있어 이름마다 적는다
export const ICONS: Record<string, number> = {
apple: require('../../../frontend/public/icons/apple.png'),
baseball: require('../../../frontend/public/icons/baseball.png'),
@@ -6,6 +6,7 @@ export const ICONS: Record<string, number> = {
bike: require('../../../frontend/public/icons/bike.png'),
bingsu: require('../../../frontend/public/icons/bingsu.png'),
blanket: require('../../../frontend/public/icons/blanket.png'),
boiler: require('../../../frontend/public/icons/boiler.png'),
bronze: require('../../../frontend/public/icons/bronze.png'),
bungeoppang: require('../../../frontend/public/icons/bungeoppang.png'),
camping: require('../../../frontend/public/icons/camping.png'),
@@ -14,17 +15,24 @@ export const ICONS: Record<string, number> = {
chimaek: require('../../../frontend/public/icons/chimaek.png'),
cloud: require('../../../frontend/public/icons/cloud.png'),
coldwind: require('../../../frontend/public/icons/coldwind.png'),
date: require('../../../frontend/public/icons/date.png'),
delivery: require('../../../frontend/public/icons/delivery.png'),
dog: require('../../../frontend/public/icons/dog.png'),
drive: require('../../../frontend/public/icons/drive.png'),
fallen_leaf: require('../../../frontend/public/icons/fallen_leaf.png'),
fishing: require('../../../frontend/public/icons/fishing.png'),
flower: require('../../../frontend/public/icons/flower.png'),
frizz: require('../../../frontend/public/icons/frizz.png'),
game: require('../../../frontend/public/icons/game.png'),
garden: require('../../../frontend/public/icons/garden.png'),
gift: require('../../../frontend/public/icons/gift.png'),
ginkgo: require('../../../frontend/public/icons/ginkgo.png'),
glasses: require('../../../frontend/public/icons/glasses.png'),
gold: require('../../../frontend/public/icons/gold.png'),
golf: require('../../../frontend/public/icons/golf.png'),
hangang: require('../../../frontend/public/icons/hangang.png'),
hiking: require('../../../frontend/public/icons/hiking.png'),
hyodo: require('../../../frontend/public/icons/hyodo.png'),
iced_hot: require('../../../frontend/public/icons/iced_hot.png'),
indoordry: require('../../../frontend/public/icons/indoordry.png'),
jipkok: require('../../../frontend/public/icons/jipkok.png'),
@@ -38,10 +46,12 @@ export const ICONS: Record<string, number> = {
maple: require('../../../frontend/public/icons/maple.png'),
mask: require('../../../frontend/public/icons/mask.png'),
moon: require('../../../frontend/public/icons/moon.png'),
mosquito: require('../../../frontend/public/icons/mosquito.png'),
muggy: require('../../../frontend/public/icons/muggy.png'),
naengmyeon: require('../../../frontend/public/icons/naengmyeon.png'),
netflix: require('../../../frontend/public/icons/netflix.png'),
pajeon: require('../../../frontend/public/icons/pajeon.png'),
party: require('../../../frontend/public/icons/party.png'),
peanut: require('../../../frontend/public/icons/peanut.png'),
photo: require('../../../frontend/public/icons/photo.png'),
picnic: require('../../../frontend/public/icons/picnic.png'),
@@ -49,29 +59,84 @@ export const ICONS: Record<string, number> = {
rain: require('../../../frontend/public/icons/rain.png'),
riverwind: require('../../../frontend/public/icons/riverwind.png'),
running: require('../../../frontend/public/icons/running.png'),
selfie: require('../../../frontend/public/icons/selfie.png'),
sentimental: require('../../../frontend/public/icons/sentimental.png'),
silver: require('../../../frontend/public/icons/silver.png'),
singing_rain: require('../../../frontend/public/icons/singing_rain.png'),
snow: require('../../../frontend/public/icons/snow.png'),
stars: require('../../../frontend/public/icons/stars.png'),
study: require('../../../frontend/public/icons/study.png'),
sun_cloud: require('../../../frontend/public/icons/sun_cloud.png'),
sun: require('../../../frontend/public/icons/sun.png'),
sun_cloud: require('../../../frontend/public/icons/sun_cloud.png'),
sunscreen: require('../../../frontend/public/icons/sunscreen.png'),
sunset: require('../../../frontend/public/icons/sunset.png'),
sweet_potato: require('../../../frontend/public/icons/sweet_potato.png'),
tangerine: require('../../../frontend/public/icons/tangerine.png'),
taxi: require('../../../frontend/public/icons/taxi.png'),
tennis: require('../../../frontend/public/icons/tennis.png'),
thanks: require('../../../frontend/public/icons/thanks.png'),
themepark: require('../../../frontend/public/icons/themepark.png'),
trot: require('../../../frontend/public/icons/trot.png'),
umbrella: require('../../../frontend/public/icons/umbrella.png'),
vent: require('../../../frontend/public/icons/vent.png'),
walk: require('../../../frontend/public/icons/walk.png'),
waterplay: require('../../../frontend/public/icons/waterplay.png'),
yajang: require('../../../frontend/public/icons/yajang.png'),
alarm_clock: require('../../../frontend/public/b/icons/alarm_clock.png'),
bat: require('../../../frontend/public/b/icons/bat.png'),
briefcase: require('../../../frontend/public/b/icons/briefcase.png'),
bulb: require('../../../frontend/public/b/icons/bulb.png'),
calendar: require('../../../frontend/public/b/icons/calendar.png'),
candy: require('../../../frontend/public/b/icons/candy.png'),
check_mark_button: require('../../../frontend/public/b/icons/check_mark_button.png'),
christmas_tree: require('../../../frontend/public/b/icons/christmas_tree.png'),
clapper: require('../../../frontend/public/b/icons/clapper.png'),
concert: require('../../../frontend/public/b/icons/concert.png'),
crystal_ball: require('../../../frontend/public/b/icons/crystal_ball.png'),
dango: require('../../../frontend/public/b/icons/dango.png'),
droplet: require('../../../frontend/public/b/icons/droplet.png'),
exhibition: require('../../../frontend/public/b/icons/exhibition.png'),
fireworks: require('../../../frontend/public/b/icons/fireworks.png'),
full_moon: require('../../../frontend/public/b/icons/full_moon.png'),
ghost: require('../../../frontend/public/b/icons/ghost.png'),
jack_o_lantern: require('../../../frontend/public/b/icons/jack_o_lantern.png'),
leaf: require('../../../frontend/public/b/icons/leaf.png'),
locked: require('../../../frontend/public/b/icons/locked.png'),
lollipop: require('../../../frontend/public/b/icons/lollipop.png'),
milky_way: require('../../../frontend/public/b/icons/milky_way.png'),
money_bag: require('../../../frontend/public/b/icons/money_bag.png'),
moon_viewing: require('../../../frontend/public/b/icons/moon_viewing.png'),
pear: require('../../../frontend/public/b/icons/pear.png'),
pepero_almond: require('../../../frontend/public/b/icons/pepero_almond.png'),
pepero_basket: require('../../../frontend/public/b/icons/pepero_basket.png'),
pepero_box: require('../../../frontend/public/b/icons/pepero_box.png'),
pepero_bundle: require('../../../frontend/public/b/icons/pepero_bundle.png'),
pepero_choco: require('../../../frontend/public/b/icons/pepero_choco.png'),
pepero_nude: require('../../../frontend/public/b/icons/pepero_nude.png'),
pepero_pair: require('../../../frontend/public/b/icons/pepero_pair.png'),
pepero_strawberry: require('../../../frontend/public/b/icons/pepero_strawberry.png'),
popup: require('../../../frontend/public/b/icons/popup.png'),
rainbow: require('../../../frontend/public/b/icons/rainbow.png'),
red_heart: require('../../../frontend/public/b/icons/red_heart.png'),
sheaf: require('../../../frontend/public/b/icons/sheaf.png'),
shooting_star: require('../../../frontend/public/b/icons/shooting_star.png'),
skull: require('../../../frontend/public/b/icons/skull.png'),
sparkles: require('../../../frontend/public/b/icons/sparkles.png'),
speech: require('../../../frontend/public/b/icons/speech.png'),
spider: require('../../../frontend/public/b/icons/spider.png'),
spider_web: require('../../../frontend/public/b/icons/spider_web.png'),
spiral_calendar: require('../../../frontend/public/b/icons/spiral_calendar.png'),
sunrise: require('../../../frontend/public/b/icons/sunrise.png'),
thermo: require('../../../frontend/public/b/icons/thermo.png'),
tshirt: require('../../../frontend/public/b/icons/tshirt.png'),
two_hearts: require('../../../frontend/public/b/icons/two_hearts.png'),
warning: require('../../../frontend/public/b/icons/warning.png'),
xmas_candy_cane: require('../../../frontend/public/b/icons/xmas_candy_cane.png'),
xmas_gingerbread: require('../../../frontend/public/b/icons/xmas_gingerbread.png'),
xmas_ornament: require('../../../frontend/public/b/icons/xmas_ornament.png'),
xmas_santa: require('../../../frontend/public/b/icons/xmas_santa.png'),
xmas_santa_hat: require('../../../frontend/public/b/icons/xmas_santa_hat.png'),
xmas_stocking: require('../../../frontend/public/b/icons/xmas_stocking.png'),
xmas_wreath: require('../../../frontend/public/b/icons/xmas_wreath.png'),
yin_yang: require('../../../frontend/public/b/icons/yin_yang.png'),
};
+95
View File
@@ -0,0 +1,95 @@
import { attendMutation, myLevelOptions, myLevelQueryKey, sharedMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { ResLevel } from '@nalssigak/shared/api/client/types.gen';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { router, type Href } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useRef } from 'react';
import { useAuth } from '@/lib/auth';
import { useSheet } from '@/lib/sheet';
/** 잠시 숨긴 기능 (아이콘 줄·각 모으는 법에서 뺀다, 웹 features.ts 와 같게) */
export const HIDDEN = new Set<string>(['tarot']);
// 받침 있으면 a, 없으면 b: josa('연애운', '이', '가') → '연애운이'
export const josa = (w: string, a: string, b: string) => {
const c = w.charCodeAt(w.length - 1) - 0xac00;
return w + (c >= 0 && c < 11172 && c % 28 === 0 ? b : a);
};
// 레벨마다 보여 줄 하늘 아이콘 (이름은 서버 LEVELS)
const LEVEL_ICON = ['droplet', 'sun', 'leaf', 'rainbow', 'sunset', 'milky_way', 'shooting_star'];
export const levelIcon = (level: number) => LEVEL_ICON[Math.min(Math.max(level, 1), LEVEL_ICON.length) - 1];
/** 서버 응답에서 기본값이 있는 칸은 생략될 수 있어 채워 둔다 */
export type Level = ResLevel & { points: number; level: number; floor: number; streak: number };
const toLevel = (d: ResLevel): Level | undefined => (d.result?.success ? { ...d, points: d.points ?? 0, level: d.level ?? 1, floor: d.floor ?? 0, streak: d.streak ?? 0 } : undefined);
/** 내 레벨 (로그인했을 때만). 각을 주는 일은 모두 mutation 이라 끝날 때마다 다시 받는다(query-client.ts) */
export function useLevel() {
const { loggedIn } = useAuth();
return useQuery({ ...myLevelOptions(), enabled: loggedIn, staleTime: 60_000, select: toLevel });
}
/** 다음 레벨까지 진행률 0~1 */
export function progress(l: Level) {
if (l.next_points == null) return 1;
return Math.min(1, (l.points - l.floor) / (l.next_points - l.floor));
}
/** 다음 레벨에서 열리는 것 이름 */
export const nextUnlock = (l: Level) => (l.unlocks ?? []).filter((u) => u.level === l.level + 1).map((u) => u.name);
/** 창을 닫고 그 화면으로 간다 */
export function useCloseAndGo() {
const { close } = useSheet();
return (to: string) => {
close();
router.push(to as Href);
};
}
const SEEN_KEY = 'nalssigak.levelSeen';
/** 로그인한 사람이 앱을 열면 하루 한 번 출석 각. 레벨이 오르면 축하 창을 띄운다 (루트 레이아웃에 한 번 둔다) */
export function LevelWatcher() {
const { loggedIn, me } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
const level = useLevel().data;
const { mutate } = useMutation({ ...attendMutation() });
const attended = useRef<string | null>(null);
useEffect(() => {
if (!loggedIn || !me || attended.current === me.login_id) return;
attended.current = me.login_id;
mutate({}, { onSuccess: (res) => res.result?.success && queryClient.setQueryData(myLevelQueryKey(), res) });
}, [loggedIn, me, mutate, queryClient]);
useEffect(() => {
if (!level || !me) return;
// SecureStore 키는 영문·숫자·._- 만 된다
const key = `${SEEN_KEY}.${me.login_id.replace(/[^\w.-]/g, '_')}`;
let seen: number | null = null;
try {
seen = Number(SecureStore.getItem(key)) || null;
SecureStore.setItem(key, String(level.level));
} catch (e) {
console.warn('[level] 본 레벨을 저장하지 못함', e);
}
// 처음 보는 기기에선 축하하지 않는다 (예전 레벨을 모름)
if (seen != null && level.level > seen) open({ type: 'levelUp', level: level.level });
}, [level, me, open]);
return null;
}
/** 공유를 마치면 하루 한 번 각 (로그인했을 때만) */
export function useShareReward() {
const { loggedIn } = useAuth();
const { mutate } = useMutation({ ...sharedMutation() });
return () => {
if (loggedIn) mutate({});
};
}
+159
View File
@@ -0,0 +1,159 @@
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { scoreMyGak } from '@nalssigak/shared/api/client/sdk.gen';
import type { MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useSyncExternalStore } from 'react';
import { track } from '@/lib/analytics';
import { useAuth } from '@/lib/auth';
import { useRegion } from '@/lib/region';
import { useSheet } from '@/lib/sheet';
import { SITE_URL } from '@/lib/site';
const KEY = 'nalssigak.myRule';
export type Slot = 'morning' | 'day' | 'evening' | 'night';
export const SLOTS: [Slot, string][] = [
['morning', '아침'],
['day', '낮'],
['evening', '저녁'],
['night', '밤'],
];
export const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>;
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) (웹 myGakState.ts) */
export type MyGak = { id?: number; name: string; icon?: string | null; rule: MyGakRule };
/** 아이콘을 안 골랐을 때 */
export const MY_GAK_ICON = 'rabbit';
function readLocal(): MyGak | null {
try {
const raw = SecureStore.getItem(KEY);
return raw ? (JSON.parse(raw) as MyGak) : null;
} catch (e) {
console.warn('[myGak] 기기에 저장한 각을 읽지 못함', e);
return null;
}
}
// 창과 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
let local: MyGak | null | undefined;
const listeners = new Set<() => void>();
const subscribe = (cb: () => void) => {
listeners.add(cb);
return () => listeners.delete(cb);
};
const getLocal = () => {
if (local === undefined) local = readLocal();
return local;
};
function setLocal(g: MyGak | null) {
local = g;
listeners.forEach((cb) => cb());
try {
if (g) SecureStore.setItem(KEY, JSON.stringify(g));
else void SecureStore.deleteItemAsync(KEY);
} catch (e) {
console.warn('[myGak] 기기에 저장하지 못함', e);
}
}
/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
export const gakName = (name: string) => {
const n = name.trim().replace(/\s+/g, ' ');
return n && !n.endsWith('각') ? `${n}각` : n;
};
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 (웹과 같은 형식) */
export function shareUrl(g: MyGak) {
const json = JSON.stringify({ n: g.name, i: g.icon ?? undefined, r: g.rule });
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)));
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`;
}
export function fromShare(code: string): MyGak | null {
try {
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'));
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; i?: unknown; r?: unknown };
const icon = typeof v.i === 'string' && /^[a-z_]{1,32}$/.test(v.i) ? v.i : null;
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, icon, rule: v.r as MyGakRule } : null;
} catch (e) {
console.warn('[myGak] 받은 링크를 읽지 못함', e);
return null;
}
}
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
export function useMyGakScores(rules: MyGakRule[]) {
const { region } = useRegion();
return useQuery({
queryKey: ['myGakScore', region.code, rules],
enabled: rules.length > 0,
staleTime: 5 * 60_000,
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } });
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score');
return { nowSlot: data.now_slot as Slot | null | undefined, scores: data.scores ?? [] };
},
});
}
/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */
export function usePresets() {
return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] });
}
export function useMyGak() {
const { loggedIn } = useAuth();
const { open } = useSheet();
const queryClient = useQueryClient();
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn });
const saved = useSyncExternalStore(subscribe, getLocal);
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() });
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh });
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh });
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
const { mutate } = add;
useEffect(() => {
if (!loggedIn || !saved) return;
mutate({ body: { name: saved.name, icon: saved.icon, rule: saved.rule } }, { onSuccess: () => setLocal(null) });
}, [loggedIn, saved, mutate]);
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, icon: g.icon, rule: g.rule })) : saved ? [saved] : [];
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
const create = (g: MyGak, onDone?: () => void) => {
const item = { name: gakName(g.name), icon: g.icon, rule: g.rule };
if (loggedIn) {
add.mutate(
{ body: item },
{
onSuccess: (res) => {
if (!res.result?.success) return;
track('my_gak_save', { gak_name: item.name });
onDone?.();
},
},
);
return;
}
if (saved) {
open({ type: 'login' });
return;
}
setLocal(item);
track('my_gak_save', { gak_name: item.name });
onDone?.();
};
const remove = (g: MyGak) => {
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } });
setLocal(null);
};
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false };
}
+43
View File
@@ -0,0 +1,43 @@
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen';
import type { PinnedKey } from '@nalssigak/shared/lib/analytics';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { track } from '@/lib/analytics';
/** 히어로·오늘의 각처럼 포스트 틀이 아닌 카드의 좋아요 (웹 pinnedLike.ts). 로그인 없이 된다. 화면을 먼저 바꾸고 실패하면 되돌린다 */
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
const queryClient = useQueryClient();
const like = useMutation(likePostMutation());
const unlike = useMutation(unlikePostMutation());
const [failed, setFailed] = useState(false);
const liked = !!r?.liked;
const count = r?.like_count ?? 0;
const patch = (values: Partial<PostReaction>) =>
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed,
);
const toggle = () => {
if (!r || like.isPending || unlike.isPending) return;
const on = !liked;
setFailed(false);
patch({ liked: on, like_count: count + (on ? 1 : -1) });
const revert = () => {
patch({ liked, like_count: count });
setFailed(true);
};
(on ? like : unlike).mutate(
{ path: { post_id: r.post_id } },
{
onSuccess: (res) => {
if (!res.result?.success) return revert();
patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) });
if (on) track('like', { content_type: key, item_id: r.post_id });
},
onError: revert,
},
);
};
return { liked, count, failed, toggle };
}
+5 -2
View File
@@ -1,4 +1,5 @@
import { focusManager, keepPreviousData, QueryClient } from '@tanstack/react-query';
import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { focusManager, keepPreviousData, MutationCache, QueryClient } from '@tanstack/react-query';
import { AppState, Platform } from 'react-native';
// 앱이 다시 앞으로 오면 '포커스'로 보고, 5분 넘게 묵은 데이터만 다시 받는다
@@ -10,6 +11,8 @@ if (Platform.OS !== 'web') {
}
// 웹과 같은 기본값: 다시 받는 동안 이전 결과를 그대로 두어 화면이 비지 않게 한다
export const queryClient = new QueryClient({
export const queryClient: QueryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, placeholderData: keepPreviousData } },
// 각을 주는 일(좋아요·댓글·글·공유·사주)은 모두 mutation 이라, 끝나면 내 레벨을 다시 받는다 (웹 main.tsx)
mutationCache: new MutationCache({ onSuccess: () => queryClient.invalidateQueries({ queryKey: myLevelQueryKey() }) }),
});
+8 -1
View File
@@ -5,6 +5,8 @@ import * as Location from 'expo-location';
import * as SecureStore from 'expo-secure-store';
import { createContext, use, useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
import { track } from '@/lib/analytics';
const KEY = 'nalssigak.region';
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error';
@@ -67,6 +69,7 @@ export function RegionProvider({ children }: { children: ReactNode }) {
if (r === 'denied') return setLocateStatus('denied');
setLocateStatus('idle');
setRegion(r);
track('region_change', { region_name: r.name, method: 'location' });
onFound?.();
})
.catch((e: unknown) => {
@@ -81,7 +84,11 @@ export function RegionProvider({ children }: { children: ReactNode }) {
useEffect(() => {
if (stored) return;
findNearest()
.then((r) => r !== 'denied' && setRegion(r))
.then((r) => {
if (r === 'denied') return;
setRegion(r);
track('region_change', { region_name: r.name, method: 'location' });
})
.catch((e: unknown) => console.warn('첫 위치로 지역을 찾지 못함', e))
.finally(() => setLocateStatus('idle'));
}, [stored, setRegion]);
+169
View File
@@ -0,0 +1,169 @@
import { getBirthQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { deleteBirth, getBirth, putBirth } from '@nalssigak/shared/api/client/sdk.gen';
import type { SajuSavedBirth } from '@nalssigak/shared/api/client/types.gen';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useSyncExternalStore } from 'react';
import { useAuth } from '@/lib/auth';
/** 날씨 사주에 쓰는 태어난 정보. 기기에 두고, 로그인했으면 계정에도 저장한다 (웹 sajuBirth.ts) */
export type Birth = { y: number; m: number; d: number; hour: number | null; minute: number | null; place: string; gender: 'M' | 'F' | null };
// SecureStore 키는 영문·숫자·._- 만 된다
const KEY = 'nalssigak.birth';
const SEEN_KEY = 'nalssigak.sajuSeen';
/** 태어난 곳: 시각을 그곳 경도로 맞춘다 (시·도청 경도) */
export const BIRTH_PLACES: [string, string, number][] = [
['seoul', '서울', 126.98],
['busan', '부산', 129.08],
['daegu', '대구', 128.6],
['incheon', '인천', 126.71],
['gwangju', '광주', 126.85],
['daejeon', '대전', 127.38],
['ulsan', '울산', 129.31],
['sejong', '세종', 127.29],
['gyeonggi', '경기', 127.01],
['gangwon', '강원', 127.73],
['chungbuk', '충북', 127.49],
['chungnam', '충남', 126.67],
['jeonbuk', '전북', 127.11],
['jeonnam', '전남', 126.46],
['gyeongbuk', '경북', 128.51],
['gyeongnam', '경남', 128.69],
['jeju', '제주', 126.5],
];
export const placeLon = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[2] ?? 127;
export const placeName = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[1] ?? key;
const pad = (n: number) => String(n).padStart(2, '0');
/** 사주 풀이·궁합 요청에 넣는 생년월일 */
export const toBody = (b: Birth) => ({
birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`,
birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined,
longitude: placeLon(b.place),
});
function readLocal(): Birth | null {
try {
const raw = SecureStore.getItem(KEY);
return raw ? (JSON.parse(raw) as Birth) : null;
} catch (e) {
console.warn('[saju] 기기에 저장한 생년월일을 읽지 못함', e);
return null;
}
}
// 사주 화면과 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
let birth: Birth | null | undefined;
const listeners = new Set<() => void>();
const subscribe = (cb: () => void) => {
listeners.add(cb);
return () => listeners.delete(cb);
};
const getBirthLocal = () => {
if (birth === undefined) birth = readLocal();
return birth;
};
export function setBirth(b: Birth | null) {
birth = b;
listeners.forEach((cb) => cb());
try {
if (b) SecureStore.setItem(KEY, JSON.stringify(b));
else void SecureStore.deleteItemAsync(KEY);
} catch (e) {
console.warn('[saju] 기기에 저장하지 못함', e);
}
}
export const useBirth = () => useSyncExternalStore(subscribe, getBirthLocal);
const toSaved = (b: Birth): SajuSavedBirth => ({
birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`,
birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined,
place: b.place,
gender: b.gender === 'M' ? 'male' : b.gender === 'F' ? 'female' : undefined,
});
const fromSaved = (s: SajuSavedBirth): Birth => {
const [y, m, d] = s.birth_date.split('-').map(Number);
const [hour, minute] = s.birth_time ? s.birth_time.split(':').map(Number) : [null, null];
return { y, m, d, hour, minute, place: s.place ?? 'seoul', gender: s.gender === 'male' ? 'M' : s.gender === 'female' ? 'F' : null };
};
/** 로그인했으면 계정의 생년월일을 기기로 가져온다. 계정엔 없고 기기에만 있으면 계정으로 올린다. 받는 중이면 true */
export function useAccountBirth() {
const { loggedIn } = useAuth();
const q = useQuery({ queryKey: getBirthQueryKey(), enabled: loggedIn, staleTime: Infinity, queryFn: async () => (await getBirth()).data });
useEffect(() => {
if (!loggedIn || !q.data?.result?.success) return;
if (q.data.birth) setBirth(fromSaved(q.data.birth));
else {
const local = getBirthLocal();
if (local) putBirth({ body: toSaved(local) }).catch((e) => console.warn('[saju] 계정에 올리지 못함', e));
}
}, [loggedIn, q.data]);
return loggedIn && q.isPending;
}
/** 생년월일 저장·지우기: 기기에 두고, 로그인했으면 계정에도 */
export function useSaveBirth() {
const { loggedIn } = useAuth();
const queryClient = useQueryClient();
return async (b: Birth | null) => {
setBirth(b);
if (!loggedIn) return;
try {
const { data } = b ? await putBirth({ body: toSaved(b) }) : await deleteBirth();
if (data.result?.success) queryClient.setQueryData(getBirthQueryKey(), data);
} catch (e) {
console.warn('[saju] 계정에 저장하지 못함', e);
}
};
}
/** 있는 날짜이고 1900-01-01 ~ 오늘 사이인지 */
export function validBirth(y: number, m: number, d: number) {
const at = new Date(Date.UTC(y, m - 1, d));
const ok = at.getUTCFullYear() === y && at.getUTCMonth() === m - 1 && at.getUTCDate() === d;
return ok && y >= 1900 && at.getTime() <= Date.now();
}
// 오늘 사주를 본 날 (오늘 아이콘 줄의 빨간 점)
let seen: string | null | undefined;
const seenListeners = new Set<() => void>();
const subscribeSeen = (cb: () => void) => {
seenListeners.add(cb);
return () => seenListeners.delete(cb);
};
const getSeen = () => {
if (seen === undefined) {
try {
seen = SecureStore.getItem(SEEN_KEY);
} catch (e) {
console.warn('[saju] 본 날을 읽지 못함', e);
// 저장소를 못 쓰면 점을 보이지 않는다
seen = new Date().toDateString();
}
}
return seen;
};
/** 오늘 아이콘 줄의 빨간 점: 오늘 날씨 사주를 이미 봤는지 (웹 SajuPage sajuSeenToday) */
export const sajuSeenToday = () => getSeen() === new Date().toDateString();
/** sajuSeenToday 를 화면에서 쓸 때: 사주를 보고 돌아오면 바로 점이 사라진다 */
export const useSajuSeenToday = () => useSyncExternalStore(subscribeSeen, getSeen) === new Date().toDateString();
export function markSajuSeen() {
seen = new Date().toDateString();
seenListeners.forEach((cb) => cb());
try {
SecureStore.setItem(SEEN_KEY, seen);
} catch (e) {
console.warn('[saju] 본 날을 저장하지 못함', e);
}
}
+21 -4
View File
@@ -3,16 +3,33 @@ import type { RefObject } from 'react';
import { Share, type View } from 'react-native';
import { captureRef } from 'react-native-view-shot';
/** 보이는 화면 조각을 PNG로 찍어 공유. 이미지 공유가 안 되는 곳(웹 등)이면 글로 보낸다 */
export async function shareView(ref: RefObject<View | null>, { title, message }: { title: string; message: string }) {
import { track } from '@/lib/analytics';
import { useShareReward } from '@/lib/level';
type ShareText = { title: string; message: string };
/** 보이는 화면 조각을 PNG로 찍어 공유. 이미지 공유가 안 되는 곳(웹 등)이면 글로 보낸다. 보냈으면 true */
async function shareView(ref: RefObject<View | null>, { title, message }: ShareText) {
try {
if (ref.current && (await Sharing.isAvailableAsync())) {
const uri = await captureRef(ref, { format: 'png', quality: 1, result: 'tmpfile' });
await Sharing.shareAsync(uri, { mimeType: 'image/png', UTI: 'public.png', dialogTitle: title });
return;
// 앱은 보이는 카드를 그대로 찍어 보내므로 비율은 'card'
track('share', { content_type: 'image', item_id: title, method: 'share_sheet', ratio: 'card' });
return true;
}
await Share.share({ message });
const res = await Share.share({ message });
return res.action === Share.sharedAction;
} catch (e) {
console.warn('공유 실패', e);
return false;
}
}
/** 화면 조각 공유. 보내면 하루 한 번 각을 받는다 (로그인했을 때만) */
export function useShare() {
const reward = useShareReward();
return async (ref: RefObject<View | null>, text: ShareText) => {
if (await shareView(ref, text)) reward();
};
}
+12 -2
View File
@@ -1,15 +1,25 @@
import { createContext, use } from 'react';
type CommentsState = { type: 'comments'; postId: number; draft?: string };
import type { WeatherWhyPayload } from '@/components/sheets/weather-why';
import type { MyGak } from '@/lib/my-gak';
/** 댓글이 달린 곳: 운영 포스트 또는 사람 글 */
export type CommentTarget = { postId: number } | { talkId: number };
type CommentsState = { type: 'comments'; draft?: string } & CommentTarget;
export type SheetState =
| { type: 'gak'; indexId: number }
| { type: 'article'; articleId: number }
| CommentsState
| { type: 'seasonWeek' }
| { type: 'login'; then?: CommentsState }
| { type: 'login'; then?: CommentsState; why?: 'level' }
| { type: 'me' }
| { type: 'region' }
| { type: 'weatherWhy'; why: WeatherWhyPayload }
| { type: 'level' }
| { type: 'levelUp'; level: number }
| { type: 'mix'; shared?: MyGak }
| { type: 'myGak'; gak: MyGak }
| null;
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void };
+5
View File
@@ -2,3 +2,8 @@ export const SITE_URL = (process.env.EXPO_PUBLIC_SITE_URL ?? 'https://weather.o2
/** 서버가 주는 사진 경로가 '/season/..' 처럼 사이트 기준이면 사이트 주소를 붙인다 */
export const imageUri = (path: string) => (path.startsWith('/') ? `${SITE_URL}${path}` : path);
/** API 서버 주소. 카드뉴스 그림(/v1/card/...)처럼 API 서버에서 주는 경로에 붙인다 */
export const API_URL = (process.env.EXPO_PUBLIC_API_BASE_URL ?? 'http://localhost:9810').replace(/\/+$/, '');
export const apiUri = (path: string) => (path.startsWith('/') ? `${API_URL}${path}` : path);
+75
View File
@@ -0,0 +1,75 @@
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen';
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen';
import { kst } from '@nalssigak/shared/lib';
import { HOLIDAYS, holidayOn } from '@nalssigak/shared/lib/holiday';
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';
import { useRegion } from '@/lib/region';
import { apiUri } from '@/lib/site';
// 글 주제와 이름 (웹 talkState.ts)
export const TOPICS = [
[TalkTopic.LOCAL, '동네 이야기'],
[TalkTopic.SKY, '하늘·노을'],
[TalkTopic.RAIN, '비·눈'],
[TalkTopic.FOLIAGE, '단풍·꽃'],
[TalkTopic.OUTFIT, '오늘 옷차림'],
...HOLIDAYS.map((h) => [h.topic, h.name] as const),
] as const;
export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기';
/** 지금 고를 수 있는 주제: 기념일 주제는 그 기간에만 */
export function openTopics() {
const on = holidayOn()?.topic;
return TOPICS.filter(([k]) => !HOLIDAYS.some((h) => h.topic === k) || k === on);
}
/** 주제별 글 페이지 목록 (topic 없으면 전체) */
export function useTopicTalks(topic?: TalkTopic) {
const { region } = useRegion();
const list = useInfiniteQuery({
...listTalksInfiniteOptions({ query: { region: region.code, ...(topic ? { topic } : {}) } }),
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
});
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
refetch: list.refetch,
refetching: list.isRefetching,
};
}
/** 내가 쓴 글 (최신순) */
export function useMyTalks(enabled = true) {
const list = useInfiniteQuery({
...listMyTalksInfiniteOptions(),
enabled,
initialPageParam: {},
getNextPageParam: (last) => last.next_cursor ?? undefined,
});
return {
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
loaded: list.isSuccess,
more: list.hasNextPage && !list.isFetchingNextPage,
loadMore: list.fetchNextPage,
};
}
export function useRefreshTalks() {
const queryClient = useQueryClient();
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') });
}
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
function slotWord(iso: string) {
const h = kst(iso).h;
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤';
}
export const talkMeta = (t: TalkData) => [t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ');
/** 올린 사진은 API 서버 경로(/v1/talk/image/...) */
export const talkImage = (t: TalkData) => (t.image ? apiUri(t.image) : undefined);
+38
View File
@@ -54,6 +54,7 @@
"expo-font": "~57.0.4",
"expo-glass-effect": "~57.0.4",
"expo-image": "~57.0.5",
"expo-image-picker": "~57.0.20",
"expo-linear-gradient": "~57.0.2",
"expo-linking": "~57.0.12",
"expo-location": "~57.0.21",
@@ -75,6 +76,7 @@
"react-native-svg": "15.15.4",
"react-native-view-shot": "5.1.0",
"react-native-web": "~0.21.0",
"react-native-webview": "13.16.1",
"react-native-worklets": "0.10.1",
"tailwindcss": "^4.3.3",
"uniwind": "^1.12.2"
@@ -15524,6 +15526,42 @@
"peerDependencies": {
"@tanstack/react-query": "^5.104.0"
}
},
"node_modules/expo-image-loader": {
"version": "57.0.1",
"resolved": "https://registry.npmjs.org/expo-image-loader/-/expo-image-loader-57.0.1.tgz",
"integrity": "sha512-uhrZKLT/cTl2mXyR28kPpVkS5O+PK9N1QA/07IFM4f5T4g0lTW1JHT3NEWwEEsGFldPmVX4j7LwUVVZxE+woug==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-image-picker": {
"version": "57.0.20",
"resolved": "https://registry.npmjs.org/expo-image-picker/-/expo-image-picker-57.0.20.tgz",
"integrity": "sha512-plgcGuMZMWqDchjXQW6S/WepYLB5KqfbZOzwC6xe0+j5IhY4ipvVuRZcXeP/0NgKgU0Jiu/XoTK4Bi8crtZ+sQ==",
"license": "MIT",
"dependencies": {
"expo-image-loader": "~57.0.1"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/react-native-webview": {
"version": "13.16.1",
"resolved": "https://registry.npmjs.org/react-native-webview/-/react-native-webview-13.16.1.tgz",
"integrity": "sha512-If0eHhoEdOYDcHsX+xBFwHMbWBGK1BvGDQDQdVkwtSIXiq1uiqjkpWVP2uQ1as94J0CzvFE9PUNDuhiX0Z6ubw==",
"license": "MIT",
"peer": true,
"dependencies": {
"escape-string-regexp": "^4.0.0",
"invariant": "2.2.4"
},
"peerDependencies": {
"react": "*",
"react-native": "*"
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
/** 히어로·오늘의 각·단풍 지도·띠처럼 포스트 틀이 아닌 카드 (피드 응답의 반응 칸 이름) */
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
export type HolidayKey = 'halloween' | 'pepero' | 'christmas' | 'chuseok'
/** GA4로 보내는 이벤트와 값 (웹·앱 같이 씀). 목록은 docs/이벤트_추적.md. Sheet 는 화면마다 다른 창 이름 */
export type Events<Sheet extends string = string> = {
view_gak: { index_id: number; gak_name: string; score: number; rank: number }
select_content: { content_type: 'article'; item_id: number; category: string }
share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string }
login: { method: 'id' | 'google' | 'toss' }
sign_up: { method: 'id' | 'google' | 'toss' }
region_change: { region_name: string; method: 'list' | 'location' }
install_banner_view: Record<string, never>
install_click: { from: 'banner' | 'menu'; method: 'prompt' | 'guide' }
install_choice: { outcome: 'accepted' | 'dismissed' }
install_done: Record<string, never>
app_launch: { mode: 'standalone' }
/** index.html 첫 화면 스크립트가 gtag 로 바로 보낸다 */
boot_stuck: { reason: string; seconds: number; tries: number; app_started: boolean }
sheet_open: { sheet: Sheet }
like: { content_type: 'post' | 'comment' | 'talk' | PinnedKey; item_id: number }
comment: { post_id: number }
talk_comment: { talk_id: number }
report: { content_type: 'comment' | 'talk'; reason: number }
block: { content_type: 'comment' | 'talk' }
terms_agree: Record<string, never>
talk_post: { topic: number; with_image: boolean }
feed_item_view: { item_type: 'talk' | 'event'; position: number }
hero_day_switch: { day: 'today' | 'tomorrow' }
tomorrow_to_today: { region_name: string }
search_landing: { page: 'today' | 'tomorrow'; engine: 'google' | 'naver'; copy: 'new' | 'old' | 'none' }
shorts_open: { video_id: string }
shorts_view: { video_id: string; index: number }
shorts_sound: { on: boolean }
foliage_open: Record<string, never>
foliage_spot: { spot_name: string; from: 'page' | 'card' }
my_gak_save: { gak_name: string }
fortune_draw: { card: string }
day_log: { mood: number; went_out: boolean; card_hit: boolean | null }
today_icon: { icon: string }
saju_input: { with_time: boolean }
saju_view: { scene: string; score: number; strength: string; top_element: string }
game_start: { again: boolean; logged_in: boolean; wind_ms: number; theme: 'basic' | HolidayKey }
game_round: { round: number; score: number; logged_in: boolean }
game_over: { round: number; score: number; best: boolean; drops: number }
toss_intro_start: Record<string, never>
install_banner_close: Record<string, never>
}
/** GA 에 찍히는 이벤트 이름 (한국어). 코드에서는 왼쪽 키로 부른다 */
export const GA_NAME: Record<keyof Events, string> = {
view_gak: '각_보기',
select_content: '글_열기',
share: '공유',
login: '로그인',
sign_up: '회원가입',
region_change: '지역_변경',
install_banner_view: '설치배너_노출',
install_click: '설치_누름',
install_choice: '설치_선택',
install_done: '설치_완료',
app_launch: '앱_실행',
boot_stuck: '첫화면_멈춤',
sheet_open: '창_열기',
like: '좋아요',
comment: '댓글',
talk_comment: '이야기_댓글',
report: '신고',
block: '차단',
terms_agree: '약관_동의',
talk_post: '이야기_올림',
feed_item_view: '피드_항목_노출',
hero_day_switch: '오늘내일_전환',
tomorrow_to_today: '내일에서_오늘로',
search_landing: '검색_유입',
shorts_open: '쇼츠_열기',
shorts_view: '쇼츠_보기',
shorts_sound: '쇼츠_소리',
foliage_open: '단풍지도_열기',
foliage_spot: '단풍명소_보기',
my_gak_save: '내각_저장',
fortune_draw: '타로_뽑기',
day_log: '하루_기록',
today_icon: '오늘아이콘_누름',
saju_input: '사주_입력',
saju_view: '사주_결과',
game_start: '게임_시작',
game_round: '게임_라운드',
game_over: '게임_끝',
toss_intro_start: '토스소개_시작',
install_banner_close: '설치배너_닫기',
}
+201
View File
@@ -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<Raw, 'basis' | 'lat' | 'lon'> & { 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<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' }
export const KIND: Record<Kind, string> = { 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<string, number>()
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<string, { w: number; h: number }>
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<string, { left: number; top: number }>, 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<string, { left: number; top: number }> = {}
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
}
+106
View File
@@ -0,0 +1,106 @@
import { TalkTopic } from '../api/client/types.gen'
import { kst } from '.'
/** 게임 8단계 그림을 바꾼다. 작은 것부터 큰 것 순서, 크기·색은 원래 단계 그대로 */
type GamePiece = { icon: string; name: string }
/**
* 기념일 꾸밈. 기간(KST, 양 끝 포함) 안에만 켜진다. 'MM-DD' 는 해마다, 'YYYY-MM-DD' 는 그해만(음력 기념일).
* 새 기념일: 여기에 한 줄 + TalkTopic(backend/common/enums.py) + 게임 그림(public/b/icons, lib.ts OWN) + 소품 그림(public/b/holiday, 투명 배경, b.css)
*/
export type Holiday = {
key: 'halloween' | 'pepero' | 'christmas' | 'chuseok'
name: string
ranges: readonly (readonly [string, string])[]
topic: TalkTopic
/** 글만 있는 사람 글 배경 (b.css b-bg-*) */
bg: string
game: readonly GamePiece[]
}
export const HOLIDAYS: readonly Holiday[] = [
{
key: 'halloween',
name: '할로윈',
ranges: [['10-30', '11-01']],
topic: TalkTopic.HALLOWEEN,
bg: 'night',
game: [
{ icon: 'candy', name: '사탕' },
{ icon: 'lollipop', name: '막대사탕' },
{ icon: 'spider', name: '거미' },
{ icon: 'spider_web', name: '거미줄' },
{ icon: 'bat', name: '박쥐' },
{ icon: 'ghost', name: '유령' },
{ icon: 'skull', name: '해골' },
{ icon: 'jack_o_lantern', name: '호박등' },
],
},
{
key: 'pepero',
name: '빼빼로데이',
ranges: [['11-11', '11-11']],
topic: TalkTopic.PEPERO,
bg: 'peach',
game: [
{ icon: 'pepero_choco', name: '초코' },
{ icon: 'pepero_almond', name: '아몬드' },
{ icon: 'pepero_strawberry', name: '딸기' },
{ icon: 'pepero_nude', name: '누드' },
{ icon: 'pepero_pair', name: '한 쌍' },
{ icon: 'pepero_bundle', name: '다발' },
{ icon: 'pepero_box', name: '한 상자' },
{ icon: 'pepero_basket', name: '바구니' },
],
},
{
key: 'christmas',
name: '크리스마스',
ranges: [['12-24', '12-25']],
topic: TalkTopic.CHRISTMAS,
bg: 'mint',
game: [
{ icon: 'xmas_candy_cane', name: '캔디케인' },
{ icon: 'xmas_ornament', name: '장식볼' },
{ icon: 'xmas_gingerbread', name: '진저쿠키' },
{ icon: 'xmas_santa_hat', name: '산타 모자' },
{ icon: 'xmas_stocking', name: '양말' },
{ icon: 'xmas_wreath', name: '리스' },
{ icon: 'xmas_santa', name: '산타' },
{ icon: 'christmas_tree', name: '트리' },
],
},
{
key: 'chuseok',
name: '추석',
ranges: [['2027-09-14', '2027-09-16']],
topic: TalkTopic.CHUSEOK,
bg: 'butter',
game: [
{ icon: 'chestnut', name: '밤' },
{ icon: 'pear', name: '배' },
{ icon: 'apple', name: '사과' },
{ icon: 'dango', name: '떡' },
{ icon: 'rabbit', name: '토끼' },
{ icon: 'maple', name: '단풍' },
{ icon: 'moon_viewing', name: '달맞이' },
{ icon: 'full_moon', name: '보름달' },
],
},
]
const pad = (n: number) => String(n).padStart(2, '0')
function inRange([from, to]: readonly [string, string], y: number, md: string) {
const day = from.length === 10 ? `${y}-${md}` : md
return from <= day && day <= to
}
/** 그날(KST) 켜진 기념일 */
export function holidayOn(now = new Date()): Holiday | undefined {
const { y, mo, d } = kst(now)
const md = `${pad(mo)}-${pad(d)}`
return HOLIDAYS.find((h) => h.ranges.some((r) => inRange(r, y, md)))
}
export const holidayByTopic = (t?: number) => HOLIDAYS.find((h) => h.topic === t)
+1
View File
@@ -5,6 +5,7 @@
"module": "esnext",
"moduleResolution": "bundler",
"verbatimModuleSyntax": true,
"resolveJsonModule": true,
"moduleDetection": "force",
"noEmit": true,
"skipLibCheck": true,