chore: main 병합 — 단풍 지도 페이지·검수 반영
This commit is contained in:
commit
fdd2200ae2
9 files changed
+974
-100
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { BrowserRouter, Route, Routes } from 'react-router'
|
||||
import { BLayout } from './b/BLayout'
|
||||
import { FoliagePage } from './b/FoliagePage'
|
||||
import { GakPage } from './b/GakPage'
|
||||
import { SeasonPage } from './b/SeasonPage'
|
||||
import { SkyPage } from './b/SkyPage'
|
||||
@@ -18,6 +19,7 @@ export default function App() {
|
||||
<Route path="sky" element={<SkyPage />} />
|
||||
<Route path="week" element={<WeekPage />} />
|
||||
<Route path="season" element={<SeasonPage />} />
|
||||
<Route path="foliage" element={<FoliagePage />} />
|
||||
<Route path="*" element={<TodayPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { NavLink, Outlet, useLocation } from 'react-router'
|
||||
import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
|
||||
import { useIsFetching, useQuery } from '@tanstack/react-query'
|
||||
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
@@ -202,12 +202,41 @@ function FirstLoad() {
|
||||
)
|
||||
}
|
||||
|
||||
// 페이지마다 마지막 스크롤 위치: 뒤로 가기로 돌아오면 그 자리로
|
||||
const scrolled = new Map<string, number>()
|
||||
|
||||
function Shell() {
|
||||
const { pathname } = useLocation()
|
||||
const { pathname, key } = useLocation()
|
||||
const navType = useNavigationType()
|
||||
const { kind } = useSky()
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [pathname])
|
||||
const save = () => scrolled.set(key, window.scrollY)
|
||||
window.addEventListener('scroll', save, { passive: true })
|
||||
return () => window.removeEventListener('scroll', save)
|
||||
}, [key])
|
||||
useEffect(() => {
|
||||
const top = navType === 'POP' ? scrolled.get(key) : undefined
|
||||
if (top == null) {
|
||||
window.scrollTo({ top: 0 })
|
||||
return
|
||||
}
|
||||
// 피드가 다시 그려져 그 높이가 될 때까지 최대 3초 맞추고, 그 사이 사람이 화면을 만지면 멈춘다
|
||||
let tries = 0
|
||||
let raf = 0
|
||||
const stop = () => cancelAnimationFrame(raf)
|
||||
const go = () => {
|
||||
window.scrollTo({ top })
|
||||
if (Math.abs(window.scrollY - top) > 2 && ++tries < 180) raf = requestAnimationFrame(go)
|
||||
}
|
||||
go()
|
||||
window.addEventListener('touchstart', stop, { once: true, passive: true })
|
||||
window.addEventListener('wheel', stop, { once: true, passive: true })
|
||||
return () => {
|
||||
stop()
|
||||
window.removeEventListener('touchstart', stop)
|
||||
window.removeEventListener('wheel', stop)
|
||||
}
|
||||
}, [pathname, key, navType])
|
||||
// 지금 보고 있는 탭을 다시 누르면 맨 위로
|
||||
const toTopIfHere = (to: string) => () => {
|
||||
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
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, 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 { useSheet } from './sheetContext'
|
||||
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
|
||||
import { SendIcon } from './svg'
|
||||
import { Chips, Ic, TAP44 } from './ui'
|
||||
|
||||
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]
|
||||
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
|
||||
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 }
|
||||
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: [Stage, string][] = [
|
||||
['peak', '지금 절정'],
|
||||
['first', '곧 절정'],
|
||||
['before', '아직'],
|
||||
['gone', '절정 지남'],
|
||||
]
|
||||
const FILTERS: [Filter, string][] = [
|
||||
['all', '전체'],
|
||||
['maple', '단풍'],
|
||||
['ginkgo', '은행'],
|
||||
]
|
||||
|
||||
// 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(고르면 점을 크게)
|
||||
const DOT_CLASS: Record<Stage, string> = { peak: '', first: 'bg-[#d9772e]/85', before: 'bg-[#8f8a80]/60', gone: 'bg-[#8f8a80]/60' }
|
||||
|
||||
function StageMark({ m, big }: { m: Spot; big?: boolean }) {
|
||||
if (m.stage === 'peak') return <Ic name={m.kind} className={cx('relative', big ? 'size-8' : 'size-5', LEAF_SHADOW)} />
|
||||
return <i className={cx('b-keep-bg relative rounded-full', DOT_CLASS[m.stage], big ? 'size-3.5' : m.stage === 'first' ? 'size-[7px]' : 'size-[5px]')} />
|
||||
}
|
||||
|
||||
function Marker({ p, sel }: { p: Pt; 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]" />}
|
||||
<StageMark m={p.m} big={sel && p.m.stage !== 'peak'} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 단풍 지도 페이지: 명소 65곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
|
||||
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)
|
||||
const spotShotRef = useRef<HTMLDivElement>(null)
|
||||
const mapShotRef = useRef<HTMLDivElement>(null)
|
||||
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter])
|
||||
|
||||
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
|
||||
const s = Math.min(W / ((x1 - x0 + 0.14) * W), h / ((y1 - y0) * W))
|
||||
return { s, tx: W / 2 - ((x0 + x1) / 2) * 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
|
||||
}
|
||||
started.current = true
|
||||
set(fit)
|
||||
const m = spots.find((s) => s.name === linked.current)
|
||||
if (m) focus(m)
|
||||
}, [box, fit, spots, set, clamp, focus])
|
||||
|
||||
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])
|
||||
|
||||
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 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) => {
|
||||
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)
|
||||
const el = vpRef.current
|
||||
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
|
||||
focus(m)
|
||||
}
|
||||
// 보내기: 공유 창이 이미지(명소 하나면 그 명소 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
|
||||
const share = (m?: Spot) => {
|
||||
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 peakSpots = spots.filter((m) => m.stage === 'peak')
|
||||
const peakCount = peakSpots.length
|
||||
const ranked = rankNow(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="maple" className="size-4" />
|
||||
단풍 지도 · {md(today)}
|
||||
</p>
|
||||
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{headline(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>
|
||||
|
||||
<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(MAP_IMG, 'max-w-none')} style={{ inset: 'auto', 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.stage === 'peak') - Number(b.m.stage === 'peak')).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 === 'peak' ? LABEL_INK[m.kind] : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
|
||||
style={labelAt[m.name] ?? { left: 0, top: 0 }}
|
||||
>
|
||||
{m.name}
|
||||
</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">
|
||||
<StageMark 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', chosen.stage === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : chosen.stage === 'first' ? 'bg-[#ffe8d2] text-[#a34f12]' : 'bg-(--chip) text-(--ink2)')}>{STAGE[chosen.stage]}</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">· 절정 예상 {md(chosen.peak)}</span>
|
||||
</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="maple" className={cx('size-4', LEAF_SHADOW)} />
|
||||
단풍 절정
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Ic name="ginkgo" className={cx('size-4', LEAF_SHADOW)} />
|
||||
은행 절정
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<i className="b-keep-bg size-[7px] rounded-full bg-[#d9772e]/85" />첫 단풍
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<i className="b-keep-bg size-[5px] rounded-full bg-[#8f8a80]/60" />단풍 전
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Chips label="종류" items={FILTERS} value={filter} onChange={setFilter} />
|
||||
<div className="px-4">
|
||||
{GROUPS.map(([g, title]) => {
|
||||
const rows = shown.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak))
|
||||
if (!rows.length) return null
|
||||
return (
|
||||
<section key={g} aria-label={title} className="pt-5">
|
||||
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
|
||||
{title}
|
||||
<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(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">
|
||||
<StageMark 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} · {m.own ? '절정 예상' : '가까운 지점 날짜'}
|
||||
</small>
|
||||
</span>
|
||||
<b className={cx('shrink-0 font-jua text-[18px] font-normal tabular-nums', g === 'peak' ? 'text-(--orange)' : 'text-(--ink2)')}>{md(m.peak)}</b>
|
||||
</button>
|
||||
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
|
||||
<SendIcon />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
<FoliageSpotShare spot={shareSpot} peak={peakSpots} ref={spotShotRef} />
|
||||
<FoliageMapShare title={headline(spots)} peak={peakSpots} ranked={ranked} ref={mapShotRef} />
|
||||
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
|
||||
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요{peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -611,7 +611,8 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
|
||||
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] {
|
||||
color: #ffd0dc;
|
||||
}
|
||||
.b-app[data-t='night'] .text-\[\#28304a\] {
|
||||
/* b-keep-bg(밤에도 밝은 바탕 그대로) 안은 글자도 그대로 */
|
||||
.b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *) {
|
||||
color: var(--ink);
|
||||
}
|
||||
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) {
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
|
||||
import data from '../../seo/foliage_2026.json'
|
||||
import { kst } from './lib'
|
||||
|
||||
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 }
|
||||
|
||||
// 지도 그림(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 })
|
||||
|
||||
// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림
|
||||
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('·')
|
||||
|
||||
/** 오늘(한국 시각) 기준 명소 65곳과 단계. 단풍철이 아니면 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
|
||||
}
|
||||
|
||||
/** 이름표 크기를 재 둔다: host 안 data-label 이 붙은 요소의 폭·높이 (host 크기가 바뀌면 다시) */
|
||||
export function useLabelSize(host: RefObject<HTMLElement | null>, key: unknown) {
|
||||
const [size, setSize] = useState<Record<string, { w: number; h: number }>>({})
|
||||
useLayoutEffect(() => {
|
||||
const el = host.current
|
||||
if (!el) return
|
||||
const ro = new ResizeObserver(() => {
|
||||
const out: Record<string, { w: number; h: number }> = {}
|
||||
el.querySelectorAll<HTMLElement>('[data-label]').forEach((l) => {
|
||||
out[l.dataset.label ?? ''] = { w: l.offsetWidth, h: l.offsetHeight }
|
||||
})
|
||||
setSize(out)
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [host, key])
|
||||
return size
|
||||
}
|
||||
|
||||
export const LEAF_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
|
||||
// 밤 화면에서도 지도는 밝은 종이 그대로라 이름표도 흰 바탕 그대로(b-keep-bg)
|
||||
export const LABEL = "b-keep-bg absolute rounded-[7px] before:absolute before:-inset-x-1 before:-inset-y-2 before:content-[''] px-[5px] py-px text-[11.5px] leading-[1.35] font-extrabold whitespace-nowrap shadow-[0_1px_3px_rgb(40_48_74/0.18)]"
|
||||
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]'
|
||||
+145
-95
@@ -1,108 +1,158 @@
|
||||
import { useState } from 'react'
|
||||
import data from '../../seo/foliage_2026.json'
|
||||
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import { kst } from './lib'
|
||||
import { useCarousel } from './carousel'
|
||||
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage'
|
||||
import { PostFrame } from './Post'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { FoliageSpotShare } from './shareCards'
|
||||
import { SendIcon } from './svg'
|
||||
import { Ic } from './ui'
|
||||
|
||||
type Kind = 'maple' | 'ginkgo'
|
||||
type Spot = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
|
||||
type Stage = 'before' | 'first' | 'peak'
|
||||
const TAP_R = 24
|
||||
const RANK_N = 7
|
||||
|
||||
// 지도 그림(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 일 전부터 절정으로 본다
|
||||
const FIRST_DAYS = 14
|
||||
const PEAK_DAYS = 3
|
||||
const SEASON = { from: '09-20', to: '11-25' }
|
||||
const SEOUL = { lat: 37.566, lon: 126.978 }
|
||||
|
||||
const STAGE: Record<Stage, { label: string; icon: string }> = {
|
||||
before: { label: '단풍 전', icon: 'size-3 opacity-60 grayscale' },
|
||||
first: { label: '첫 단풍', icon: 'size-3.5' },
|
||||
peak: { label: '절정', icon: 'size-[18px]' },
|
||||
}
|
||||
const KIND: Record<Kind, { label: string; icon: string }> = {
|
||||
maple: { label: '단풍', icon: 'maple' },
|
||||
ginkgo: { label: '은행', icon: 'ginkgo' },
|
||||
}
|
||||
|
||||
const pos = (m: Spot) => ({
|
||||
left: `${((MAP.ox + (m.lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size) * 100}%`,
|
||||
top: `${((MAP.oy + (MAP.lat1 - m.lat) * MAP.s) / MAP.size) * 100}%`,
|
||||
})
|
||||
|
||||
const DAY = 86_400_000
|
||||
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
|
||||
|
||||
function stage(m: Spot, today: string): Stage {
|
||||
const d = days(today, m.peak)
|
||||
if (d <= PEAK_DAYS) return 'peak'
|
||||
return d <= FIRST_DAYS ? 'first' : 'before'
|
||||
}
|
||||
|
||||
const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
|
||||
|
||||
/** 단풍철에만 나오는 단풍 지도 카드. 산마다 절정 예측일로 지금 절정·곧·아직·지남을 점으로 */
|
||||
/** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */
|
||||
export function FoliageCard() {
|
||||
const [now] = useState(() => new Date())
|
||||
const t = kst(now)
|
||||
const today = `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
|
||||
const navigate = useNavigate()
|
||||
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 mapRef = useRef<HTMLDivElement>(null)
|
||||
const size = useLabelSize(mapRef, peak)
|
||||
const [W, setW] = useState(0)
|
||||
const [picked, setPicked] = useState<string | null>(null)
|
||||
const mmdd = today.slice(5)
|
||||
if (mmdd < SEASON.from || mmdd > SEASON.to) return null
|
||||
const spots = (data.spots as Spot[]).map((m) => ({ ...m, stage: stage(m, today) }))
|
||||
const peakNow = spots.filter((m) => m.stage === 'peak').map((m) => m.name)
|
||||
// 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 단풍 예측 산으로
|
||||
const forecast = spots.filter((m) => m.kind === 'maple' && m.basis.startsWith('산림청'))
|
||||
const seoul = forecast.reduce((a, b) => (Math.hypot(b.lat - SEOUL.lat, b.lon - SEOUL.lon) < Math.hypot(a.lat - SEOUL.lat, a.lon - SEOUL.lon) ? b : a))
|
||||
const sel = spots.find((m) => m.name === picked)
|
||||
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(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])
|
||||
|
||||
if (!inSeason) return null
|
||||
const go = (name?: string) => navigate(name ? `/foliage?spot=${encodeURIComponent(name)}` : '/foliage')
|
||||
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 = peak.find((m) => m.name === picked)
|
||||
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
|
||||
const ranked = rankNow(spots).slice(0, RANK_N)
|
||||
return (
|
||||
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peakNow.length ? `지금 절정 ${peakNow.length}곳: ${peakNow.slice(0, 5).join(' · ')}${peakNow.length > 5 ? ' 외' : ''}` : undefined}>
|
||||
<div className="relative bg-[#fff6ea] px-4 pt-4 pb-3">
|
||||
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}>
|
||||
<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">단풍 지도 · {md(today)}</p>
|
||||
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">서울 근교 {seoul.name} 절정 예상 {md(seoul.peak)}</p>
|
||||
<div className="relative mx-auto mt-1 aspect-square w-full">
|
||||
<img src="/foliage/korea-map.webp" alt="단풍 지도" className="absolute inset-0 size-full" />
|
||||
{spots.map((m) => (
|
||||
<button
|
||||
key={m.name}
|
||||
type="button"
|
||||
onClick={() => setPicked(m.name === picked ? null : m.name)}
|
||||
aria-label={`${m.name} ${KIND[m.kind].label} ${STAGE[m.stage].label}, 절정 예상 ${md(m.peak)}`}
|
||||
className={cx('absolute grid -translate-x-1/2 -translate-y-1/2 cursor-pointer place-items-center p-0.5', m.name === picked && 'z-[2] scale-150')}
|
||||
style={pos(m)}
|
||||
>
|
||||
<Ic name={KIND[m.kind].icon} className={cx('drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.4)]', STAGE[m.stage].icon)} />
|
||||
</button>
|
||||
))}
|
||||
{sel && (
|
||||
<p className="absolute right-0 bottom-0 z-[3] m-0 max-w-[75%] rounded-[14px] bg-white/95 px-3 py-2 text-[13px] font-bold shadow-[0_4px_12px_rgb(40_48_74/0.15)]">
|
||||
<b className="font-jua text-[16px] font-normal">{sel.name}</b> {sel.region}
|
||||
<br />
|
||||
{KIND[sel.kind].label} {STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)}
|
||||
{!sel.basis.startsWith('산림청') && <small className="block text-[11px] font-semibold text-(--ink3)">가까운 예측 지점 날짜예요</small>}
|
||||
</p>
|
||||
)}
|
||||
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">{headline(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">
|
||||
<div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full bg-[#fff6ea]">
|
||||
<img src={MAP_SRC} alt="" className={MAP_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={p.m.kind} className={cx('relative size-5', LEAF_SHADOW)} />
|
||||
</span>
|
||||
))}
|
||||
{peak.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, LABEL_INK[m.kind], 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
|
||||
style={labelAt[m.name] ?? { left: 0, top: 0 }}
|
||||
>
|
||||
{m.name}
|
||||
</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={sel.kind} 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">{sel.region.split(' ')[0]}</span>
|
||||
<span className="shrink-0">· 절정 예상 {md(sel.peak)}</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-3 text-[12.5px] font-bold">
|
||||
<span className="flex items-center gap-1">
|
||||
<Ic name="maple" className="size-4" />
|
||||
단풍 절정
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Ic name="ginkgo" className="size-4" />
|
||||
은행 절정
|
||||
</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">지금 가기 좋은 곳</p>
|
||||
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">절정 예상일이 오늘과 가까운 순서예요</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-[#b5321f]' : 'text-[#9a8f80]')}>{i + 1}</b>
|
||||
<Ic name={m.kind} className={cx('size-7 shrink-0', LEAF_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">{md(m.peak)}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
|
||||
{(Object.keys(KIND) as Kind[]).map((k) => (
|
||||
<span key={k} className="flex items-center gap-1">
|
||||
<Ic name={KIND[k].icon} className="size-4" />
|
||||
{KIND[k].label}
|
||||
</span>
|
||||
))}
|
||||
<span className="opacity-30" aria-hidden="true">|</span>
|
||||
{(Object.keys(STAGE) as Stage[]).map((st) => (
|
||||
<span key={st} className="flex items-center gap-1">
|
||||
<Ic name="maple" className={cx('size-4', STAGE[st].icon)} />
|
||||
{STAGE[st].label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
|
||||
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요
|
||||
</p>
|
||||
<FoliageSpotShare spot={sel ?? null} peak={peak} 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>
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Ref } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { cx } from '../lib/utils'
|
||||
import type { TopIndex } from '../api/client/types.gen'
|
||||
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
|
||||
import { MEDALS, type TimeKind } from './lib'
|
||||
import { Ic } from './ui'
|
||||
|
||||
@@ -114,3 +115,73 @@ export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title:
|
||||
</Offscreen>
|
||||
)
|
||||
}
|
||||
|
||||
/** 단풍 명소 하나 공유: 그 명소를 가운데 둔 지도 조각(둘레 시·도 이름과 다른 절정 잎) 위에 큰 잎, 아래에 이름·지역·절정 예상일 */
|
||||
export function FoliageSpotShare({ spot, peak, ref }: { spot: Spot | null; peak: Spot[]; ref: Ref<HTMLDivElement> }) {
|
||||
if (!spot) return null
|
||||
const near = peak.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">
|
||||
{/* 명소가 가운데 오게 지도 그림을 3배로 키워 옮긴다 */}
|
||||
<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={MAP_IMG} />
|
||||
{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={m.kind} className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', LEAF_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={spot.kind} className={cx('w-[60px]', LEAF_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 === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : 'bg-[#efe6d8] text-[#5b6075]')}>{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.peak)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</Offscreen>
|
||||
)
|
||||
}
|
||||
|
||||
/** 단풍 지도 전체 공유: 지금 절정 제목, 절정 잎만 찍힌 지도, 가기 좋은 곳 1~3위 */
|
||||
export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; peak: Spot[]; ranked: Spot[]; 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 font-jua text-[24px] leading-tight">{title}</p>
|
||||
<div className="relative mx-auto mt-1 aspect-square w-[78%] bg-[#fff6ea]">
|
||||
<img src={MAP_SRC} alt="" className={MAP_IMG} />
|
||||
{PROVINCES.map((v) => (
|
||||
<span key={v.name} className={PROVINCE} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
|
||||
{v.name}
|
||||
</span>
|
||||
))}
|
||||
{peak.map((m) => (
|
||||
<Ic key={m.name} name={m.kind} className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.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" />
|
||||
<Ic name={m.kind} 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.split(' ')[0]}</span>
|
||||
<span className="shrink-0 font-jua text-[16px] text-[#b5321f]">{md(m.peak)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</Offscreen>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user