Files
o2o-weather/frontend/src/b/foliage.ts
T

214 lines
11 KiB
TypeScript

import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
import data from '../../seo/foliage_2026.json'
import { kst } from '@nalssigak/shared/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]'