feat: 단풍 지도 페이지(/foliage) — 카드는 절정만 잎 아이콘, 누르면 페이지에서 확대·이동·목록, 확대할수록 이름 더, 뒤로 가면 피드 위치 그대로
This commit is contained in:
1 parent
446af2e9b5
commit
d75144a6ac
6 files changed
+652
-211
No files matched your search
@@ -66,6 +66,9 @@
|
||||
| [ ] | '○○구 내일 날씨' 검색 태깅 — 스위치 뒤 내용은 눌러야 보여 구글이 읽는지 공식 문서로 확인 필요. 구 페이지(SEO)에 내일 기온·습도 넣는 안과 비교 | 10/21 회의 결정 | `backend/router/v1/seo/` |
|
||||
| [x] | **운영 DB 반영(10/21 배포 때 init.sql로 적용 확인)** — 댓글 표 `user_id` NULL 허용, `ip_hash`·`region_name` 칸, `idx_comment_ip` (init.sql에 추가, 로컬만 적용). 배포 전에 운영에 ALTER 실행 (운영 영향, 확인 받고) | 익명 댓글 | `backend/postgres-init/init.sql` |
|
||||
| [ ] | **[결정 필요]** 새 화면 문구 검토: '보냈어요. 링크도 복사해 뒀어요', '글쓰기는 로그인한 뒤에 할 수 있어요.', '오늘'/'내일', '내일 낮 날씨 점수', '내일은 ○○각!'/'내일은 쉬어 가요', '최저'/'최고'/'습도', 익명 이름 '마포구 익명', 단풍 지도 '단풍 전'/'첫 단풍'/'절정'/'단풍'/'은행', '가까운 예측 지점 날짜예요', '지금 절정 ○곳: … 외' | 화면 문구 규칙 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/Sheets.tsx` |
|
||||
| [ ] | 단풍 지도 페이지(`/foliage`) 검색 등록 — 사이트맵 추가, 미리 그린 HTML(제목·설명), 공식 문서로 확인 후 | 페이지 따로 만든 이유(공유·검색), 사용자 10/23 | `backend/services/seo_service.py`, `frontend/src/b/FoliagePage.tsx` |
|
||||
| [ ] | 단풍 지도 그림 고해상도로 다시(지금 1024px라 확대하면 흐림) — Codex | 단풍 지도 페이지 확대 | `frontend/public/foliage/korea-map.webp` |
|
||||
| [ ] | **[결정 필요]** 단풍 지도 페이지 문구: '단풍 절정'/'은행 절정', '지도 크게 보기 ›', '지금 절정'/'곧 절정'/'아직'/'절정 지남', '전체'/'단풍'/'은행', '절정 예상'/'가까운 지점 날짜', '링크를 복사했어요' | 화면 문구 규칙 | `frontend/src/b/FoliagePage.tsx`, `frontend/src/b/foliageMap.tsx` |
|
||||
| [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` |
|
||||
| [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | |
|
||||
|
||||
|
||||
@@ -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,34 @@ 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
|
||||
}
|
||||
// 피드가 다시 그려져 그 높이가 될 때까지 몇 프레임 기다리며 맞춘다
|
||||
let tries = 0
|
||||
let raf = 0
|
||||
const go = () => {
|
||||
window.scrollTo({ top })
|
||||
if (Math.abs(window.scrollY - top) > 2 && ++tries < 60) raf = requestAnimationFrame(go)
|
||||
}
|
||||
go()
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [pathname, key, navType])
|
||||
// 지금 보고 있는 탭을 다시 누르면 맨 위로
|
||||
const toTopIfHere = (to: string) => () => {
|
||||
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useNavigate, useSearchParams } from 'react-router'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ICON_R, KIND, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
|
||||
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 SEL_R = 18
|
||||
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
|
||||
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3)
|
||||
const LABEL_FROM = [1, 1.6, 1.6, 2.5]
|
||||
const TAP_R = 24
|
||||
const GROUPS: [Stage, string][] = [
|
||||
['peak', '지금 절정'],
|
||||
['first', '곧 절정'],
|
||||
['before', '아직'],
|
||||
['gone', '절정 지남'],
|
||||
]
|
||||
const FILTERS: [Filter, string][] = [
|
||||
['all', '전체'],
|
||||
['maple', '단풍'],
|
||||
['ginkgo', '은행'],
|
||||
]
|
||||
// 단계마다 잎 아이콘을 얼마나 흐리게: 절정만 또렷하게
|
||||
const LEAF_DIM: Record<Stage, string> = { peak: '', first: 'opacity-80', before: 'opacity-45 grayscale', gone: 'opacity-45 grayscale' }
|
||||
|
||||
function Marker({ p, sel }: { p: Pt; sel: boolean }) {
|
||||
const style = { left: p.x, top: p.y }
|
||||
if (p.m.stage === 'peak' || sel)
|
||||
return (
|
||||
<span className={cx('pointer-events-none absolute -translate-x-1/2 -translate-y-1/2', sel && 'z-[3] grid size-9 place-items-center rounded-full bg-white shadow-[0_2px_8px_rgb(40_48_74/0.3)] ring-2 ring-(--ink)')} style={style}>
|
||||
<Ic name={p.m.kind} className={cx(sel ? 'size-6' : 'size-5', !sel && LEAF_SHADOW, LEAF_DIM[p.m.stage])} />
|
||||
</span>
|
||||
)
|
||||
return <i className={cx('pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 rounded-full', p.m.stage === 'first' ? 'size-[7px] bg-[#d9772e]/85' : 'size-[5px] bg-[#8f8a80]/60')} style={style} />
|
||||
}
|
||||
|
||||
/** 단풍 지도 페이지: 명소 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 [copied, setCopied] = useState(false)
|
||||
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)]
|
||||
const s = Math.min(W / ((x1 - x0 + 0.14) * W), H / ((y1 - y0 + 0.1) * W))
|
||||
return { s, tx: W / 2 - ((x0 + x1) / 2) * W * s, ty: 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(() => 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.name === sel ? SEL_R : DOT_R[m.stage] }))), [shown, view, box.W, 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 }]
|
||||
if (sel) blocked.push({ l: 0, t: box.H - 110, r: box.W, b: box.H })
|
||||
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked)
|
||||
}, [pts, size, sel, view.s, fit.s, box])
|
||||
|
||||
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]
|
||||
}
|
||||
if (best) setSel(best)
|
||||
}, [])
|
||||
|
||||
// 손가락: 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대
|
||||
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 } | 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 }
|
||||
}
|
||||
}
|
||||
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])
|
||||
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
|
||||
if (!zoomed()) return
|
||||
e.preventDefault()
|
||||
const v = viewRef.current
|
||||
set(clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y }))
|
||||
one = { ...p, moved: one.moved }
|
||||
}
|
||||
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 = () => {
|
||||
const url = `${SITE_URL}/foliage`
|
||||
if (navigator.share) {
|
||||
navigator.share({ title: '단풍 지도 · 날씨각', text: headline(spots), url }).catch((e: unknown) => {
|
||||
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[foliage] share', e)
|
||||
})
|
||||
return
|
||||
}
|
||||
navigator.clipboard.writeText(url).then(
|
||||
() => setCopied(true),
|
||||
(e: unknown) => console.error('[foliage] copy', e),
|
||||
)
|
||||
}
|
||||
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
|
||||
const peakCount = spots.filter((m) => m.stage === 'peak').length
|
||||
|
||||
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('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 shadow-[0_4px_10px_rgb(40_48_74/0.08)] [&_svg]:size-5 [&_svg]:fill-none [&_svg]:stroke-(--ink) [&_svg]:stroke-[1.9]', TAP44)}>
|
||||
<SendIcon />
|
||||
</button>
|
||||
</div>
|
||||
{copied && <p className="m-0 px-4 pt-1 text-right text-[12.5px] font-bold text-(--ink2)">링크를 복사했어요</p>}
|
||||
|
||||
<div ref={vpRef} className="relative mt-2 h-[min(122vw,calc(100dvh-250px),560px)] min-h-[320px] 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 }} />
|
||||
{[...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) => (
|
||||
<span key={m.name} data-label={m.name} aria-hidden="true" className={cx(LABEL, 'pointer-events-none', m.stage === 'peak' ? LABEL_INK[m.kind] : 'text-(--ink2)', !labelAt[m.name] && 'invisible')} style={labelAt[m.name] ?? { left: 0, top: 0 }}>
|
||||
{m.name}
|
||||
</span>
|
||||
))}
|
||||
<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="grid size-9 cursor-pointer place-items-center rounded-full bg-white text-[20px] font-bold shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
|
||||
{t}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{chosen && (
|
||||
<div className="absolute inset-x-2.5 bottom-2.5 z-[4] flex items-center gap-3 rounded-[18px] bg-white px-3.5 py-3 shadow-[0_6px_18px_rgb(40_48_74/0.2)]">
|
||||
<Ic name={chosen.kind} className={cx('size-9 shrink-0', LEAF_DIM[chosen.stage])} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<b className="block truncate font-jua text-[19px] leading-tight font-normal">{chosen.name}</b>
|
||||
<small className="block truncate text-[12px] font-bold text-(--ink3)">
|
||||
{chosen.region} · {KIND[chosen.kind]}
|
||||
</small>
|
||||
{!chosen.own && <small className="block text-[11px] font-semibold text-(--ink3)">가까운 예측 지점 날짜예요</small>}
|
||||
</div>
|
||||
<div className="shrink-0 text-right tabular-nums">
|
||||
<b className={cx('block text-[13px] font-extrabold', chosen.stage === 'peak' ? LABEL_INK[chosen.kind] : 'text-(--ink2)')}>{STAGE[chosen.stage]}</b>
|
||||
<span className="text-[14px] font-extrabold">절정 예상 {md(chosen.peak)}</span>
|
||||
</div>
|
||||
<button type="button" onClick={() => setSel(null)} aria-label="닫기" className={cx('relative grid size-7 shrink-0 cursor-pointer place-items-center text-xl text-(--ink2)', TAP44)}>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 px-4 pt-2.5 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="size-[7px] rounded-full bg-[#d9772e]/85" />첫 단풍
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<i className="size-[5px] rounded-full bg-[#8f8a80]/60" />단풍 전
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Chips label="종류" items={FILTERS} value={filter} onChange={setFilter} />
|
||||
<div className="px-3 pt-1">
|
||||
{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}>
|
||||
<h3 className="m-0 px-1.5 pt-4 pb-1 text-[13px] font-extrabold text-(--ink3)">
|
||||
{title} {rows.length}
|
||||
</h3>
|
||||
<ul className="m-0 list-none overflow-hidden rounded-[20px] bg-white p-0 shadow-[inset_0_-4px_0_var(--shade)]">
|
||||
{rows.map((m) => (
|
||||
<li key={m.name} className="border-b border-(--line) last:border-0">
|
||||
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className={cx('flex w-full cursor-pointer items-center gap-3 px-3.5 py-2.5 text-left', m.name === sel && 'bg-[#fff1ec]')}>
|
||||
<Ic name={m.kind} className={cx('size-7 shrink-0', LEAF_DIM[m.stage])} />
|
||||
<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} · {KIND[m.kind]}
|
||||
</small>
|
||||
</span>
|
||||
<span className="shrink-0 text-right tabular-nums">
|
||||
<b className={cx('block text-[15px] font-extrabold', g === 'peak' && LABEL_INK[m.kind])}>{md(m.peak)}</b>
|
||||
<small className="text-[11px] font-semibold text-(--ink3)">{m.own ? '절정 예상' : '가까운 지점 날짜'}</small>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
})}
|
||||
<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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
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'
|
||||
}
|
||||
|
||||
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),
|
||||
x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size,
|
||||
y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size,
|
||||
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 type Pt = { m: Spot; x: number; y: number; r: number }
|
||||
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[] = []) {
|
||||
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
|
||||
const tries = [
|
||||
[p.r + 2, -s.h / 2],
|
||||
[-s.w - p.r - 2, -s.h / 2],
|
||||
[-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
|
||||
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
|
||||
}
|
||||
}
|
||||
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)]'
|
||||
export const LABEL = 'absolute rounded-[7px] bg-white/92 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: 'text-[#b5321f]', ginkgo: '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
|
||||
+40
-207
@@ -1,239 +1,72 @@
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import data from '../../seo/foliage_2026.json'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import { kst } from './lib'
|
||||
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, spread, useFoliage, useLabelSize } from './foliage'
|
||||
import { PostFrame } from './Post'
|
||||
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' | '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 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 [at, setAt] = useState<Record<string, { x: number; y: number }>>({})
|
||||
const [labelAt, setLabelAt] = useState<Record<string, { left: number; top: number }>>({})
|
||||
const size = useLabelSize(mapRef, peak)
|
||||
const [W, setW] = useState(0)
|
||||
|
||||
// 겹친 점은 서로 밀어 떼어 놓고, 이름표는 점 오른쪽·왼쪽·위·아래 순으로 놓아 보다 다른 절정 점·이름표와 겹치면 뺀다
|
||||
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)
|
||||
const el = mapRef.current
|
||||
if (!el) return
|
||||
const ro = new ResizeObserver(() => setW(el.clientWidth))
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [spots, named])
|
||||
}, [inSeason])
|
||||
|
||||
// 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지
|
||||
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'))
|
||||
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 }), [pts, size, W])
|
||||
|
||||
if (!inSeason) return null
|
||||
const go = (name?: string) => navigate(name ? `/foliage?spot=${encodeURIComponent(name)}` : '/foliage')
|
||||
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 role="link" tabIndex={0} onClick={() => go()} onKeyDown={(e) => e.key === 'Enter' && go()} aria-label="단풍 지도 크게 보기" className="relative cursor-pointer 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) => (
|
||||
<div ref={mapRef} className="relative mx-auto mt-1 aspect-square w-full">
|
||||
<img src={MAP_SRC} alt="" className={MAP_IMG} />
|
||||
{pts.map((p) => (
|
||||
<Ic key={p.m.name} name={p.m.kind} className={cx('pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: p.x, top: p.y }} />
|
||||
))}
|
||||
{peak.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)
|
||||
go(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',
|
||||
)}
|
||||
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>
|
||||
))}
|
||||
{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}
|
||||
<div className="mt-2 flex items-center justify-between gap-2">
|
||||
<span className="flex 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>
|
||||
<span className="rounded-full bg-white px-3 py-1.5 text-[13px] font-extrabold shadow-[inset_0_-3px_0_var(--shade)]">지도 크게 보기 ›</span>
|
||||
</div>
|
||||
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
|
||||
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요
|
||||
</p>
|
||||
</div>
|
||||
</PostFrame>
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user