feat: 계절 지도 자리에 첫눈 지도·해돋이 지도 — 단풍 지도가 끝나면 첫눈 지도(~12/20, 지점 42곳 평년 첫눈 날짜 + 앞으로 7일 눈 예보, GET /v1/season/first-snow), 12/21부터 해돋이 지도(~2월, 명소 50곳 해 뜨는 시각, 12월엔 새해 첫날 기준). 오늘 탭 아이콘·피드 맨 앞 카드(foliage_post 좋아요·댓글 자리를 이어받음)·/first-snow·/sunrise 페이지·공유 이미지. 지도 확대·이동은 mapView.ts 로 꺼내 단풍 지도와 같이 씀 (GA first_snow_open·first_snow_spot·sunrise_open·sunrise_spot·sunrise_day)

This commit is contained in:
skkim committed 2026-11-20 11:18:54 +09:00
1 parent 4e69c4ac44
commit d7dfc1ba82
30 files changed
+1973 -255

No files matched your search

+4
View File
@@ -1,12 +1,14 @@
import { BrowserRouter, Route, Routes } from 'react-router'
import { BLayout } from './b/BLayout'
import { CloudMergePage } from './b/CloudMergePage'
import { FirstSnowPage } from './b/FirstSnowPage'
import { FoliagePage } from './b/FoliagePage'
import { SajuPage } from './b/SajuPage'
import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage'
import { ShortsPage } from './b/Shorts'
import { SkyPage } from './b/SkyPage'
import { SunrisePage } from './b/SunrisePage'
import { TalkPage } from './b/TalkPage'
import { TodayPage } from './b/TodayPage'
import { WeekPage } from './b/WeekPage'
@@ -24,6 +26,8 @@ export default function App() {
<Route path="week" element={<WeekPage />} />
<Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} />
<Route path="first-snow" element={<FirstSnowPage />} />
<Route path="sunrise" element={<SunrisePage />} />
<Route path="saju" element={<SajuPage />} />
<Route path="talk" element={<TalkPage />} />
<Route path="shorts/:id?" element={<ShortsPage />} />
+260
View File
@@ -0,0 +1,260 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { firstSnowHeadline, SNOW_DOT, SNOW_LABEL_INK, SNOW_MAP_IMG, SNOW_PAPER, SNOW_SHADOW, SNOW_STAGE, snowSoon, useFirstSnow, type SnowSpot, type SnowStage } from './firstSnow'
import { ICON_R, LABEL, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, md, placeLabels, placeProvinces, spread, useLabelSize, type Box, type Pt } from './foliage'
import { useMapView } from './mapView'
import { useSheet } from './sheetContext'
import { FirstSnowMapShare, FirstSnowSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Ic, StateBox, TAP44 } from './ui'
import { track } from '../lib/analytics'
const DOT_R = 4
// 눈 예보도 없고 대표 지점도 아닌 곳의 이름이 나오기 시작하는 배율(처음 화면 대비): 처음엔 차분하게
const LABEL_FROM = 2.2
const TAP_R = 24
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const GROUPS: [SnowStage, string][] = [
['soon', '눈 예보가 있는 곳'],
['before', '평년 첫눈이 다가오는 곳'],
['passed', '평년 첫눈이 지난 곳'],
]
const BADGE: Record<SnowStage, string> = { soon: 'bg-[#dcebff] text-[#1f5fae]', before: 'bg-(--chip) text-(--ink2)', passed: 'bg-(--chip) text-(--ink2)' }
/** 눈 오는 양을 말로: 1cm 가 안 되면 '조금' */
const amount = (cm: number | null) => (cm && cm >= 1 ? `${Math.round(cm)}cm 안팎` : '조금')
/** 지도·목록에 크게 적는 날짜: 눈 예보가 있으면 그날, 없으면 평년 첫눈 날짜 */
const day = (m: SnowSpot) => md(m.snowDate ?? m.normal)
// 눈 예보가 있는 곳은 눈송이, 나머지는 점(평년 첫눈 전은 하늘색, 지난 곳은 회색. 고르면 점을 크게)
function SnowMark({ m, big }: { m: SnowSpot; big?: boolean }) {
if (m.stage === 'soon') return <Ic name="snow" className={cx('relative', big ? 'size-8' : 'size-5', SNOW_SHADOW)} />
return <i className={cx('relative', SNOW_DOT[m.stage], big ? 'size-3.5' : 'size-[7px]')} />
}
function Marker({ p, sel }: { p: Pt<SnowSpot>; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 지점은 속이 빈 고리만: 옆 지점을 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<SnowMark m={p.m} big={sel && p.m.stage !== 'soon'} />
</span>
)
}
/** 첫눈 지도 페이지: 지점 42곳의 평년 첫눈 날짜와 앞으로 7일 눈 예보를 지도에서 확대해 보고 목록으로 고른다. 확대·이동은 mapView.ts */
export function FirstSnowPage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { today, spots, forecast, load, refetch } = useFirstSnow()
const [sel, setSel] = useState<string | null>(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<SnowSpot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
useEffect(() => track('first_snow_open', {}), [])
useEffect(() => {
if (sel) track('first_snow_spot', { spot_name: sel, from: 'page' })
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(vpRef, spots)
const ptsRef = useRef<Pt<SnowSpot>[]>([])
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
const { box, view, fit, zoomAt, focus } = useMapView(vpRef, spots, params.get('spot'), pickAt)
const pts = useMemo(
() => spread(spots.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: m.stage === 'soon' ? ICON_R : DOT_R }))),
[spots, view, box.W],
)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
// 고른 지점 > 눈 예보가 있는 곳 > 대표 지점 > 나머지(확대해야 나옴)
const rank = (m: SnowSpot) => (m.name === sel ? 0 : m.stage === 'soon' ? 1 : m.top ? 2 : 3)
const order = pts.filter((p) => rank(p.m) < 3 || ratio >= LABEL_FROM).sort((a, b) => rank(a.m) - rank(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
// 이름이 아직 안 나오는 작은 점은 이름표가 덮어도 된다
return placeLabels(order, order, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => rank(p.m) < 3)
}, [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 chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: SnowSpot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(지점 하나면 그 지점 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: SnowSpot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 첫눈` : '첫눈 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const title = firstSnowHeadline(spots, forecast)
const soon = snowSoon(spots)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="snow" className="size-4" />
첫눈 지도 · {md(today)}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{title}</h2>
</div>
{spots.length > 0 && (
<button type="button" onClick={() => share()} aria-label="첫눈 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
)}
</div>
<div ref={vpRef} className={cx('b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden select-none', SNOW_PAPER)}>
{spots.length > 0 && <img src={MAP_SRC} alt="첫눈 지도" draggable={false} className={SNOW_MAP_IMG} style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />}
{spots.length > 0 &&
provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.stage === 'soon') - Number(b.m.stage === 'soon')).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.stage === 'soon' ? SNOW_LABEL_INK : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{day(m)}</span>
</button>
))}
{spots.length > 0 && (
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
)}
{!spots.length && <StateBox load={load} onRetry={() => refetch()} empty="첫눈 정보가 아직 없어요." className="absolute inset-x-3 top-1/2 -translate-y-1/2" />}
</div>
{/* 고른 지점은 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<SnowMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className={cx('shrink-0 rounded-full px-1.5 py-px text-[11px] font-extrabold', BADGE[chosen.stage])}>{SNOW_STAGE[chosen.stage]}</span>
</p>
<p className="m-0 truncate text-[12px] font-bold text-(--ink3)">
평년 첫눈 {md(chosen.normal)}
{chosen.snowDate && ` · ${md(chosen.snowDate)} 눈 예보(${amount(chosen.snowCm)})`}
</p>
</div>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="snow" className={cx('size-4', SNOW_SHADOW)} />눈 예보 날짜
</span>
<span className="flex items-center gap-1">
<i className={cx(SNOW_DOT.before, 'size-[7px]')} />
평년 첫눈 날짜
</span>
<span className="flex items-center gap-1">
<i className={cx(SNOW_DOT.passed, 'size-[7px]')} />
평년 첫눈 지남
</span>
</div>
)}
<div className="px-4">
{GROUPS.map(([g, heading]) => {
const rows = g === 'soon' ? soon : spots.filter((m) => m.stage === g)
if (!rows.length) return null
return (
<section key={g} aria-label={heading} className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
{heading}
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{rows.length}곳</span>
</h3>
<ul className="m-0 list-none border-t border-(--line) p-0">
{rows.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(91_155_224/0.1)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<SnowMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {g === 'soon' ? `눈 ${amount(m.snowCm)} · 평년 첫눈 ${md(m.normal)}` : '평년 첫눈'}
</small>
</span>
<b className={cx('shrink-0 font-jua text-[18px] font-normal tabular-nums', g === 'soon' ? 'text-[#2f7fd6]' : 'text-(--ink2)')}>{day(m)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ul>
</section>
)
})}
<FirstSnowSpotShare spot={shareSpot} soon={soon} ref={spotShotRef} />
<FirstSnowMapShare title={title} today={today} soon={soon} spots={spots} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
평년 첫눈은 기상청 1991~2020년 평균이에요(춘천·강릉은 북춘천·북강릉 관측소). 눈 예보는 앞으로 7일을 보고, 실제 첫눈은 평년 날짜·예보와 다를 수 있어요
{!forecast && load === 'ready' ? ' · 지금은 눈 예보를 받지 못해 평년 날짜만 보여 드려요' : ''}
</p>
</div>
</div>
)
}
+13 -238
View File
@@ -1,20 +1,17 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, LABEL_INK, LAND_CX, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { useMapView } from './mapView'
import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
import { track } from '../lib/analytics'
type View = { s: number; tx: number; ty: number }
type Filter = 'all' | Kind
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]
@@ -53,14 +50,13 @@ function Marker({ p, sel }: { p: Pt; sel: boolean }) {
)
}
/** 단풍 지도 페이지: 명소 67곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
/** 단풍 지도 페이지: 명소 67곳을 지도에서 확대해 보고 목록으로 고른다. 확대·이동은 mapView.ts */
export function FoliagePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { today, spots } = useFoliage()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const linked = useRef(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<Spot | null>(null)
const [shareReq, setShareReq] = useState(0)
@@ -73,111 +69,24 @@ export function FoliagePage() {
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const [box, setBox] = useState({ W: 0, H: 0 })
const [view, setView] = useState<View>({ s: 1, tx: 0, ty: 0 })
const viewRef = useRef(view)
useLayoutEffect(() => {
viewRef.current = view
}, [view])
const size = useLabelSize(vpRef, spots)
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<View>(() => {
const { W, H } = box
if (!W) 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: View): View => {
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: View) => {
cancelAnimationFrame(anim.current)
setView(v)
}, [])
const animateTo = useCallback(
(to: View) => {
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],
)
useLayoutEffect(() => {
const el = vpRef.current
if (!el) return
const ro = new ResizeObserver(() => setBox({ W: el.clientWidth, H: el.clientHeight }))
ro.observe(el)
return () => ro.disconnect()
}, [])
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로
const started = useRef(false)
useEffect(() => {
if (!box.W) return
if (started.current) {
set(clamp(viewRef.current))
return
const ptsRef = useRef<Pt[]>([])
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
started.current = true
set(fit)
const m = spots.find((s) => s.name === linked.current)
if (m) focus(m)
}, [box, fit, spots, set, clamp, focus])
setSel((cur) => (best && best !== cur ? best : null))
}, [])
const { box, view, fit, zoomAt, focus } = useMapView(vpRef, spots, params.get('spot'), pickAt)
const pts = useMemo(() => {
const ratio = view.s / fit.s
const visible = shown.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] })))
}, [shown, view, box.W, fit.s, sel])
const ptsRef = useRef(pts)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
@@ -193,140 +102,6 @@ export function FoliagePage() {
[view, box.W, pts, labelAt, size],
)
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
// 손가락: 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대
useEffect(() => {
const el = vpRef.current
if (!el) return
let pinch: { d: number; x: number; y: number } | null = null
let one: { x: number; y: number; moved: boolean; scroll: boolean } | null = null
let lastTap = 0
const local = (t: { clientX: number; clientY: number }) => {
const r = el.getBoundingClientRect()
return { x: t.clientX - r.left, y: t.clientY - r.top }
}
const zoomed = () => viewRef.current.s > fit.s * 1.01
const onStart = (e: TouchEvent) => {
if ((e.target as HTMLElement).closest('button')) {
one = null
return
}
cancelAnimationFrame(anim.current)
if (e.touches.length === 2) {
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
one = null
} else if (e.touches.length === 1) {
one = { ...local(e.touches[0]), moved: false, scroll: false }
}
}
const onMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinch) {
e.preventDefault()
const [a, b] = [local(e.touches[0]), local(e.touches[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) / pinch.d))
const k = s / v.s
set(clamp({ s, tx: x - (pinch.x - v.tx) * k, ty: y - (pinch.y - v.ty) * k }))
pinch = { d, x, y }
return
}
if (e.touches.length !== 1 || !one) return
const p = local(e.touches[0])
const first = !one.moved
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
if (!zoomed() || one.scroll) return
const v = viewRef.current
const next = clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y })
// 첫 움직임이 세로인데 지도가 그쪽 끝에 닿아 더 못 가면 이번 손짓은 페이지 스크롤로 넘긴다
if (first && Math.abs(p.y - one.y) > Math.abs(p.x - one.x) && next.ty === v.ty) {
one.scroll = true
return
}
e.preventDefault()
set(next)
one = { ...p, moved: one.moved, scroll: false }
}
const onEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinch = null
if (e.touches.length || !one || one.moved) {
if (!e.touches.length) one = null
return
}
e.preventDefault()
const now = Date.now()
if (now - lastTap < 300) {
lastTap = 0
zoomAt(2, one.x, one.y, true)
} else {
lastTap = now
pickAt(one.x, one.y)
}
one = null
}
// 마우스: 끌어서 이동, 누르면 고르기, 두 번 누르면 확대, 트랙패드 오므리기(ctrl+휠)로 확대
let drag: { x: number; y: number; moved: boolean } | null = null
const onDown = (e: PointerEvent) => {
if (e.pointerType !== 'mouse' || (e.target as HTMLElement).closest('button')) return
cancelAnimationFrame(anim.current)
drag = { ...local(e), moved: false }
}
const onPMove = (e: PointerEvent) => {
if (!drag) return
const p = local(e)
if (Math.hypot(p.x - drag.x, p.y - drag.y) > 3) drag.moved = true
const v = viewRef.current
set(clamp({ s: v.s, tx: v.tx + p.x - drag.x, ty: v.ty + p.y - drag.y }))
drag = { ...p, moved: drag.moved }
}
const onUp = () => {
if (drag && !drag.moved) pickAt(drag.x, drag.y)
drag = null
}
const onDbl = (e: MouseEvent) => {
// +/− 를 빨리 두 번 누른 건 확대로 치지 않는다
if ((e.target as HTMLElement).closest('button')) return
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return
e.preventDefault()
const p = local(e)
zoomAt(Math.exp(-e.deltaY * 0.01), p.x, p.y)
}
el.addEventListener('touchstart', onStart, { passive: true })
el.addEventListener('touchmove', onMove, { passive: false })
el.addEventListener('touchend', onEnd, { passive: false })
el.addEventListener('pointerdown', onDown)
window.addEventListener('pointermove', onPMove)
window.addEventListener('pointerup', onUp)
el.addEventListener('dblclick', onDbl)
el.addEventListener('wheel', onWheel, { passive: false })
return () => {
el.removeEventListener('touchstart', onStart)
el.removeEventListener('touchmove', onMove)
el.removeEventListener('touchend', onEnd)
el.removeEventListener('pointerdown', onDown)
window.removeEventListener('pointermove', onPMove)
window.removeEventListener('pointerup', onUp)
el.removeEventListener('dblclick', onDbl)
el.removeEventListener('wheel', onWheel)
}
}, [fit, clamp, set, zoomAt, pickAt])
const chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: Spot) => {
setSel(m.name)
+248
View File
@@ -0,0 +1,248 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, md, placeLabels, placeProvinces, spread, useLabelSize, type Box, type Pt } from './foliage'
import { useMapView } from './mapView'
import { useSheet } from './sheetContext'
import { SunriseMapShare, SunriseSpotShare } from './shareCards'
import { clock, COAST, direction, dokdoRise, SUN_DOT, SUN_LABEL_INK, SUN_MAP_IMG, SUN_SHADOW, sunriseHeadline, useSunrise, type Coast, type SunSpot } from './sunrise'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
import { track } from '../lib/analytics'
type Filter = 'all' | Coast
const DOT_R = 4
// 대표 명소가 아닌 곳의 이름이 나오기 시작하는 배율(처음 화면 대비): 처음엔 대표 명소 이름만 보여 차분하게
const LABEL_FROM = 2.2
const TAP_R = 24
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const FILTERS: [Filter, string][] = [['all', '전체'], ...(Object.entries(COAST) as [Coast, string][])]
// 대표 명소는 해 아이콘, 나머지는 주황 점(고르면 점을 크게)
function SunMark({ m, big }: { m: SunSpot; big?: boolean }) {
if (m.top) return <Ic name="sun" className={cx('relative', big ? 'size-8' : 'size-5', SUN_SHADOW)} />
return <i className={cx('relative', SUN_DOT, big ? 'size-3.5' : 'size-[7px]')} />
}
function Marker({ p, sel }: { p: Pt<SunSpot>; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 명소는 속이 빈 고리만: 옆 명소를 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<SunMark m={p.m} big={sel && !p.m.top} />
</span>
)
}
/** 해돋이 지도 페이지: 명소 50곳의 해 뜨는 시각을 지도에서 확대해 보고 이른 순 목록으로 고른다. 확대·이동은 mapView.ts */
export function SunrisePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { days, day, setDay, spots } = useSunrise()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<SunSpot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.coast === filter), [spots, filter])
useEffect(() => track('sunrise_open', {}), [])
useEffect(() => {
if (sel) track('sunrise_spot', { spot_name: sel, from: 'page' })
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(vpRef, spots)
const ptsRef = useRef<Pt<SunSpot>[]>([])
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
const { box, view, fit, zoomAt, focus } = useMapView(vpRef, spots, params.get('spot'), pickAt)
const pts = useMemo(
() => spread(shown.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: m.top ? ICON_R : DOT_R }))),
[shown, view, box.W],
)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
// 고른 명소 > 대표 명소 > 나머지(확대해야 나옴), 같은 급이면 해가 이른 순(pts 는 이른 순)
const rank = (m: SunSpot) => (m.name === sel ? 0 : m.top ? 1 : 2)
const order = pts.filter((p) => p.m.name === sel || p.m.top || ratio >= LABEL_FROM).sort((a, b) => rank(a.m) - rank(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
// 이름이 아직 안 나오는 작은 점은 이름표가 덮어도 된다: 동해안처럼 점이 몰린 곳에서도 대표 명소 이름이 보이게
return placeLabels(order, order, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.top || 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 chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: SunSpot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(명소 하나면 그 명소 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: SunSpot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 해돋이` : '해돋이 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const pickDay = (key: typeof day.key) => {
setDay(key)
track('sunrise_day', { day: key })
}
const when = `${day.label} ${md(day.date)}`
const tops = spots.filter((m) => m.top)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="sun" className="size-4" />
해돋이 지도 · {when}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{sunriseHeadline(day, spots)}</h2>
</div>
<button type="button" onClick={() => share()} aria-label="해돋이 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
</div>
{days.length > 1 && <Chips label="날짜" items={days.map((d) => [d.key, `${d.label} ${md(d.date)}`] as const)} value={day.key} onChange={pickDay} />}
<div ref={vpRef} className="b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden bg-[#fff6ea] select-none">
<img src={MAP_SRC} alt="해돋이 지도" draggable={false} className={cx(SUN_MAP_IMG, 'max-w-none')} style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.top) - Number(b.m.top)).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.top ? SUN_LABEL_INK : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{clock(m.rise)}</span>
</button>
))}
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
</div>
{/* 고른 명소는 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<SunMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className="shrink-0 rounded-full bg-[#ffe8d2] px-1.5 py-px text-[11px] font-extrabold text-[#a34f12]">{COAST[chosen.coast]}</span>
</p>
<p className="m-0 flex gap-1 text-[12px] font-bold text-(--ink3)">
<span className="truncate">{chosen.region}</span>
<span className="shrink-0">
· {clock(chosen.dawn)}부터 밝아져요 · {direction(chosen.az)}쪽
</span>
</p>
</div>
<b className="shrink-0 font-jua text-[22px] font-normal text-(--orange) tabular-nums">{clock(chosen.rise)}</b>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="sun" className={cx('size-4', SUN_SHADOW)} />
대표 명소
</span>
<span className="flex items-center gap-1">
<i className={cx(SUN_DOT, 'size-[7px]')} />그 밖의 명소
</span>
<span className="text-(--ink3)">숫자는 해 뜨는 시각</span>
</div>
)}
<Chips label="바다·산" items={FILTERS} value={filter} onChange={setFilter} />
<div className="px-4">
<section aria-label="해가 먼저 뜨는 순서" className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
해가 먼저 뜨는 순서
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{shown.length}곳</span>
</h3>
<ol className="m-0 list-none border-t border-(--line) p-0">
{shown.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(255_122_69/0.08)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<SunMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {clock(m.dawn)}부터 밝아져요
</small>
</span>
<b className="shrink-0 font-jua text-[18px] font-normal text-(--orange) tabular-nums">{clock(m.rise)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ol>
</section>
<SunriseSpotShare spot={shareSpot} when={when} tops={tops} ref={spotShotRef} />
<SunriseMapShare title={sunriseHeadline(day, spots)} when={when} tops={tops} ranked={spots} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
해 뜨는 시각은 명소 위치로 계산한 값이에요(바다 높이 기준, 1분쯤 다를 수 있어요). 높은 산 위에서는 몇 분 더 일찍 보여요 · 우리나라에서 가장 먼저 뜨는 독도는 {clock(dokdoRise(day.date))}
</p>
</div>
</div>
)
}
+5 -1
View File
@@ -16,7 +16,9 @@ import {
import { cx } from '../lib/utils'
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
import { fall } from './lib'
import { FirstSnowCard } from './firstSnowMap'
import { FoliageCard } from './foliageMap'
import { SunriseCard } from './sunriseMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
import { MyGakRow } from './myGak'
@@ -645,8 +647,10 @@ export function TodayPage() {
{load !== 'loading' && !posts.length && (
<StateBox load="ready" empty={load === 'ready' ? '오늘 올라온 글이 아직 없어요.' : '글을 불러오지 못했어요.'} hold={<PostsSkel />} className="inset-x-3 top-3.5 bottom-auto" />
)}
{/* 단풍철엔 단풍 지도를 포스트 맨 앞에 */}
{/* 계절 지도 카드를 포스트 맨 앞에: 단풍 지도 → 첫눈 지도 → 해돋이 지도 순으로 한 번에 하나만. 좋아요·댓글 자리(foliage_post)는 같이 쓴다 */}
{load !== 'loading' && posts.length > 0 && <FoliageCard post={f?.foliage_post} />}
{load !== 'loading' && posts.length > 0 && <FirstSnowCard post={f?.foliage_post} />}
{load !== 'loading' && posts.length > 0 && <SunriseCard post={f?.foliage_post} />}
{posts.map((p, i) => {
const t = talkAt(i)
const ev = eventNo.get(p.post_id)
+31
View File
@@ -0,0 +1,31 @@
import { useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getFirstSnowOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { loadOf } from '@nalssigak/shared/lib'
import { firstSnowInSeason, firstSnowOn } from '@nalssigak/shared/lib/firstSnow'
import { foliageToday } from '@nalssigak/shared/lib/foliage'
// 단계·제목 계산은 shared/lib/firstSnow.ts. 지도 그림·이름표 배치는 단풍 지도 것을 같이 쓴다(foliage.ts). 여기는 웹 화면에 붙는 것만
export { firstSnowHeadline, firstSnowInSeason, SNOW_STAGE, snowNote, snowSoon } from '@nalssigak/shared/lib/firstSnow'
export type { SnowSpot, SnowStage } from '@nalssigak/shared/lib/firstSnow'
// 눈 예보는 서버가 3시간에 한 번 받는다. 화면은 30분 동안은 다시 묻지 않는다
const STALE_MS = 30 * 60_000
/** 지점 42곳의 평년 첫눈 날짜와 눈 예보(평년 첫눈이 이른 순). enabled 가 false 면 받지 않는다. 첫눈 지도철이 아니면 inSeason 이 false */
export function useFirstSnow(enabled = true) {
const [today] = useState(() => foliageToday())
const q = useQuery({ ...getFirstSnowOptions(), staleTime: STALE_MS, enabled })
const spots = useMemo(() => firstSnowOn(today, q.data?.spots ?? []), [today, q.data])
return { today, spots, forecast: !!q.data?.forecast, load: loadOf(q), refetch: q.refetch, inSeason: firstSnowInSeason(today) }
}
// 지도 그림은 단풍 지도와 같은 것. 색을 다 빼고 옅게 해서 눈 내린 땅처럼 보이게, 양옆 귀퉁이의 단풍잎 장식은 잘라 낸다
export const SNOW_MAP_IMG = 'pointer-events-none absolute max-w-none select-none mix-blend-multiply brightness-[1.25] saturate-0 opacity-70 [clip-path:inset(0_8%_0_14%)]'
// 지도 바탕: 차가운 흰색
export const SNOW_PAPER = 'bg-[#f3f6fb]'
// 눈 예보가 있는 곳의 이름표
export const SNOW_LABEL_INK = 'bg-[#ffffffeb] text-[#1f5fae]'
export const SNOW_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
// 평년 첫눈 전은 하늘색 점, 지난 곳은 회색 점
export const SNOW_DOT = { before: 'b-keep-bg rounded-full bg-[#5b9be0]/90', passed: 'b-keep-bg rounded-full bg-[#8f8a80]/60' }
+197
View File
@@ -0,0 +1,197 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { useCarousel } from './carousel'
import { firstSnowHeadline, firstSnowInSeason, SNOW_DOT, SNOW_LABEL_INK, SNOW_MAP_IMG, SNOW_PAPER, SNOW_SHADOW, snowNote, snowSoon, useFirstSnow } from './firstSnow'
import { ICON_R, LABEL, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, spread, useLabelSize } from './foliage'
import { PostFrame } from './Post'
import { useSheet } from './sheetContext'
import { FirstSnowSpotShare } from './shareCards'
import { CROP_IMG, cropXY } from './sunrise'
import { SendIcon } from './svg'
import { Ic } from './ui'
import { track } from '../lib/analytics'
const TAP_R = 24
const DOT_R = 4
const RANK_N = 7
/** 피드의 첫눈 지도 카드(단풍 지도가 끝나면 그 자리를 이어받고, 끝나면 해돋이 지도에 넘긴다): 1장은 눈 예보가 있는 곳과 대표 지점(누르면 카드 안에 정보), 2장은 눈 예보가 가까운 순위. '지도 크게 보기'로 첫눈 지도 페이지 */
export function FirstSnowCard({ post }: { post?: PostReaction | null }) {
const navigate = useNavigate()
const [season] = useState(() => firstSnowInSeason())
const { today, spots, forecast, inSeason } = useFirstSnow(season)
// 지도에는 눈 예보가 있는 곳과 대표 지점만: 카드에서는 차분하게
const shown = useMemo(() => spots.filter((m) => m.stage === 'soon' || m.top), [spots])
const mapRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(mapRef, shown)
const [W, setW] = useState(0)
const [picked, setPicked] = useState<string | null>(null)
const { open } = useSheet()
const spotShotRef = useRef<HTMLDivElement>(null)
const { ref: sliderRef, index } = useCarousel({ align: 'start' })
const ready = inSeason && spots.length > 0
useLayoutEffect(() => {
const el = mapRef.current
if (!el) return
const ro = new ResizeObserver(() => setW(el.clientWidth))
ro.observe(el)
return () => ro.disconnect()
}, [ready])
const pts = useMemo(
() =>
spread(
shown.map((m) => {
const at = cropXY(m.x, m.y)
return { m, x: at.x * W, y: at.y * W, r: m.stage === 'soon' ? ICON_R : DOT_R }
}),
),
[shown, W],
)
const labelAt = useMemo(() => {
// 눈 예보가 있는 곳의 이름을 먼저 놓는다
const order = [...pts].sort((a, b) => Number(b.m.stage === 'soon') - Number(a.m.stage === 'soon'))
return placeLabels(order, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true)
}, [pts, size, W])
const provs = useMemo(
() =>
placeProvinces(
PROVINCES.map((v) => {
const at = cropXY(v.x, v.y)
return { name: v.name, x: at.x * W, y: at.y * W }
}),
pts,
labelBoxes(labelAt, size),
),
[pts, W, labelAt, size],
)
useEffect(() => {
if (picked) track('first_snow_spot', { spot_name: picked, from: 'card' })
}, [picked])
if (!ready) return null
const go = (name?: string) => navigate(name ? `/first-snow?spot=${encodeURIComponent(name)}` : '/first-snow')
const toggle = (name: string) => setPicked(name === picked ? null : name)
// 표시가 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 지점을 고른다
const tapMap = (e: MouseEvent<HTMLDivElement>) => {
const r = e.currentTarget.getBoundingClientRect()
let best: string | null = null
let bestD = TAP_R
for (const p of pts) {
const d = Math.hypot(p.x - (e.clientX - r.left), p.y - (e.clientY - r.top))
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setPicked(best && best !== picked ? best : null)
}
const sel = shown.find((m) => m.name === picked)
const soon = snowSoon(spots)
// 2번째 장: 눈 예보가 가까운 순서. 눈 예보가 없으면 평년 첫눈이 가까운 순서(spots 는 평년 첫눈이 이른 순)
const ranked = (soon.length ? soon : spots.filter((m) => m.stage === 'before')).slice(0, RANK_N)
const caption = soon.length ? `눈 예보 ${soon.length}곳: ${soon.slice(0, 5).map((m) => m.name).join(' · ')}${soon.length > 5 ? ' 외' : ''}` : undefined
return (
<PostFrame title="첫눈 지도" account="첫눈 지도" avatar="snow" pinned={{ key: 'foliage_post', post }} caption={caption}>
<div className={cx('b-keep-bg relative px-4 pt-4 pb-3 text-[#28304a]', SNOW_PAPER)}>
<p className="m-0 text-[13px] font-extrabold opacity-75">첫눈 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{firstSnowHeadline(spots, forecast)}</p>
<div className="relative mt-1">
<span data-noshot aria-hidden="true" className="absolute top-0 right-0 z-[4] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white">
{index + 1}/2
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
{/* 그림의 빈 가장자리는 잘라 쓴다(CROP_IMG) */}
<div ref={mapRef} onClick={tapMap} className={cx('b-keep-bg relative mx-auto aspect-square w-full overflow-hidden', SNOW_PAPER)}>
<img src={MAP_SRC} alt="" className={SNOW_MAP_IMG} style={CROP_IMG} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{pts.map((p) => (
<span key={p.m.name} className="pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center" style={{ left: p.x, top: p.y }}>
{p.m.name === picked && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
{p.m.stage === 'soon' ? <Ic name="snow" className={cx('relative size-5', SNOW_SHADOW)} /> : <i className={cx('relative size-[7px]', SNOW_DOT[p.m.stage])} />}
</span>
))}
{shown.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 정보 보기`}
onClick={(e) => {
e.stopPropagation()
toggle(m.name)
}}
className={cx(LABEL, m.stage === 'soon' ? SNOW_LABEL_INK : 'bg-[#ffffffeb] text-[#5b6075]', 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{md(m.snowDate ?? m.normal)}</span>
</button>
))}
</div>
{/* 고른 지점 정보는 지도 밖, 범례 자리에: 지도 위 표시를 가리지 않게 */}
{sel ? (
<div className="b-keep-bg mt-2 flex items-center gap-3 rounded-[16px] bg-[#ffffff] px-3 py-2.5 shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<Ic name="snow" className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<b className="block truncate font-jua text-[18px] leading-tight font-normal">{sel.name}</b>
<span className="block truncate text-[12px] font-bold text-[#6b7189]">
평년 첫눈 {md(sel.normal)}
{sel.snowDate && ` · ${md(sel.snowDate)} 눈 예보`}
</span>
</div>
<button type="button" onClick={() => sel && open({ type: 'share', share: { title: `${sel.name} 첫눈`, slides: spotShotRef.current ? [spotShotRef.current] : [] } })} aria-label={`${sel.name} 보내기`} className="relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-[#28304a] [&_svg]:stroke-[1.9]">
<SendIcon />
</button>
<button type="button" onClick={() => go(sel.name)} className="b-keep-bg shrink-0 cursor-pointer rounded-full bg-[#28304a] px-3 py-1.5 text-[12.5px] font-extrabold text-[#ffffff]">
지도에서 보기 ›
</button>
</div>
) : (
<span className="mt-2 flex h-[52px] items-center gap-3 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="snow" className="size-4" />눈 예보 날짜
</span>
<span className="flex items-center gap-1">
<i className={cx(SNOW_DOT.before, 'size-[7px]')} />
평년 첫눈 날짜
</span>
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 grow-0 basis-full flex-col pl-1">
<p className="m-0 font-jua text-[20px] leading-tight">{soon.length ? '눈 예보가 있는 곳' : '평년 첫눈이 가까운 곳'}</p>
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">{soon.length ? '앞으로 7일, 눈 예보가 가까운 순서예요' : '평년 첫눈 날짜가 가까운 순서예요'}</p>
<ol className="m-0 mt-2 flex flex-1 list-none flex-col justify-between p-0">
{ranked.map((m, i) => (
<li key={m.name}>
<button type="button" onClick={() => go(m.name)} className="flex w-full cursor-pointer items-center gap-2.5 border-0 bg-transparent py-1.5 text-left">
<b className={cx('w-6 shrink-0 text-center font-jua text-[22px] font-normal', i < 3 ? 'text-[#2f7fd6]' : 'text-[#9aa3b5]')}>{i + 1}</b>
<Ic name="snow" className={cx('size-7 shrink-0', SNOW_SHADOW)} />
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-[#6b7189]">{m.region}</small>
</span>
<span className="shrink-0 text-[14px] font-extrabold tabular-nums">{snowNote(m)}</span>
</button>
</li>
))}
</ol>
</div>
</div>
</div>
</div>
<FirstSnowSpotShare spot={sel ?? null} soon={soon} ref={spotShotRef} />
<button type="button" onClick={() => go()} className="b-keep-bg mt-2 w-full cursor-pointer rounded-full bg-[#ffffff] py-2 text-[14px] font-extrabold text-[#28304a] shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
지도 크게 보기 ›
</button>
</div>
</PostFrame>
)
}
+242
View File
@@ -0,0 +1,242 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'
import { LAND_CX } from './foliage'
export type View = { s: number; tx: number; ty: number }
type Place = { name: string; x: number; y: number }
const MAX_ZOOM = 5
const FIT_TOP = 30
const FIT_BOTTOM = 14
/**
* 전국 지도 그림의 확대·이동 (단풍 지도·해돋이 지도 페이지가 같이 쓴다).
* 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대, 한 번 누르면 pickAt(누른 자리).
* places 는 처음 화면에 다 들어와야 하는 명소, linked 는 처음에 가운데로 데려갈 명소 이름(링크로 들어왔을 때)
*/
export function useMapView(vpRef: RefObject<HTMLDivElement | null>, places: Place[], linked: string | null, pickAt: (x: number, y: number) => void) {
const [box, setBox] = useState({ W: 0, H: 0 })
const [view, setView] = useState<View>({ s: 1, tx: 0, ty: 0 })
const viewRef = useRef(view)
useLayoutEffect(() => {
viewRef.current = view
}, [view])
const linkedRef = useRef(linked)
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<View>(() => {
const { W, H } = box
if (!W || !places.length) return { s: 1, tx: 0, ty: 0 }
const xs = places.map((m) => m.x)
const ys = places.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, places])
const clamp = useCallback(
(v: View): View => {
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: View) => {
cancelAnimationFrame(anim.current)
setView(v)
}, [])
const animateTo = useCallback(
(to: View) => {
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: { x: number; y: number }) => {
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],
)
useLayoutEffect(() => {
const el = vpRef.current
if (!el) return
const ro = new ResizeObserver(() => setBox({ W: el.clientWidth, H: el.clientHeight }))
ro.observe(el)
return () => ro.disconnect()
}, [vpRef])
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로
const started = useRef(false)
useEffect(() => {
// 명소를 API 로 받는 지도(첫눈)는 받을 때까지 기다린다
if (!box.W || !places.length) return
if (started.current) {
set(clamp(viewRef.current))
return
}
started.current = true
set(fit)
const m = places.find((s) => s.name === linkedRef.current)
if (m) focus(m)
}, [box, fit, places, set, clamp, focus])
useEffect(() => {
const el = vpRef.current
if (!el) return
let pinch: { d: number; x: number; y: number } | null = null
let one: { x: number; y: number; moved: boolean; scroll: boolean } | null = null
let lastTap = 0
const local = (t: { clientX: number; clientY: number }) => {
const r = el.getBoundingClientRect()
return { x: t.clientX - r.left, y: t.clientY - r.top }
}
const zoomed = () => viewRef.current.s > fit.s * 1.01
const onStart = (e: TouchEvent) => {
if ((e.target as HTMLElement).closest('button')) {
one = null
return
}
cancelAnimationFrame(anim.current)
if (e.touches.length === 2) {
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
one = null
} else if (e.touches.length === 1) {
one = { ...local(e.touches[0]), moved: false, scroll: false }
}
}
const onMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinch) {
e.preventDefault()
const [a, b] = [local(e.touches[0]), local(e.touches[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) / pinch.d))
const k = s / v.s
set(clamp({ s, tx: x - (pinch.x - v.tx) * k, ty: y - (pinch.y - v.ty) * k }))
pinch = { d, x, y }
return
}
if (e.touches.length !== 1 || !one) return
const p = local(e.touches[0])
const first = !one.moved
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
if (!zoomed() || one.scroll) return
const v = viewRef.current
const next = clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y })
// 첫 움직임이 세로인데 지도가 그쪽 끝에 닿아 더 못 가면 이번 손짓은 페이지 스크롤로 넘긴다
if (first && Math.abs(p.y - one.y) > Math.abs(p.x - one.x) && next.ty === v.ty) {
one.scroll = true
return
}
e.preventDefault()
set(next)
one = { ...p, moved: one.moved, scroll: false }
}
const onEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinch = null
if (e.touches.length || !one || one.moved) {
if (!e.touches.length) one = null
return
}
e.preventDefault()
const now = Date.now()
if (now - lastTap < 300) {
lastTap = 0
zoomAt(2, one.x, one.y, true)
} else {
lastTap = now
pickAt(one.x, one.y)
}
one = null
}
// 마우스: 끌어서 이동, 누르면 고르기, 두 번 누르면 확대, 트랙패드 오므리기(ctrl+휠)로 확대
let drag: { x: number; y: number; moved: boolean } | null = null
const onDown = (e: PointerEvent) => {
if (e.pointerType !== 'mouse' || (e.target as HTMLElement).closest('button')) return
cancelAnimationFrame(anim.current)
drag = { ...local(e), moved: false }
}
const onPMove = (e: PointerEvent) => {
if (!drag) return
const p = local(e)
if (Math.hypot(p.x - drag.x, p.y - drag.y) > 3) drag.moved = true
const v = viewRef.current
set(clamp({ s: v.s, tx: v.tx + p.x - drag.x, ty: v.ty + p.y - drag.y }))
drag = { ...p, moved: drag.moved }
}
const onUp = () => {
if (drag && !drag.moved) pickAt(drag.x, drag.y)
drag = null
}
const onDbl = (e: MouseEvent) => {
// +/− 를 빨리 두 번 누른 건 확대로 치지 않는다
if ((e.target as HTMLElement).closest('button')) return
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return
e.preventDefault()
const p = local(e)
zoomAt(Math.exp(-e.deltaY * 0.01), p.x, p.y)
}
el.addEventListener('touchstart', onStart, { passive: true })
el.addEventListener('touchmove', onMove, { passive: false })
el.addEventListener('touchend', onEnd, { passive: false })
el.addEventListener('pointerdown', onDown)
window.addEventListener('pointermove', onPMove)
window.addEventListener('pointerup', onUp)
el.addEventListener('dblclick', onDbl)
el.addEventListener('wheel', onWheel, { passive: false })
return () => {
el.removeEventListener('touchstart', onStart)
el.removeEventListener('touchmove', onMove)
el.removeEventListener('touchend', onEnd)
el.removeEventListener('pointerdown', onDown)
window.removeEventListener('pointermove', onPMove)
window.removeEventListener('pointerup', onUp)
el.removeEventListener('dblclick', onDbl)
el.removeEventListener('wheel', onWheel)
}
}, [vpRef, fit, clamp, set, zoomAt, pickAt])
return { box, view, fit, zoomAt, focus }
}
+163
View File
@@ -2,8 +2,10 @@ import type { Ref } from 'react'
import { createPortal } from 'react-dom'
import { cx } from '../lib/utils'
import type { TopIndex } from '@nalssigak/shared/api/client/types.gen'
import { SNOW_DOT, SNOW_MAP_IMG, SNOW_PAPER, SNOW_SHADOW, SNOW_STAGE, type SnowSpot } from './firstSnow'
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
import { MEDALS, type TimeKind } from '@nalssigak/shared/lib'
import { clock, COAST, CROP_IMG, cropXY, direction, SUN_MAP_IMG, SUN_SHADOW, type SunSpot } from './sunrise'
import { Ic } from './ui'
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
@@ -186,6 +188,167 @@ export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; p
)
}
/** 해돋이 명소 하나 공유: 그 명소를 가운데 둔 지도 조각(둘레 시·도 이름과 다른 대표 명소) 위에 큰 해, 아래에 이름·지역·해 뜨는 시각 */
export function SunriseSpotShare({ spot, when, tops, ref }: { spot: SunSpot | null; when: string; tops: SunSpot[]; ref: Ref<HTMLDivElement> }) {
if (!spot) return null
const near = tops.filter((m) => m.name !== spot.name)
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] text-[#28304a]">
<div className="relative flex-1 overflow-hidden">
{/* 명소가 가운데 오게 지도 그림을 키워 옮긴다 */}
<div className="absolute top-1/2 left-1/2 aspect-square w-[220%] bg-[#fff6ea]" style={{ transform: `translate(-${spot.x * 100}%, -${spot.y * 100}%)` }}>
<img src={MAP_SRC} alt="" className={cx(SUN_MAP_IMG, 'inset-0 size-full')} />
{PROVINCES.map((v) => (
<span key={v.name} className={cx(PROVINCE, 'text-[15px]')} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{near.map((m) => (
<Ic key={m.name} name="sun" className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', SUN_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<span className="absolute top-1/2 left-1/2 grid size-[92px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-[3px] border-[#28304a] bg-[#ffffff99]">
<Ic name="sun" className={cx('w-[60px]', SUN_SHADOW)} />
</span>
</div>
<div className="px-5 pt-3 pb-4">
<p className="m-0 flex items-center gap-2">
<b className="font-jua text-[34px] leading-tight font-normal">{spot.name}</b>
<span className="rounded-full bg-[#ffe8d2] px-2 py-0.5 text-[14px] font-extrabold text-[#a34f12]">{COAST[spot.coast]}</span>
</p>
<p className="m-0 mt-0.5 text-[15px] font-bold text-[#6b7189]">
{spot.region} · {clock(spot.dawn)}부터 밝아져요 · {direction(spot.az)}쪽
</p>
<p className="m-0 mt-2 font-jua text-[22px]">
{when} 해 뜨는 시각 <span className="text-[#e0621f]">{clock(spot.rise)}</span>
</p>
</div>
</div>
</Offscreen>
)
}
/** 해돋이 지도 전체 공유: 제목, 대표 명소에 해가 찍힌 지도, 해가 먼저 뜨는 곳 1~3위. ranked 는 이른 순 */
export function SunriseMapShare({ title, when, tops, ranked, ref }: { title: string; when: string; tops: SunSpot[]; ranked: SunSpot[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">해돋이 지도 · {when}</p>
<p className="m-0 font-jua text-[24px] leading-tight">{title}</p>
<div className="relative mx-auto mt-1 aspect-square w-[72%] overflow-hidden bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={SUN_MAP_IMG} style={CROP_IMG} />
{PROVINCES.map((v) => {
const at = cropXY(v.x, v.y)
return (
<span key={v.name} className={PROVINCE} style={{ left: `${at.x * 100}%`, top: `${at.y * 100}%` }}>
{v.name}
</span>
)
})}
{tops.map((m) => {
const at = cropXY(m.x, m.y)
return <Ic key={m.name} name="sun" className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', SUN_SHADOW)} style={{ left: `${at.x * 100}%`, top: `${at.y * 100}%` }} />
})}
</div>
<ol className="m-0 mt-auto grid list-none gap-1.5 p-0">
{ranked.slice(0, 3).map((m, i) => (
<li key={m.name} className="flex items-center gap-2.5 rounded-[14px] bg-[#ffffff] px-3 py-1.5">
<Ic name={MEDALS[i]} className="w-[22px] shrink-0" />
<b className="min-w-0 flex-1 truncate font-jua text-[17px] font-normal">{m.name}</b>
<span className="shrink-0 text-[13px] font-bold text-[#6b7189]">{m.region}</span>
<span className="shrink-0 font-jua text-[16px] text-[#e0621f] tabular-nums">{clock(m.rise)}</span>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
/** 첫눈 지점 하나 공유: 그 지점을 가운데 둔 지도 조각(둘레 시·도 이름과 눈 예보가 있는 다른 곳) 위에 큰 눈송이, 아래에 이름·평년 첫눈 날짜·눈 예보 */
export function FirstSnowSpotShare({ spot, soon, ref }: { spot: SnowSpot | null; soon: SnowSpot[]; ref: Ref<HTMLDivElement> }) {
if (!spot) return null
const near = soon.filter((m) => m.name !== spot.name)
return (
<Offscreen>
<div ref={ref} className={cx('flex aspect-[4/5] flex-col text-[#28304a]', SNOW_PAPER)}>
<div className="relative flex-1 overflow-hidden">
{/* 지점이 가운데 오게 지도 그림을 키워 옮긴다 */}
<div className={cx('absolute top-1/2 left-1/2 aspect-square w-[220%]', SNOW_PAPER)} style={{ transform: `translate(-${spot.x * 100}%, -${spot.y * 100}%)` }}>
<img src={MAP_SRC} alt="" className={cx(SNOW_MAP_IMG, 'inset-0 size-full')} />
{PROVINCES.map((v) => (
<span key={v.name} className={cx(PROVINCE, 'text-[15px]')} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{near.map((m) => (
<Ic key={m.name} name="snow" className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', SNOW_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<span className="absolute top-1/2 left-1/2 grid size-[92px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-[3px] border-[#28304a] bg-[#ffffff99]">
<Ic name="snow" className={cx('w-[60px]', SNOW_SHADOW)} />
</span>
</div>
<div className="px-5 pt-3 pb-4">
<p className="m-0 flex items-center gap-2">
<b className="font-jua text-[34px] leading-tight font-normal">{spot.name}</b>
<span className={cx('rounded-full px-2 py-0.5 text-[14px] font-extrabold', spot.stage === 'soon' ? 'bg-[#dcebff] text-[#1f5fae]' : 'bg-[#e6ebf3] text-[#5b6075]')}>{SNOW_STAGE[spot.stage]}</span>
</p>
<p className="m-0 mt-0.5 text-[15px] font-bold text-[#6b7189]">{spot.region}</p>
<p className="m-0 mt-2 font-jua text-[22px]">
평년 첫눈 {md(spot.normal)}
{spot.snowDate && <span className="text-[#2f7fd6]"> · {md(spot.snowDate)} 눈 예보</span>}
</p>
</div>
</div>
</Offscreen>
)
}
/** 첫눈 지도 전체 공유: 제목, 눈 예보가 있는 곳은 눈송이·나머지는 점이 찍힌 지도, 눈 예보가 가까운 곳(없으면 평년 첫눈이 가까운 곳) 1~3위. spots 는 평년 첫눈이 이른 순 */
export function FirstSnowMapShare({ title, today, soon, spots, ref }: { title: string; today: string; soon: SnowSpot[]; spots: SnowSpot[]; ref: Ref<HTMLDivElement> }) {
const rows = (soon.length ? soon : spots.filter((m) => m.stage === 'before')).slice(0, 3)
return (
<Offscreen>
<div ref={ref} className={cx('flex aspect-[4/5] flex-col px-4 pt-4 pb-3 text-[#28304a]', SNOW_PAPER)}>
<p className="m-0 text-[13px] font-extrabold opacity-75">첫눈 지도 · {md(today)}</p>
<p className="m-0 font-jua text-[24px] leading-tight">{title}</p>
<div className={cx('relative mx-auto mt-1 aspect-square w-[72%] overflow-hidden', SNOW_PAPER)}>
<img src={MAP_SRC} alt="" className={SNOW_MAP_IMG} style={CROP_IMG} />
{PROVINCES.map((v) => {
const at = cropXY(v.x, v.y)
return (
<span key={v.name} className={PROVINCE} style={{ left: `${at.x * 100}%`, top: `${at.y * 100}%` }}>
{v.name}
</span>
)
})}
{spots.map((m) => {
const at = cropXY(m.x, m.y)
const style = { left: `${at.x * 100}%`, top: `${at.y * 100}%` }
return m.stage === 'soon' ? (
<Ic key={m.name} name="snow" className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', SNOW_SHADOW)} style={style} />
) : (
<i key={m.name} className={cx('absolute size-[5px] -translate-x-1/2 -translate-y-1/2', SNOW_DOT[m.stage])} style={style} />
)
})}
</div>
<ol className="m-0 mt-auto grid list-none gap-1.5 p-0">
{rows.map((m) => (
<li key={m.name} className="flex items-center gap-2.5 rounded-[14px] bg-[#ffffff] px-3 py-1.5">
<Ic name="snow" className="w-[22px] shrink-0" />
<b className="min-w-0 flex-1 truncate font-jua text-[17px] font-normal">{m.name}</b>
<span className="shrink-0 text-[13px] font-bold text-[#6b7189]">{m.snowDate ? '눈 예보' : '평년 첫눈'}</span>
<span className="shrink-0 font-jua text-[16px] text-[#2f7fd6] tabular-nums">{md(m.snowDate ?? m.normal)}</span>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
/** 내 각 공유: 아이콘·이름·점수, 조건마다 막대와 실제 값. 로고·지역·날짜는 공유 틀이 그린다 */
export function MyGakShareCard({ name, icon, score, slot, rows, ref }: { name: string; icon: string; score?: number | null; slot?: string; rows: { axis: string; label: string; value: number; note: string }[]; ref: Ref<HTMLDivElement> }) {
return (
+30
View File
@@ -0,0 +1,30 @@
import { useMemo, useState } from 'react'
import { sunriseDays, sunriseInSeason, sunriseOn, type SunDayKey } from '@nalssigak/shared/lib/sunrise'
// 데이터·시각 계산은 shared/lib/sunrise.ts. 지도 그림·이름표 배치는 단풍 지도 것을 같이 쓴다(foliage.ts). 여기는 웹 화면에 붙는 것만
export { clock, COAST, direction, dokdoRise, sunriseHeadline } from '@nalssigak/shared/lib/sunrise'
export type { Coast, SunDay, SunDayKey, SunSpot } from '@nalssigak/shared/lib/sunrise'
/** 고를 수 있는 날(새해 첫날·오늘/내일), 고른 날의 명소 50곳과 해 뜨는 시각(이른 순). 해돋이철이 아니면 inSeason 이 false */
export function useSunrise() {
const [now] = useState(() => new Date())
const days = useMemo(() => sunriseDays(now), [now])
const [key, setDay] = useState<SunDayKey>(days[0].key)
const day = days.find((d) => d.key === key) ?? days[0]
const spots = useMemo(() => sunriseOn(day.date), [day.date])
return { days, day, setDay, spots, inSeason: sunriseInSeason(now) }
}
// 지도 그림은 단풍 지도와 같은 것. 가을 색을 거의 다 빼고 옅게 해서 겨울 새벽 땅처럼 보이게, 양옆 귀퉁이의 단풍잎 장식은 잘라 낸다
export const SUN_MAP_IMG = 'pointer-events-none absolute max-w-none select-none mix-blend-multiply brightness-[1.22] saturate-[.2] opacity-80 [clip-path:inset(0_8%_0_14%)]'
export const SUN_LABEL_INK = 'bg-[#ffffffeb] text-[#b4501a]'
export const SUN_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
// 대표 명소가 아닌 곳은 주황 점
export const SUN_DOT = 'b-keep-bg rounded-full bg-[#f08a3c]/90'
// 피드 카드·공유 이미지는 그림 전체를 쓰지 않고 이 범위(그림 안 0~1)만 잘라 쓴다: 빈 가장자리를 덜어 땅을 크게 보이게 (맨 북쪽 명소부터 제주까지는 들어온다)
const CROP = { x0: 0.04, y0: 0.08, s: 0.85 }
/** 그림 안 위치(0~1) → 잘라 낸 칸 안 위치(0~1) */
export const cropXY = (x: number, y: number) => ({ x: (x - CROP.x0) / CROP.s, y: (y - CROP.y0) / CROP.s })
/** 잘라 낸 칸(정사각형, overflow-hidden) 안에 지도 그림을 놓는 자리 */
export const CROP_IMG = { width: `${100 / CROP.s}%`, height: `${100 / CROP.s}%`, left: `${(-CROP.x0 / CROP.s) * 100}%`, top: `${(-CROP.y0 / CROP.s) * 100}%` }
+182
View File
@@ -0,0 +1,182 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useNavigate } from 'react-router'
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
import { cx } from '../lib/utils'
import { useCarousel } from './carousel'
import { ICON_R, LABEL, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, spread, useLabelSize } from './foliage'
import { PostFrame } from './Post'
import { useSheet } from './sheetContext'
import { SunriseSpotShare } from './shareCards'
import { clock, COAST, CROP_IMG, cropXY, SUN_LABEL_INK, SUN_MAP_IMG, SUN_SHADOW, sunriseHeadline, useSunrise } from './sunrise'
import { SendIcon } from './svg'
import { Ic } from './ui'
import { track } from '../lib/analytics'
const TAP_R = 24
const RANK_N = 7
/** 피드의 해돋이 지도 카드(해돋이철에 단풍 지도 카드 자리를 이어받는다): 1장은 대표 명소와 해 뜨는 시각(누르면 카드 안에 정보), 2장은 해가 먼저 뜨는 순위. '지도 크게 보기'로 해돋이 지도 페이지 */
export function SunriseCard({ post }: { post?: PostReaction | null }) {
const navigate = useNavigate()
const { day, spots, inSeason } = useSunrise()
const tops = useMemo(() => spots.filter((m) => m.top), [spots])
const mapRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(mapRef, tops)
const [W, setW] = useState(0)
const [picked, setPicked] = useState<string | null>(null)
const { open } = useSheet()
const spotShotRef = useRef<HTMLDivElement>(null)
const { ref: sliderRef, index } = useCarousel({ align: 'start' })
useLayoutEffect(() => {
const el = mapRef.current
if (!el) return
const ro = new ResizeObserver(() => setW(el.clientWidth))
ro.observe(el)
return () => ro.disconnect()
}, [inSeason])
const pts = useMemo(
() =>
spread(
tops.map((m) => {
const at = cropXY(m.x, m.y)
return { m, x: at.x * W, y: at.y * W, r: ICON_R }
}),
),
[tops, 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) => {
const at = cropXY(v.x, v.y)
return { name: v.name, x: at.x * W, y: at.y * W }
}),
pts,
labelBoxes(labelAt, size),
),
[pts, W, labelAt, size],
)
useEffect(() => {
if (picked) track('sunrise_spot', { spot_name: picked, from: 'card' })
}, [picked])
if (!inSeason) return null
const go = (name?: string) => navigate(name ? `/sunrise?spot=${encodeURIComponent(name)}` : '/sunrise')
const toggle = (name: string) => setPicked(name === picked ? null : name)
// 해 아이콘이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
const tapMap = (e: MouseEvent<HTMLDivElement>) => {
const r = e.currentTarget.getBoundingClientRect()
let best: string | null = null
let bestD = TAP_R
for (const p of pts) {
const d = Math.hypot(p.x - (e.clientX - r.left), p.y - (e.clientY - r.top))
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setPicked(best && best !== picked ? best : null)
}
const sel = tops.find((m) => m.name === picked)
const when = `${day.label} ${md(day.date)}`
// 2번째 장: 해가 먼저 뜨는 순서(spots 는 이른 순)
const ranked = spots.slice(0, RANK_N)
return (
<PostFrame title="해돋이 지도" account="해돋이 지도" avatar="sun" pinned={{ key: 'foliage_post', post }} caption={`가장 이른 곳: ${spots.slice(0, 3).map((m) => `${m.name} ${clock(m.rise)}`).join(' · ')}`}>
<div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">해돋이 지도 · {when}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{sunriseHeadline(day, spots)}</p>
<div className="relative mt-1">
<span data-noshot aria-hidden="true" className="absolute top-0 right-0 z-[4] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white">
{index + 1}/2
</span>
<div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
<div className="flex">
<div className="min-w-0 shrink-0 grow-0 basis-full">
{/* 그림의 빈 가장자리는 잘라 쓴다(CROP_IMG) */}
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full overflow-hidden bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={SUN_MAP_IMG} style={CROP_IMG} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{pts.map((p) => (
<span key={p.m.name} className="pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center" style={{ left: p.x, top: p.y }}>
{p.m.name === picked && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<Ic name="sun" className={cx('relative size-5', SUN_SHADOW)} />
</span>
))}
{tops.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 정보 보기`}
onClick={(e) => {
e.stopPropagation()
toggle(m.name)
}}
className={cx(LABEL, SUN_LABEL_INK, 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{clock(m.rise)}</span>
</button>
))}
</div>
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 해를 가리지 않게 */}
{sel ? (
<div className="b-keep-bg mt-2 flex items-center gap-3 rounded-[16px] bg-[#ffffff] px-3 py-2.5 shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<Ic name="sun" className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<b className="block truncate font-jua text-[18px] leading-tight font-normal">{sel.name}</b>
<span className="flex gap-1 text-[12px] font-bold text-[#6b7189]">
<span className="shrink-0">{COAST[sel.coast]}</span>
<span className="shrink-0">· 해 뜨는 시각 {clock(sel.rise)}</span>
</span>
</div>
<button type="button" onClick={() => sel && open({ type: 'share', share: { title: `${sel.name} 해돋이`, slides: spotShotRef.current ? [spotShotRef.current] : [] } })} aria-label={`${sel.name} 보내기`} className="relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-[#28304a] [&_svg]:stroke-[1.9]">
<SendIcon />
</button>
<button type="button" onClick={() => go(sel.name)} className="b-keep-bg shrink-0 cursor-pointer rounded-full bg-[#28304a] px-3 py-1.5 text-[12.5px] font-extrabold text-[#ffffff]">
지도에서 보기 ›
</button>
</div>
) : (
<span className="mt-2 flex h-[52px] items-center gap-1 text-[12.5px] font-bold">
<Ic name="sun" className="size-4" />
대표 명소의 해 뜨는 시각이에요
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 grow-0 basis-full flex-col pl-1">
<p className="m-0 font-jua text-[20px] leading-tight">해가 먼저 뜨는 곳</p>
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">{when} 해 뜨는 시각이 이른 순서예요</p>
<ol className="m-0 mt-2 flex flex-1 list-none flex-col justify-between p-0">
{ranked.map((m, i) => (
<li key={m.name}>
<button type="button" onClick={() => go(m.name)} className="flex w-full cursor-pointer items-center gap-2.5 border-0 bg-transparent py-1.5 text-left">
<b className={cx('w-6 shrink-0 text-center font-jua text-[22px] font-normal', i < 3 ? 'text-[#e0621f]' : 'text-[#9a8f80]')}>{i + 1}</b>
<Ic name="sun" className={cx('size-7 shrink-0', SUN_SHADOW)} />
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-[#6b7189]">{m.region}</small>
</span>
<span className="shrink-0 text-[14px] font-extrabold tabular-nums">{clock(m.rise)}</span>
</button>
</li>
))}
</ol>
</div>
</div>
</div>
</div>
<SunriseSpotShare spot={sel ?? null} when={when} tops={tops} ref={spotShotRef} />
<button type="button" onClick={() => go()} className="b-keep-bg mt-2 w-full cursor-pointer rounded-full bg-[#ffffff] py-2 text-[14px] font-extrabold text-[#28304a] shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
지도 크게 보기 ›
</button>
</div>
</PostFrame>
)
}
+8 -1
View File
@@ -1,10 +1,12 @@
import { type ReactNode } from 'react'
import { useState, type ReactNode } from 'react'
import { Link } from 'react-router'
import { track } from '../lib/analytics'
import { HIDDEN } from './features'
import { firstSnowInSeason } from './firstSnow'
import { useFoliage } from './foliage'
import { useTarotBadge } from './fortune'
import { sajuSeenToday } from './SajuPage'
import { useSunrise } from './sunrise'
import { useSheet } from './sheetContext'
import { Ic, Rail } from './ui'
@@ -20,6 +22,8 @@ export function TodayIcons() {
const { open } = useSheet()
const tarot = useTarotBadge()
const { inSeason } = useFoliage()
const [snowSeason] = useState(() => firstSnowInSeason())
const { inSeason: sunriseSeason } = useSunrise()
const items: Item[] = [
{
@@ -35,7 +39,10 @@ export function TodayIcons() {
},
{ key: 'saju', label: '날씨 사주', icon: 'yin_yang', badge: sajuSeenToday() ? null : <Dot />, to: '/saju' },
{ key: 'game', label: '날씨 게임', icon: 'game', to: '/game' },
// 계절 지도 칸: 단풍 지도 → 첫눈 지도 → 해돋이 지도 순으로 한 번에 하나만 나온다
...(inSeason ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' }] : []),
...(snowSeason ? [{ key: 'firstSnow', label: '첫눈 지도', icon: 'snow', to: '/first-snow' }] : []),
...(sunriseSeason ? [{ key: 'sunrise', label: '해돋이 지도', icon: 'sunset', to: '/sunrise' }] : []),
{ key: 'shorts', label: '쇼츠', icon: 'clapper', to: '/shorts' },
{ key: 'myGak', label: '내 각', icon: 'rabbit', onClick: () => document.getElementById(MY_GAK_ID)?.scrollIntoView({ behavior: 'smooth', block: 'start' }) },
{ key: 'talk', label: '동네 이야기', icon: 'speech', to: '/talk' },