Files
o2o-weather/frontend/src/b/SunrisePage.tsx
T

251 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, md, placeLabels, placeProvinces, spread, useLabelSize, type Box, type Pt } from './foliage'
import { useMapView } from './mapView'
import { useSheet } from './sheetContext'
import { SunriseMapShare, SunriseSpotShare } from './shareCards'
import { clock, COAST, direction, dokdoRise, SUN_DOT, SUN_LABEL_INK, SUN_MAP_IMG, SUN_PAPER, SUN_SHADOW, sunriseHeadline, useSunrise, type Coast, type SunSpot } from './sunrise'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
import { track } from '../lib/analytics'
type Filter = 'all' | Coast
const DOT_R = 4
// 대표 명소가 아닌 곳의 이름이 나오기 시작하는 배율(처음 화면 대비): 처음엔 대표 명소 이름만 보여 차분하게
const LABEL_FROM = 2.2
const TAP_R = 24
// 처음 화면에서 − 를 한 번 더 누를 수 있다: 울릉도·독도까지 전체가 보인다
const MIN_ZOOM = 1 / 1.6
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const FILTERS: [Filter, string][] = [['all', '전체'], ...(Object.entries(COAST) as [Coast, string][])]
// 대표 명소는 해 아이콘, 나머지는 주황 점(고르면 점을 크게)
function SunMark({ m, big }: { m: SunSpot; big?: boolean }) {
if (m.top) return <Ic name="sun" className={cx('relative', big ? 'size-8' : 'size-5', SUN_SHADOW)} />
return <i className={cx('relative', SUN_DOT, big ? 'size-3.5' : 'size-[7px]')} />
}
function Marker({ p, sel }: { p: Pt<SunSpot>; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 명소는 속이 빈 고리만: 옆 명소를 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<SunMark m={p.m} big={sel && !p.m.top} />
</span>
)
}
/** 해돋이 지도 페이지: 명소 50곳의 해 뜨는 시각을 지도에서 확대해 보고 이른 순 목록으로 고른다. 확대·이동은 mapView.ts */
export function SunrisePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { days, day, setDay, spots } = useSunrise()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<SunSpot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.coast === filter), [spots, filter])
useEffect(() => track('sunrise_open', {}), [])
useEffect(() => {
if (sel) track('sunrise_spot', { spot_name: sel, from: 'page' })
}, [sel])
const vpRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(vpRef, spots)
const ptsRef = useRef<Pt<SunSpot>[]>([])
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
const { box, view, fit, zoomAt, focus } = useMapView(vpRef, spots, params.get('spot'), pickAt, MIN_ZOOM)
const pts = useMemo(
() => spread(shown.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: m.top ? ICON_R : DOT_R }))),
[shown, view, box.W],
)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
// 고른 명소 > 대표 명소 > 나머지(확대해야 나옴), 같은 급이면 해가 이른 순(pts 는 이른 순)
const rank = (m: SunSpot) => (m.name === sel ? 0 : m.top ? 1 : 2)
const order = pts.filter((p) => p.m.name === sel || p.m.top || ratio >= LABEL_FROM).sort((a, b) => rank(a.m) - rank(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
// 이름이 아직 안 나오는 작은 점은 이름표가 덮어도 된다: 동해안처럼 점이 몰린 곳에서도 대표 명소 이름이 보이게
return placeLabels(order, order, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.top || p.m.name === sel)
}, [pts, size, sel, view.s, fit.s, box])
const provs = useMemo(
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
[view, box.W, pts, labelAt, size],
)
const chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: SunSpot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(명소 하나면 그 명소 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: SunSpot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 해돋이` : '해돋이 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const pickDay = (key: typeof day.key) => {
setDay(key)
track('sunrise_day', { day: key })
}
const when = `${day.label} ${md(day.date)}`
const tops = spots.filter((m) => m.top)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="sun" className="size-4" />
해돋이 지도 · {when}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{sunriseHeadline(day, spots)}</h2>
</div>
<button type="button" onClick={() => share()} aria-label="해돋이 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
</div>
{days.length > 1 && <Chips label="날짜" items={days.map((d) => [d.key, `${d.label} ${md(d.date)}`] as const)} value={day.key} onChange={pickDay} />}
<div ref={vpRef} className={cx('b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden select-none', SUN_PAPER)}>
<img src={MAP_SRC} alt="해돋이 지도" draggable={false} className={cx(SUN_MAP_IMG, 'max-w-none')} style={{ left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.top) - Number(b.m.top)).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.top ? SUN_LABEL_INK : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name} <span className="tabular-nums opacity-80">{clock(m.rise)}</span>
</button>
))}
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
</div>
{/* 고른 명소는 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<SunMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className="shrink-0 rounded-full bg-[#ffe8d2] px-1.5 py-px text-[11px] font-extrabold text-[#a34f12]">{COAST[chosen.coast]}</span>
</p>
<p className="m-0 flex gap-1 text-[12px] font-bold text-(--ink3)">
<span className="truncate">{chosen.region}</span>
<span className="shrink-0">
· {clock(chosen.dawn)}부터 밝아져요 · {direction(chosen.az)}쪽
</span>
</p>
</div>
<b className="shrink-0 font-jua text-[22px] font-normal text-(--orange) tabular-nums">{clock(chosen.rise)}</b>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="sun" className={cx('size-4', SUN_SHADOW)} />
대표 명소
</span>
<span className="flex items-center gap-1">
<i className={cx(SUN_DOT, 'size-[7px]')} />그 밖의 명소
</span>
<span className="text-(--ink3)">숫자는 해 뜨는 시각</span>
</div>
)}
<Chips label="바다·산" items={FILTERS} value={filter} onChange={setFilter} />
<div className="px-4">
<section aria-label="해가 먼저 뜨는 순서" className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
해가 먼저 뜨는 순서
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{shown.length}곳</span>
</h3>
<ol className="m-0 list-none border-t border-(--line) p-0">
{shown.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(255_122_69/0.08)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<SunMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {clock(m.dawn)}부터 밝아져요
</small>
</span>
<b className="shrink-0 font-jua text-[18px] font-normal text-(--orange) tabular-nums">{clock(m.rise)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ol>
</section>
<SunriseSpotShare spot={shareSpot} when={when} tops={tops} ref={spotShotRef} />
<SunriseMapShare title={sunriseHeadline(day, spots)} when={when} tops={tops} ranked={spots} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
해 뜨는 시각은 명소 위치로 계산한 값이에요(바다 높이 기준, 1분쯤 다를 수 있어요). 높은 산 위에서는 몇 분 더 일찍 보여요 · 우리나라에서 가장 먼저 뜨는 독도는 {clock(dokdoRise(day.date))}
</p>
</div>
</div>
)
}