241 lines
11 KiB
TypeScript
241 lines
11 KiB
TypeScript
import { useLayoutEffect, useMemo, useRef, useState } from 'react'
|
|
import data from '../../seo/foliage_2026.json'
|
|
import { cx } from '../lib/utils'
|
|
import { kst } from './lib'
|
|
import { PostFrame } from './Post'
|
|
|
|
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' | 'gone'
|
|
|
|
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
|
|
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
|
|
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다
|
|
const FIRST_DAYS = 14
|
|
const PEAK_DAYS = 3
|
|
const PEAK_AFTER = 7
|
|
// 점 반지름(테두리 포함, px)과 점 사이 최소 틈, 지도를 눌렀을 때 가장 가까운 명소를 고르는 거리
|
|
const DOT_R: Record<Stage, number> = { before: 2.5, first: 3, peak: 7.5, gone: 2.5 }
|
|
const GAP = 1.5
|
|
const TAP_R = 22
|
|
|
|
const STAGE: Record<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '' }
|
|
const KIND: Record<Kind, string> = { maple: '단풍', ginkgo: '은행' }
|
|
// 절정만 테두리·그림자로 띄우고, 나머지는 테두리 없는 작은 점으로 지도 결에 묻는다
|
|
const DOT: Record<Stage, string> = {
|
|
before: 'size-[5px] bg-[#8f8a80]/55',
|
|
first: 'size-[6px] bg-[#d9772e]/80',
|
|
peak: 'size-[13px] border-2 border-white bg-[#e0442e] shadow-[0_1px_3px_rgb(40_48_74/0.35)]',
|
|
gone: 'size-[5px] bg-[#8f8a80]/55',
|
|
}
|
|
const LEGEND = [
|
|
{ label: '단풍 전', dot: DOT.before },
|
|
{ label: '첫 단풍', dot: DOT.first },
|
|
{ label: '절정 단풍', dot: DOT.peak },
|
|
{ label: '절정 은행', dot: cx(DOT.peak, 'bg-[#f2c230]') },
|
|
]
|
|
|
|
const xy = (m: Spot) => [(MAP.ox + (m.lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, (MAP.oy + (MAP.lat1 - m.lat) * MAP.s) / MAP.size]
|
|
|
|
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_AFTER) return 'gone'
|
|
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))}`
|
|
const province = (m: Spot) => m.region.split(' ')[0].split('·')
|
|
|
|
/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */
|
|
function headline(spots: (Spot & { stage: Stage })[]) {
|
|
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)}쯤`
|
|
}
|
|
|
|
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
|
|
|
|
/** 단풍철에만 나오는 단풍 지도 카드. 명소마다 절정 예측일로 단풍 전·첫 단풍·절정을 점 색으로, 절정 단풍은 이름까지 */
|
|
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 [picked, setPicked] = useState<string | null>(null)
|
|
const spots = useMemo(() => (data.spots as Spot[]).map((m) => ({ ...m, stage: stage(m, today) })), [today])
|
|
const named = useMemo(() => spots.filter((m) => m.kind === 'maple' && m.stage === 'peak').sort((a, b) => b.lat - a.lat), [spots])
|
|
const mapRef = useRef<HTMLDivElement>(null)
|
|
const [at, setAt] = useState<Record<string, { x: number; y: number }>>({})
|
|
const [labelAt, setLabelAt] = useState<Record<string, { left: number; top: number }>>({})
|
|
|
|
// 겹친 점은 서로 밀어 떼어 놓고, 이름표는 점 오른쪽·왼쪽·위·아래 순으로 놓아 보다 다른 절정 점·이름표와 겹치면 뺀다
|
|
useLayoutEffect(() => {
|
|
const box = mapRef.current
|
|
if (!box) return
|
|
const place = () => {
|
|
const W = box.clientWidth
|
|
const pts = spots.map((m) => {
|
|
const [x, y] = xy(m)
|
|
return { m, x: x * W, y: y * W, r: DOT_R[m.stage] }
|
|
})
|
|
for (let it = 0; it < 80; 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
|
|
}
|
|
const pos = Object.fromEntries(pts.map((p) => [p.m.name, { x: p.x, y: p.y }]))
|
|
const dot = (p: (typeof pts)[number]): Box => ({ l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r })
|
|
const taken = pts.filter((p) => p.m.stage === 'peak').map((p) => ({ name: p.m.name, box: dot(p) }))
|
|
const out: Record<string, { left: number; top: number }> = {}
|
|
box.querySelectorAll<HTMLElement>('[data-label]').forEach((el) => {
|
|
const p = pts.find((q) => q.m.name === el.dataset.label)
|
|
if (!p) return
|
|
const w = el.offsetWidth
|
|
const h = el.offsetHeight
|
|
const tries = [
|
|
[p.r + 2, -h / 2],
|
|
[-w - p.r - 2, -h / 2],
|
|
[-w / 2, -h - p.r - 1],
|
|
[-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 + w, b: p.y + dy + h }
|
|
if (r.l < 0 || r.t < 0 || r.r > W || r.b > W) continue
|
|
if (taken.some((o) => o.name !== p.m.name && overlaps(r, o.box))) continue
|
|
taken.push({ name: '', box: r })
|
|
out[p.m.name] = { left: r.l, top: r.t }
|
|
break
|
|
}
|
|
})
|
|
setAt(pos)
|
|
setLabelAt(out)
|
|
}
|
|
place()
|
|
const ro = new ResizeObserver(place)
|
|
ro.observe(box)
|
|
return () => ro.disconnect()
|
|
}, [spots, named])
|
|
|
|
// 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지
|
|
const peaks = spots.map((m) => m.peak).sort()
|
|
if (days(peaks[0], today) < -FIRST_DAYS || days(peaks[peaks.length - 1], today) > PEAK_AFTER) return null
|
|
const peakNow = spots.filter((m) => m.stage === 'peak').map((m) => m.name)
|
|
const sel = spots.find((m) => m.name === picked)
|
|
// 작은 점도 손가락으로 고를 수 있게 누른 자리에서 가장 가까운 명소를 연다
|
|
const tapNearest = (e: React.MouseEvent<HTMLDivElement>) => {
|
|
const r = e.currentTarget.getBoundingClientRect()
|
|
const x = e.clientX - r.left
|
|
const y = e.clientY - r.top
|
|
let best: string | null = null
|
|
let bestD = TAP_R
|
|
for (const m of spots) {
|
|
const [nx, ny] = xy(m)
|
|
const p = at[m.name] ?? { x: nx * r.width, y: ny * r.width }
|
|
const d = Math.hypot(p.x - x, p.y - y)
|
|
if (d < bestD) [best, bestD] = [m.name, d]
|
|
}
|
|
setPicked(best === picked ? null : best)
|
|
}
|
|
const order = [...spots].sort((a, b) => Number(a.stage === 'peak') - Number(b.stage === 'peak'))
|
|
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">
|
|
<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">{headline(spots)}</p>
|
|
<div ref={mapRef} onClick={tapNearest} className="relative mx-auto mt-1 aspect-square w-full">
|
|
<img src="/foliage/korea-map.webp" alt="단풍 지도" className="absolute inset-0 size-full mix-blend-multiply brightness-[1.08] saturate-[.3]" />
|
|
{order.map((m) => {
|
|
const [x, y] = xy(m)
|
|
const p = at[m.name]
|
|
return (
|
|
<button
|
|
key={m.name}
|
|
type="button"
|
|
onClick={(e) => {
|
|
e.stopPropagation()
|
|
setPicked(m.name === picked ? null : m.name)
|
|
}}
|
|
aria-label={`${m.name} ${KIND[m.kind]} ${STAGE[m.stage]}, 절정 예상 ${md(m.peak)}`}
|
|
className={cx(
|
|
'absolute -translate-x-1/2 -translate-y-1/2 cursor-pointer rounded-full border-0 p-0',
|
|
DOT[m.stage],
|
|
m.stage === 'peak' && m.kind === 'ginkgo' && 'bg-[#f2c230]',
|
|
m.name === picked && 'z-[2] scale-150 outline-2 outline-offset-1 outline-[#28304a]',
|
|
)}
|
|
style={p ? { left: p.x, top: p.y } : { left: `${x * 100}%`, top: `${y * 100}%` }}
|
|
/>
|
|
)
|
|
})}
|
|
{named.map((m) => (
|
|
<button
|
|
key={m.name}
|
|
type="button"
|
|
data-label={m.name}
|
|
tabIndex={-1}
|
|
aria-hidden="true"
|
|
onClick={(e) => {
|
|
e.stopPropagation()
|
|
setPicked(m.name === picked ? null : m.name)
|
|
}}
|
|
className={cx(
|
|
'absolute cursor-pointer rounded-[7px] border-0 bg-white/92 px-[5px] py-px text-[11.5px] leading-[1.35] font-extrabold whitespace-nowrap text-[#b5321f] shadow-[0_1px_3px_rgb(40_48_74/0.18)]',
|
|
!labelAt[m.name] && 'invisible',
|
|
)}
|
|
style={labelAt[m.name] ?? { left: 0, top: 0 }}
|
|
>
|
|
{m.name}
|
|
</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]} {STAGE[sel.stage] && `${STAGE[sel.stage]} · `}절정 예상 {md(sel.peak)}
|
|
{!sel.basis.startsWith('산림청') && <small className="block text-[11px] font-semibold text-(--ink3)">가까운 예측 지점 날짜예요</small>}
|
|
</p>
|
|
)}
|
|
</div>
|
|
<div className="mt-2 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
|
|
{LEGEND.map((l) => (
|
|
<span key={l.label} className="flex items-center gap-1">
|
|
<i className="grid size-[13px] place-items-center">
|
|
<i className={cx('block rounded-full', l.dot)} />
|
|
</i>
|
|
{l.label}
|
|
</span>
|
|
))}
|
|
</div>
|
|
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
|
|
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요
|
|
</p>
|
|
</div>
|
|
</PostFrame>
|
|
)
|
|
}
|