chore: main 병합 — 로그인 없이 댓글·좋아요, 구글 로그인만, 동네 이야기·카드뉴스 등 (차단 표 user_block 하나로 합침, 익명 댓글도 신고 가능)
This commit is contained in:
commit
dba34675c8
408 files changed
+36377
-725
No files matched your search
@@ -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 '@nalssigak/shared/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' })
|
||||
@@ -232,7 +261,7 @@ function Shell() {
|
||||
{TABS.map((t) =>
|
||||
t.key === 'today' ? (
|
||||
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
|
||||
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}>
|
||||
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') || pathname.startsWith('/tomorrow/') ? 'text-(--orange)' : 'text-(--ink3)')}>
|
||||
<span className="b-keep-bg grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
|
||||
<TabIcon name={t.key} className="size-[30px]" />
|
||||
</span>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
+115
-12
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react'
|
||||
import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode, type RefObject } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type ImageSlide, type PlanSlide, type PostData, type PostReaction, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { API_BASE_URL } from '../api/setup'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, clockShort } from '@nalssigak/shared/lib'
|
||||
import { fall } from './lib'
|
||||
@@ -8,7 +9,7 @@ import type { SlideBg } from '@nalssigak/shared/lib/types'
|
||||
import { deg } from '@nalssigak/shared/lib/weatherText'
|
||||
import { useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
|
||||
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { useAuth } from './authContext'
|
||||
import { usePinnedLike, type PinnedKey } from './pinnedLike'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||
import { useCarousel } from './carousel'
|
||||
@@ -30,9 +31,15 @@ const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||
[PostType.DAY_TRIP]: ['당일치기', 'picnic'],
|
||||
[PostType.MOON]: ['오늘 밤 달', 'moon'],
|
||||
[PostType.UV]: ['자외선', 'glasses'],
|
||||
[PostType.HERO]: ['오늘 날씨', 'sun'],
|
||||
[PostType.TODAY_GAK]: ['오늘의 각', 'rabbit'],
|
||||
[PostType.FOLIAGE]: ['단풍 지도', 'maple'],
|
||||
[PostType.EVENTS_BAND]: ['이번 주 가까운 행사', 'fireworks'],
|
||||
[PostType.SEASON_BAND]: ['이번 주 계절 이야기', 'fallen_leaf'],
|
||||
[PostType.CARD]: ['날씨각 카드', 'stars'],
|
||||
}
|
||||
|
||||
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide
|
||||
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide | PlanSlide | ImageSlide
|
||||
|
||||
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac']
|
||||
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach', moon: 'lilac', glasses: 'butter' }
|
||||
@@ -44,6 +51,7 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
|
||||
if (slide.kind === 'week') return 'mint'
|
||||
if (slide.kind === 'plan') return slide.eyebrow.startsWith('일') ? 'peach' : 'butter'
|
||||
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
|
||||
if (slide.kind === 'image') return 'sky'
|
||||
if (post.post_type === PostType.EVENT) return 'night'
|
||||
if (post.post_type === PostType.TIP) return 'sky'
|
||||
if (post.post_type === PostType.AIR) return slide.icon === 'vent' ? 'mint' : 'lilac'
|
||||
@@ -53,6 +61,22 @@ function slideBg(post: PostData, slide: Slide): SlideBg {
|
||||
|
||||
const DARK = new Set<SlideBg>(['dusk', 'night'])
|
||||
|
||||
// 그림 배경이 있는 각(code)과 장 수. 여러 장이면 글마다 돌려 쓴다
|
||||
const BG_IMAGES: Record<string, number> = { bike: 4, picnic: 1, hiking: 1, camping: 1, stars: 1, walk: 1, hangang: 1 }
|
||||
const EVENT_BG_N = 4
|
||||
|
||||
function bgImage(name: string, n: number, seed: number): CSSProperties {
|
||||
const file = n > 1 ? `${name}-${'abcd'[seed % n]}` : name
|
||||
return { backgroundImage: `url(/post-bg/${file}.webp)`, backgroundSize: 'cover', backgroundPosition: 'center' }
|
||||
}
|
||||
|
||||
/** 그림 배경: 각은 각마다, 사진 없는 행사는 행사용. 없으면 색 배경만 */
|
||||
function slideImage(post: PostData, slide: Slide): CSSProperties | undefined {
|
||||
if (slide.kind === 'gak') return BG_IMAGES[slide.code] ? bgImage(slide.code, BG_IMAGES[slide.code], post.post_id) : undefined
|
||||
if (post.post_type === PostType.EVENT && slide.kind === 'rows' && !slide.image) return bgImage('event', EVENT_BG_N, post.post_id)
|
||||
return undefined
|
||||
}
|
||||
|
||||
function Lines({ text }: { text: string }) {
|
||||
return text.split('\n').map((t, i) => (
|
||||
<span key={i}>
|
||||
@@ -73,14 +97,14 @@ function Big({ children, className }: { children: ReactNode; className?: string
|
||||
function Pic({ name, className }: { name: string; className?: string }) {
|
||||
return (
|
||||
<span className={cx('b-fall pointer-events-none absolute top-[30%] right-3.5 w-[42%]', className)} style={fall('.1s', '5s')}>
|
||||
<Ic name={name} className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
<Ic name={name} className="b-bob w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const slideBase = 'relative flex h-full w-full shrink-0 flex-col px-5 py-[22px]'
|
||||
|
||||
function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
function SlideView({ slide, bg, img }: { slide: Slide; bg: SlideBg; img?: CSSProperties }) {
|
||||
const { open } = useSheet()
|
||||
if (slide.kind === 'hours') {
|
||||
const temps = slide.hours.flatMap((h) => (h.temp_c == null ? [] : [h.temp_c]))
|
||||
@@ -115,10 +139,17 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
}
|
||||
if (slide.kind === 'gak')
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
|
||||
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
|
||||
<Big>{slide.line}</Big>
|
||||
<Pic name={slide.code} />
|
||||
{slide.say && <p className="relative z-[1] m-0 mt-2.5 w-[56%] rounded-[16px] rounded-tl-[4px] bg-white/80 px-3 py-2 text-[14px] leading-snug font-bold">{slide.say}</p>}
|
||||
{/* 점수 근거: 비중 큰 조건과 지금 값. 오른쪽 아이콘과 겹치지 않게 왼쪽 반만 */}
|
||||
{!!slide.rows?.length && (
|
||||
<div className="relative z-[1] mt-2 w-[56%] rounded-[16px] bg-white/70 px-3 text-[14px] [&_b]:text-[15px] [&>div>div]:py-1.5 [&>div]:mt-0">
|
||||
<Rows rows={slide.rows} />
|
||||
</div>
|
||||
)}
|
||||
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
|
||||
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
|
||||
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
||||
@@ -210,6 +241,9 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
// 카드뉴스: 관리자가 만든 4:5 이미지 한 장 (/v1/card/... 는 API 서버 경로)
|
||||
if (slide.kind === 'image')
|
||||
return <img src={slide.url.startsWith('/') ? `${API_BASE_URL}${slide.url}` : slide.url} alt={slide.alt ?? ''} className="h-full w-full shrink-0 object-cover" loading="lazy" draggable={false} />
|
||||
if (slide.kind === 'rows' && slide.image)
|
||||
return (
|
||||
<div className={'relative flex h-full w-full shrink-0 flex-col justify-end bg-cover bg-center text-white'} style={{ backgroundImage: `url(${slide.image})` }}>
|
||||
@@ -224,7 +258,7 @@ function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)} style={img}>
|
||||
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
|
||||
<Big className="relative z-[1]">
|
||||
<Lines text={slide.line} />
|
||||
@@ -313,7 +347,6 @@ export function PostCardSkel() {
|
||||
|
||||
function FullCard({ post }: PostProps) {
|
||||
const { open } = useSheet()
|
||||
const { loggedIn } = useAuth()
|
||||
const liked = !!post.liked
|
||||
const likeCount = post.like_count
|
||||
const queryClient = useQueryClient()
|
||||
@@ -339,7 +372,6 @@ function FullCard({ post }: PostProps) {
|
||||
|
||||
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
|
||||
const setLike = (on: boolean) => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (on === liked || like.isPending || unlike.isPending) return
|
||||
if (on) setPop((p) => p + 1)
|
||||
setLikeFailed(0)
|
||||
@@ -364,7 +396,7 @@ function FullCard({ post }: PostProps) {
|
||||
if ((e.target as HTMLElement).closest('button')) return
|
||||
const now = Date.now()
|
||||
if (now - lastTap.current < 320) {
|
||||
if (liked && loggedIn) setPop((p) => p + 1)
|
||||
if (liked) setPop((p) => p + 1)
|
||||
else setLike(true)
|
||||
}
|
||||
lastTap.current = now
|
||||
@@ -402,7 +434,7 @@ function FullCard({ post }: PostProps) {
|
||||
>
|
||||
<div ref={trackRef} className="flex h-full">
|
||||
{post.slides.map((s, i) => (
|
||||
<SlideView key={i} slide={s} bg={bgs[i]} />
|
||||
<SlideView key={i} slide={s} bg={bgs[i]} img={slideImage(post, s)} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -458,3 +490,74 @@ function FullCard({ post }: PostProps) {
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
type FrameProps = {
|
||||
title: string
|
||||
account: string
|
||||
avatar: string
|
||||
caption?: ReactNode
|
||||
more?: ReactNode
|
||||
shot?: RefObject<HTMLDivElement | null>
|
||||
pinned?: { key: PinnedKey; post?: PostReaction | null }
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** 피드 글과 같은 틀(계정 줄·본문·보내기 줄)에 날씨·각 같은 화면 조각을 담는다. 보내기는 shot(공유용 틀)이 있으면 그것을, 없으면 본문을 이미지로 */
|
||||
export function PostFrame({ title, account, avatar, caption, more, shot, pinned, children }: FrameProps) {
|
||||
const { open } = useSheet()
|
||||
const bodyRef = useRef<HTMLDivElement>(null)
|
||||
const like = usePinnedLike(pinned?.key ?? 'gak_post', pinned?.post)
|
||||
const postId = pinned?.post?.post_id
|
||||
const share = () => {
|
||||
const el = shot?.current ?? bodyRef.current
|
||||
if (el) open({ type: 'share', share: { title, slides: [el] } })
|
||||
}
|
||||
return (
|
||||
<article className="mt-3.5 border-y border-(--line) bg-white first:mt-1" aria-label={title}>
|
||||
<div className="flex items-center gap-2.5 px-3 py-2.5">
|
||||
<span className="b-ring size-[34px] shrink-0 rounded-full p-0.5">
|
||||
<i className="grid size-full place-items-center rounded-full bg-white">
|
||||
<Ic name={avatar} className="w-[22px]" />
|
||||
</i>
|
||||
</span>
|
||||
<span>
|
||||
<b className="block text-sm leading-tight font-extrabold">날씨각</b>
|
||||
<small className="text-xs font-semibold text-(--ink2)">{account}</small>
|
||||
</span>
|
||||
</div>
|
||||
<div ref={bodyRef}>{children}</div>
|
||||
<div className="flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
||||
{postId != null && (
|
||||
<>
|
||||
<button type="button" onClick={like.toggle} aria-pressed={like.liked} aria-label="좋아요" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<HeartIcon className={like.liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
|
||||
</button>
|
||||
<button type="button" onClick={() => open({ type: 'comments', postId })} aria-label="댓글 보기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button type="button" onClick={share} aria-label="보내기" className={cx('relative grid size-7 cursor-pointer place-items-center', TAP44)}>
|
||||
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||
</button>
|
||||
{more && <span className="ml-auto text-[13px] font-bold text-(--ink2)">{more}</span>}
|
||||
</div>
|
||||
{postId != null && (
|
||||
<p className="px-3 py-0.5 text-sm font-extrabold">
|
||||
{like.failed ? <span className="text-(--heart)" role="alert">좋아요를 반영하지 못했어요. 다시 해 주세요.</span> : `좋아요 ${like.count.toLocaleString()}개`}
|
||||
</p>
|
||||
)}
|
||||
{caption && (
|
||||
<p className="px-3 pt-0.5 pb-3 text-sm">
|
||||
<b className="mr-[5px] font-extrabold">날씨각</b>
|
||||
{caption}
|
||||
</p>
|
||||
)}
|
||||
{postId != null && (
|
||||
<button type="button" onClick={() => open({ type: 'comments', postId })} className="block cursor-pointer px-3 pb-3 text-sm font-semibold text-(--ink3)">
|
||||
{pinned?.post?.comment_count ? `댓글 ${pinned.post.comment_count}개 모두 보기` : '첫 댓글 남기기'}
|
||||
</button>
|
||||
)}
|
||||
</article>
|
||||
)
|
||||
}
|
||||
@@ -83,7 +83,7 @@ export function SeasonPage() {
|
||||
<p className="m-0 text-[13px] font-extrabold opacity-75">이번 주 특집{w.start && w.end ? ` · ${dateRange(w.start, w.end)}` : ''}</p>
|
||||
<p className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight">{w.headline}</p>
|
||||
<span className="b-fall pointer-events-none absolute top-[18%] right-3.5 w-[38%]" style={fall('.1s')}>
|
||||
<Ic name="maple" className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
<Ic name="maple" className="b-bob w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
</span>
|
||||
{(w.poem_lines ?? []).length > 0 && (
|
||||
<p className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[1.7]">
|
||||
|
||||
+87
-77
@@ -1,5 +1,6 @@
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
|
||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import regionPages from '../../seo/region.json'
|
||||
import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import {
|
||||
@@ -17,27 +18,30 @@ import {
|
||||
listBlockedQueryKey,
|
||||
listCommentsInfiniteQueryKey,
|
||||
listRegionsOptions,
|
||||
loginMutation,
|
||||
meQueryKey,
|
||||
reportCommentMutation,
|
||||
signupMutation,
|
||||
unblockMutation,
|
||||
unlikeCommentMutation,
|
||||
updateMeMutation,
|
||||
withdrawMutation,
|
||||
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { AuthProvider, ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib'
|
||||
import { GoogleButton } from './googleLogin'
|
||||
import { useInstall, useInstallable } from './install'
|
||||
import { InstallSheet } from './installBanner'
|
||||
import { ARTICLE_CAT } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { MixSheet } from './myGak'
|
||||
import { ownPage, useRegion } from './regionContext'
|
||||
import { WeatherWhySheet } from './weatherWhy'
|
||||
import { useSky } from './skyContext'
|
||||
import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { MyTalks, TalkSheet } from './talk'
|
||||
import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||
|
||||
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
@@ -80,7 +84,7 @@ export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
}
|
||||
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기' } as const
|
||||
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
@@ -104,13 +108,15 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
const root = document.documentElement
|
||||
const before = root.style.overflow
|
||||
root.style.overflow = 'hidden'
|
||||
root.classList.add('b-sheet-open')
|
||||
return () => {
|
||||
root.style.overflow = before
|
||||
root.classList.remove('b-sheet-open')
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
const then = state?.type === 'login' ? state.then : undefined
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
|
||||
const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type]
|
||||
|
||||
return (
|
||||
<dialog
|
||||
@@ -140,8 +146,13 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} onLoggedIn={then ? () => open(then) : onClose} />}
|
||||
{state.type === 'me' && <MeSheet onDone={onClose} />}
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
{state.type === 'mix' && <MixSheet shared={state.shared} onDone={onClose} />}
|
||||
{state.type === 'install' && <InstallSheet />}
|
||||
{state.type === 'weatherWhy' && <WeatherWhySheet d={state.why} />}
|
||||
{state.type === 'talk' && <TalkSheet talk={state.talk} />}
|
||||
</div>
|
||||
)}
|
||||
{!state && <RegionLinks />}
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
@@ -361,7 +372,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
|
||||
</div>
|
||||
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
|
||||
</div>
|
||||
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
|
||||
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
|
||||
{now && (
|
||||
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
|
||||
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
|
||||
@@ -526,14 +537,14 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
const srcs = useRef<string[]>([])
|
||||
const [toast, setToast] = useState('')
|
||||
const image = images[size]
|
||||
const text = `${share.title} · 날씨각 ${SITE_URL}`
|
||||
const text = `${share.title} · 날씨각`
|
||||
|
||||
// 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다
|
||||
useEffect(() => {
|
||||
if (images[size] || failed[size]) return
|
||||
let alive = true
|
||||
const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' })
|
||||
shareImage(share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
|
||||
shareImage(size === 'square' && share.square ? share.square : share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then(
|
||||
(blob) => {
|
||||
if (!alive) return
|
||||
const src = URL.createObjectURL(blob)
|
||||
@@ -548,21 +559,28 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [size, images, failed, share.slides, kind, region.name])
|
||||
}, [size, images, failed, share.slides, share.square, kind, region.name])
|
||||
|
||||
useEffect(() => {
|
||||
const list = srcs.current
|
||||
return () => list.forEach((s) => URL.revokeObjectURL(s))
|
||||
}, [])
|
||||
|
||||
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 공유창이 없으면 이미지를 내려받고 링크를 복사한다
|
||||
// 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 이미지만 받는 앱이 있어 링크도 복사해 둔다. 공유창이 없으면 이미지를 내려받고 링크를 복사한다
|
||||
const send = () => {
|
||||
if (!image) return
|
||||
const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' })
|
||||
if (navigator.canShare?.({ files: [file], text })) {
|
||||
navigator.share({ files: [file], title: share.title, text }).then(
|
||||
() => {
|
||||
setToast('보냈어요')
|
||||
if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) {
|
||||
const copied = navigator.clipboard?.writeText(SITE_URL).then(
|
||||
() => true,
|
||||
(e: unknown) => {
|
||||
console.error('[share] copy link', e)
|
||||
return false
|
||||
},
|
||||
)
|
||||
navigator.share({ files: [file], title: share.title, text, url: SITE_URL }).then(
|
||||
async () => {
|
||||
setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요')
|
||||
track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio })
|
||||
},
|
||||
(e: unknown) => {
|
||||
@@ -582,7 +600,7 @@ function ShareSheet({ share }: { share: SharePayload }) {
|
||||
setToast('이미지를 내려받았어요')
|
||||
return
|
||||
}
|
||||
navigator.clipboard.writeText(text).then(
|
||||
navigator.clipboard.writeText(`${text} ${SITE_URL}`).then(
|
||||
() => setToast('이미지를 내려받고 링크를 복사했어요'),
|
||||
() => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'),
|
||||
)
|
||||
@@ -701,8 +719,6 @@ function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number;
|
||||
|
||||
function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) {
|
||||
const { region } = useRegion()
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const queryClient = useQueryClient()
|
||||
const [liked, setLiked] = useState(c.liked)
|
||||
const [count, setCount] = useState(c.like_count)
|
||||
@@ -713,7 +729,6 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
|
||||
const [likeFailed, setLikeFailed] = useState(false)
|
||||
|
||||
const toggle = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (like.isPending || unlike.isPending) return
|
||||
const next = !liked
|
||||
setLikeFailed(false)
|
||||
@@ -796,8 +811,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o
|
||||
|
||||
function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const { loggedIn, me } = useAuth()
|
||||
const { me } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const list = useInfiniteQuery({
|
||||
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
|
||||
@@ -824,7 +838,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||
if (!body || add.isPending) return
|
||||
setAddFailed(false)
|
||||
add.mutate(
|
||||
{ path: { post_id: postId }, body: { body } },
|
||||
{ path: { post_id: postId }, body: { body, region: region.code } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true)
|
||||
@@ -839,10 +853,9 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
// 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
|
||||
// 로그인했으면 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } })
|
||||
if (me && !me.terms_agreed) return setAskTerms(true)
|
||||
send()
|
||||
}
|
||||
@@ -916,7 +929,7 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||
</p>
|
||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-2.5">
|
||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
|
||||
<button type="submit" disabled={add.isPending || !text.trim()} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
|
||||
<Swap labels={['게시', '올리는 중…']} at={add.isPending ? 1 : 0} />
|
||||
</button>
|
||||
</form>
|
||||
@@ -925,74 +938,41 @@ function CommentsSheet({ postId, draft }: { postId: number; draft?: string }) {
|
||||
}
|
||||
|
||||
/* ---------- 로그인 ---------- */
|
||||
const AUTH_ERRORS: Record<string, string> = {
|
||||
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
|
||||
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
|
||||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
|
||||
}
|
||||
|
||||
function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) {
|
||||
const { me } = useAuth()
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
||||
const [loginId, setLoginId] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [nickname, setNickname] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const login = useMutation(loginMutation())
|
||||
const signup = useMutation(signupMutation())
|
||||
const pending = login.isPending || signup.isPending
|
||||
|
||||
const done = (res: ResAuth, method: 'id' | 'google' = 'id') => {
|
||||
const done = (res: ResAuth) => {
|
||||
if (!res.result?.success || !res.access_token) {
|
||||
setError(method === 'google' ? '구글로 로그인하지 못했어요. 다시 해 주세요.' : (AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.'))
|
||||
setError('구글로 로그인하지 못했어요. 다시 해 주세요.')
|
||||
return
|
||||
}
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
track(method === 'google' ? 'login' : mode === 'login' ? 'login' : 'sign_up', { method })
|
||||
track('login', { method: 'google' })
|
||||
onLoggedIn()
|
||||
}
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: (res) => done(res), onError: fail })
|
||||
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: (res) => done(res), onError: fail })
|
||||
}
|
||||
|
||||
if (me) return <MeSheet onDone={onDone} />
|
||||
|
||||
const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3'
|
||||
return (
|
||||
<Body>
|
||||
<form onSubmit={submit} className="flex flex-col gap-2.5">
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<GoogleButton onResult={(res) => done(res, 'google')} onFail={fail} />
|
||||
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
|
||||
{(
|
||||
[
|
||||
['login', '로그인'],
|
||||
['signup', '처음이에요'],
|
||||
] as const
|
||||
).map(([m, l]) => (
|
||||
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-2 text-sm font-extrabold', mode === m ? 'bg-(--ink) text-white' : 'text-(--ink2)')}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<input value={loginId} onChange={(e) => setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} />
|
||||
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={mode === 'signup' ? 8 : undefined} maxLength={64} placeholder={mode === 'signup' ? '비밀번호 (8자 이상)' : '비밀번호'} aria-label="비밀번호" className={field} />
|
||||
{mode === 'signup' && <input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} placeholder="닉네임 (2~12자)" aria-label="닉네임" className={field} />}
|
||||
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||||
<div className="flex flex-col gap-2.5">
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">글쓰기는 로그인한 뒤에 할 수 있어요.</p>
|
||||
<GoogleButton
|
||||
onResult={(res) => {
|
||||
setError('')
|
||||
done(res)
|
||||
}}
|
||||
onFail={fail}
|
||||
/>
|
||||
<p className="m-0 text-center text-[13px] font-bold text-(--heart) empty:hidden" aria-live="polite">
|
||||
{error}
|
||||
</p>
|
||||
<button type="submit" disabled={pending} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
<Swap labels={mode === 'login' ? ['로그인', '로그인 중…'] : ['가입하고 시작하기', '가입하는 중…']} at={pending ? 1 : 0} />
|
||||
</button>
|
||||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||||
나중에 할게요
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
@@ -1085,6 +1065,8 @@ function Blocked() {
|
||||
}
|
||||
|
||||
function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
const install = useInstall()
|
||||
const installable = useInstallable()
|
||||
const { me, logout } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const update = useMutation(updateMeMutation())
|
||||
@@ -1118,8 +1100,13 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
<Body className="flex flex-col gap-3">
|
||||
<div className="flex flex-col items-center gap-1.5">
|
||||
<Avatar character={me.character} color={me.color} mood={me.mood} size={64} />
|
||||
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.login_id}(으)로 로그인했어요</p>
|
||||
<p className="m-0 text-center text-sm font-semibold text-(--ink2)">{me.provider === AuthProvider.GOOGLE ? '구글 계정으로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}</p>
|
||||
</div>
|
||||
{installable && (
|
||||
<button type="button" onClick={() => install('menu')} className="cursor-pointer rounded-2xl bg-[#fff4ec] py-2.5 font-jua text-[15.5px] text-(--orange)">
|
||||
📲 홈 화면에 추가
|
||||
</button>
|
||||
)}
|
||||
<section aria-label="내 캐릭터">
|
||||
<h4 className="m-0 mb-2 text-sm font-extrabold">내 캐릭터</h4>
|
||||
<div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label="캐릭터 고르기">
|
||||
@@ -1192,6 +1179,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
<p className={cx('m-0 min-h-5 text-center text-[13px] font-bold', saving ? 'text-(--ink2)' : 'text-(--heart)')} aria-live="polite">
|
||||
{saving ? (saving.nickname == null ? '저장 중…' : '') : error}
|
||||
</p>
|
||||
<MyTalks />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
@@ -1211,6 +1199,27 @@ function MeSheet({ onDone }: { onDone: () => void }) {
|
||||
/* ---------- 지역 ---------- */
|
||||
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
|
||||
|
||||
/** 구 코드 → 그 구의 지역 페이지 주소 */
|
||||
const pageHref = (code: string) => {
|
||||
const p = ownPage(code)
|
||||
return p ? `/today/${p.path}` : '/'
|
||||
}
|
||||
|
||||
/** 지역 바꾸기가 닫혀 있을 때도 지역 페이지 링크를 HTML에 둔다 (검색 로봇이 링크를 따라가게) */
|
||||
function RegionLinks() {
|
||||
return (
|
||||
<nav aria-label="지역별 오늘 날씨">
|
||||
<ul>
|
||||
{regionPages.map((p) => (
|
||||
<li key={p.path}>
|
||||
<a href={`/today/${p.path}`}>{p.name} 오늘 날씨</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||
const { me, logout } = useAuth()
|
||||
@@ -1242,10 +1251,11 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
<ul className={cx('mt-2 flex flex-col transition-opacity', list.isPlaceholderData && 'opacity-60')}>
|
||||
{regions.map((r) => (
|
||||
<li key={r.code}>
|
||||
<button
|
||||
type="button"
|
||||
<a
|
||||
href={pageHref(r.code)}
|
||||
aria-current={r.code === region.code ? 'true' : undefined}
|
||||
onClick={() => {
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
setRegion(r)
|
||||
track('region_change', { region_name: r.name, method: 'list' })
|
||||
onDone()
|
||||
@@ -1254,7 +1264,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
>
|
||||
{r.name}
|
||||
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
||||
</button>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useSearchParams } from 'react-router'
|
||||
import type { TalkTopic } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { TalkCard } from './talk'
|
||||
import { TOPICS, useTopicTalks } from './talkState'
|
||||
import { Sec } from './ui'
|
||||
|
||||
/** 주제별 사람 글: 위 주제 탭, 아래 글 목록. 피드 묶음의 '전체 보기'가 ?topic= 으로 연다 */
|
||||
export function TalkPage() {
|
||||
const [params, setParams] = useSearchParams()
|
||||
const raw = Number(params.get('topic'))
|
||||
const topic = TOPICS.some(([k]) => k === raw) ? (raw as TalkTopic) : undefined
|
||||
const { talks, loaded, more, loadMore } = useTopicTalks(topic)
|
||||
const tabs: (readonly [TalkTopic | undefined, string])[] = [[undefined, '전체'], ...TOPICS]
|
||||
|
||||
return (
|
||||
<section aria-label="동네 사람들 글">
|
||||
<Sec title="동네 사람들 글" sub="가까운 동네 글부터 보여요" />
|
||||
<div className="flex flex-wrap gap-1.5 px-4 pb-1" role="tablist" aria-label="글 주제">
|
||||
{tabs.map(([k, label]) => (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={topic === k}
|
||||
onClick={() => setParams(k ? { topic: String(k) } : {}, { replace: true })}
|
||||
className={cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2)')}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{loaded && !talks.length && <p className="mx-4 mt-6 text-center text-[14px] font-semibold text-(--ink3)">아직 이 주제 글이 없어요. 오늘 탭에서 첫 글을 써 주세요.</p>}
|
||||
{talks.map((t) => (
|
||||
<TalkCard key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />
|
||||
))}
|
||||
{more && (
|
||||
<button type="button" onClick={() => loadMore()} className="mx-3 mt-3 w-[calc(100%-1.5rem)] cursor-pointer rounded-[14px] bg-white py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
|
||||
더 보기
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
+448
-119
@@ -1,26 +1,70 @@
|
||||
import { Fragment, useEffect, useState, type ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { Link, useLocation } from 'react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getFeedOptions, getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen'
|
||||
import {
|
||||
PostType,
|
||||
RainType,
|
||||
Sky,
|
||||
TalkTopic,
|
||||
type BandArticle,
|
||||
type BandEvent,
|
||||
type Hero as HeroData,
|
||||
type PostReaction,
|
||||
type ResWeatherToday,
|
||||
type TalkData,
|
||||
type TopIndex,
|
||||
type WeatherSlot,
|
||||
} from '@nalssigak/shared/api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'
|
||||
import { fall } from './lib'
|
||||
import { PostCard, PostCardSkel } from './Post'
|
||||
import { FoliageCard } from './foliageMap'
|
||||
import { InstallBanner } from './installBanner'
|
||||
import { MyGakRow } from './myGak'
|
||||
import { fromShare } from './myGakState'
|
||||
import { PostCard, PostCardSkel, PostFrame } from './Post'
|
||||
import { usePinnedLike, type PinnedKey } from './pinnedLike'
|
||||
import { FeedComposer, NearTalks, TalkCard, TalkGroup } from './talk'
|
||||
import { topicName, useTalkGroups } from './talkState'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { useSky } from './skyContext'
|
||||
import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui'
|
||||
import { DayShareCard, DayShareGrid, GakShareCard, type DayShare } from './shareCards'
|
||||
import { CommentIcon, HeartIcon, SendIcon } from './svg'
|
||||
import { Ic, Rail, Sec, Skel, StateBox, TAP44, Thumb } from './ui'
|
||||
import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'
|
||||
import { atSlot, KINDS, moonPath, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today'
|
||||
|
||||
type Mode = 'now' | TimeKind
|
||||
|
||||
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
|
||||
const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` }))
|
||||
const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` }))
|
||||
// 하루 흐름 칸 순서와 칸마다 볼 예보 시각
|
||||
const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night']
|
||||
const PREVIEW: Record<TimeKind, { label: string; hour: number }> = {
|
||||
morning: { label: '아침', hour: 7 },
|
||||
day: { label: '낮', hour: 13 },
|
||||
sunset: { label: '저녁', hour: 18 },
|
||||
night: { label: '밤', hour: 22 },
|
||||
}
|
||||
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||
// 비·눈 줄기: 위치·주기를 엇갈려 고르게
|
||||
const DROPS = Array.from({ length: 22 }, (_, i) => ({
|
||||
left: `${(i * 41) % 100}%`,
|
||||
'--top': `${(i * 29) % 90}%`,
|
||||
'--dl': `${((i * 37) % 100) / 100}s`,
|
||||
'--dur': `${0.55 + ((i * 13) % 5) / 10}s`,
|
||||
}))
|
||||
const FLAKES = Array.from({ length: 16 }, (_, i) => ({
|
||||
left: `${(i * 47) % 100}%`,
|
||||
'--top': `${(i * 31) % 90}%`,
|
||||
'--dl': `${((i * 53) % 100) / 25}s`,
|
||||
'--dur': `${3.2 + ((i * 7) % 5) / 2}s`,
|
||||
}))
|
||||
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({
|
||||
left: `${(i * 37) % 100}%`,
|
||||
top: `${(i * 53) % 60}%`,
|
||||
opacity: 0.4 + ((i * 7) % 6) / 10,
|
||||
}))
|
||||
// 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게
|
||||
const SHOOTS = [
|
||||
{ top: '6%', left: '80%', '--len': '90px', '--dur': '7s', '--dl': '1.5s' },
|
||||
@@ -57,27 +101,116 @@ function heroVal(load: Load, v: ReactNode, skel: string) {
|
||||
|
||||
const failed = (load: Load) => load === 'error' || load === 'retrying'
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }
|
||||
// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간
|
||||
const SLOT_KEY: Record<TimeKind, string> = {
|
||||
morning: 'morning',
|
||||
day: 'day',
|
||||
sunset: 'evening',
|
||||
night: 'night',
|
||||
}
|
||||
|
||||
/** 미리보기 시간대면 서버가 해당 구간의 날씨·시간대 적합도로 계산한 점수·순위로 다시 줄 세운다. 구간 값이 없으면(예전 캐시) 그대로 */
|
||||
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
|
||||
const k = kind && SLOT_KEY[kind]
|
||||
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
|
||||
const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null)
|
||||
return [
|
||||
...on
|
||||
.map((g) => ({
|
||||
...g,
|
||||
score: g.slots![k],
|
||||
rank: g.slot_ranks![k],
|
||||
active: true,
|
||||
}))
|
||||
.sort((a, b) => a.rank - b.rank),
|
||||
...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })),
|
||||
]
|
||||
}
|
||||
|
||||
type HeroProps = {
|
||||
hero?: HeroData | null
|
||||
post?: PostReaction | null
|
||||
today?: ResWeatherToday
|
||||
ranked: TopIndex[]
|
||||
all: TopIndex[]
|
||||
feedLoad: Load
|
||||
todayLoad: Load
|
||||
}
|
||||
|
||||
type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet'
|
||||
|
||||
/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */
|
||||
function weatherOf(slot?: WeatherSlot): Weather {
|
||||
const r = slot?.rain_type
|
||||
if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain'
|
||||
if (r === RainType.SNOW) return 'snow'
|
||||
if (r === RainType.SLEET) return 'sleet'
|
||||
return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear'
|
||||
}
|
||||
|
||||
const WEATHER_ICON: Record<Weather, string> = {
|
||||
clear: 'sun',
|
||||
partly: 'sun_cloud',
|
||||
cloudy: 'cloud',
|
||||
rain: 'rain',
|
||||
snow: 'snow',
|
||||
sleet: 'snow',
|
||||
}
|
||||
// 구름 수: 구름 많음 둘, 흐림·비·눈 셋
|
||||
// 히어로 오른쪽 위 좋아요·댓글·보내기: 셋 다 같은 32px 칸에 아이콘 가운데, 수는 아이콘 옆
|
||||
const HERO_ACT = 'relative flex h-8 min-w-8 cursor-pointer items-center justify-center gap-1 text-[13px] font-extrabold'
|
||||
const CLOUDS = [
|
||||
{ cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' },
|
||||
{ cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' },
|
||||
{ cls: 'top-[30px] left-[72%] h-7 w-[64px]', d: '.4s', f: '5.4s' },
|
||||
]
|
||||
const CLOUD_N: Record<Weather, number> = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 }
|
||||
const CLOUD_N: Record<Weather, number> = {
|
||||
clear: 0,
|
||||
partly: 2,
|
||||
cloudy: 3,
|
||||
rain: 3,
|
||||
snow: 3,
|
||||
sleet: 3,
|
||||
}
|
||||
|
||||
function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||
function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps) {
|
||||
const { open } = useSheet()
|
||||
const like = usePinnedLike('hero_post', post)
|
||||
const { region } = useRegion()
|
||||
const tplRef = useRef<HTMLDivElement>(null)
|
||||
const gridRef = useRef<HTMLDivElement>(null)
|
||||
// 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다
|
||||
// 내일 날씨 페이지(/tomorrow/...)로 들어오면 내일이 켜진 채로
|
||||
const { pathname } = useLocation()
|
||||
const [tmr, setTmr] = useState(() => pathname.startsWith('/tomorrow/'))
|
||||
const [tmrKind, setTmrKind] = useState<TimeKind>('day')
|
||||
const tomorrowQ = useQuery({
|
||||
...getWeatherTodayOptions({
|
||||
query: { region: region.code, day: 'tomorrow' },
|
||||
}),
|
||||
enabled: tmr,
|
||||
})
|
||||
const ahead = hero?.tomorrow
|
||||
const share = () =>
|
||||
tplRef.current &&
|
||||
open({
|
||||
type: 'share',
|
||||
share: {
|
||||
title: `${region.name} ${tmr ? '내일' : '오늘'} 날씨`,
|
||||
slides: [tplRef.current],
|
||||
square: gridRef.current ? [gridRef.current] : undefined,
|
||||
},
|
||||
})
|
||||
const { preview, setServerKind, setPreview } = useSky()
|
||||
const mode: Mode = preview ?? 'now'
|
||||
const mode: Mode = tmr ? tmrKind : (preview ?? 'now')
|
||||
const clock = useNow()
|
||||
const t = kst(clock)
|
||||
const t = kst(tmr ? new Date(clock.getTime() + 86400000) : clock)
|
||||
const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)
|
||||
const kind = mode === 'now' ? nowKind : mode
|
||||
// 화면 전체 하늘 배경도 같은 시간대로 맞춘다
|
||||
useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind])
|
||||
const slots = today?.slots ?? []
|
||||
const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? []
|
||||
const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad
|
||||
// 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
||||
// 지금은 가장 가까운 3시간 칸(17시면 18시 칸). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸
|
||||
const slotOf = (k: TimeKind | 'now') => {
|
||||
@@ -91,22 +224,78 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||
return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s)
|
||||
}
|
||||
const weather = weatherOf(slotOf(mode))
|
||||
const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]]
|
||||
const score = slotScore ?? hero?.weather_score
|
||||
const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active)
|
||||
const top1 = slotTop ?? hero?.top1
|
||||
const slotScore = mode === 'now' ? undefined : (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[mode]]
|
||||
const score = tmr ? slotScore : (slotScore ?? hero?.weather_score)
|
||||
// 점수 옆 ? 버튼: 보고 있는 시간대(지금이면 지금 구간)의 날씨 점수 근거
|
||||
const whyKey = mode === 'now' ? SLOT_KEY[nowKind] : SLOT_KEY[mode]
|
||||
const why = (tmr ? ahead?.weather_why : hero?.weather_why)?.[whyKey]
|
||||
const whyLabel = tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
|
||||
const slotTop = mode === 'now' || tmr ? undefined : ranked.find((g) => g.active)
|
||||
const top1 = tmr ? ahead?.top1 : (slotTop ?? hero?.top1)
|
||||
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
|
||||
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
|
||||
const moon =
|
||||
!tmr && (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null
|
||||
? {
|
||||
name: hero.moon_name,
|
||||
pct: hero.moon_pct,
|
||||
waning: WANING.includes(hero.moon_name),
|
||||
}
|
||||
: null
|
||||
// 말풍선 머리말은 칸 이름 그대로: 지금은 / 아침은 / 낮은 / 저녁은 / 밤은
|
||||
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
|
||||
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
|
||||
const status = hero?.status ?? []
|
||||
const bubble = tmr
|
||||
? top1
|
||||
? top1.score >= 70
|
||||
? `내일은 ${top1.name}!`
|
||||
: '내일은 쉬어 가요'
|
||||
: null
|
||||
: slotTop
|
||||
? slotTop.score >= 70
|
||||
? `${when}은 ${slotTop.name}!`
|
||||
: `${when}은 쉬어 가요`
|
||||
: hero
|
||||
? (hero.bubble ?? '지금은 쉬어 가요')
|
||||
: failed(feedLoad)
|
||||
? '앗, 날씨를 못 불러왔어요'
|
||||
: null
|
||||
// 내일은 최저·최고 기온과 고른 시간대 습도
|
||||
const temps = slots.flatMap((x) => (x.temp_c != null ? [x.temp_c] : []))
|
||||
const humidity = tmr && mode !== 'now' ? slotOf(mode)?.humidity : null
|
||||
const status = tmr
|
||||
? [
|
||||
...(temps.length
|
||||
? [
|
||||
{ label: '최저', value: deg(Math.min(...temps)), tone: 'info' },
|
||||
{ label: '최고', value: deg(Math.max(...temps)), tone: 'info' },
|
||||
]
|
||||
: []),
|
||||
...(humidity != null ? [{ label: '습도', value: `${humidity}%`, tone: 'info' }] : []),
|
||||
]
|
||||
: (hero?.status ?? [])
|
||||
const rain = weather === 'rain' || weather === 'sleet'
|
||||
const snow = weather === 'snow' || weather === 'sleet'
|
||||
|
||||
// 공유 이미지: 아침~밤 네 시간대 모두. 점수는 시간대 점수, 각은 그 시간대 1등
|
||||
const days: DayShare[] = KINDS.map((k) => {
|
||||
const isNow = !tmr && k === nowKind
|
||||
const s = slotOf(isNow ? 'now' : k)
|
||||
const top = tmr ? ahead?.top1 : atSlot(all, k).find((g) => g.active)
|
||||
return {
|
||||
kind: k,
|
||||
label: PREVIEW[k].label,
|
||||
now: isNow,
|
||||
icon: k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)],
|
||||
temp: s?.temp_c != null ? deg(s.temp_c) : '–',
|
||||
score: (tmr ? ahead?.weather_slots : hero?.weather_slots)?.[SLOT_KEY[k]] ?? (isNow ? hero?.weather_score : null),
|
||||
gak: top ? { name: top.name, icon: top.icon } : null,
|
||||
}
|
||||
})
|
||||
|
||||
// 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로)
|
||||
return (
|
||||
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3" data-t={kind} data-sky={weather}>
|
||||
<DayShareCard days={days} ref={tplRef} />
|
||||
<DayShareGrid days={days} ref={gridRef} />
|
||||
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{STARS.map((s, i) => (
|
||||
<i key={i} className="absolute size-[3px] rounded-full shadow-[0_0_6px_#fff]" style={s} />
|
||||
@@ -121,29 +310,109 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||
{snow && FLAKES.map((s, i) => <i key={i} className="b-flake" style={s} />)}
|
||||
</div>
|
||||
)}
|
||||
<p className="relative z-[3] m-0 text-[14px] font-bold opacity-80">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
|
||||
</p>
|
||||
<div className="relative z-[3] flex items-center justify-between">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="b-strip grid grid-cols-2 rounded-full p-[3px]" role="radiogroup" aria-label="오늘 또는 내일 날씨">
|
||||
{(
|
||||
[
|
||||
[false, '오늘'],
|
||||
[true, '내일'],
|
||||
] as const
|
||||
).map(([v, l]) => (
|
||||
<button
|
||||
key={l}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={tmr === v}
|
||||
onClick={() => setTmr(v)}
|
||||
className={cx('cursor-pointer rounded-full px-2.5 py-0.5 font-jua text-[13px]', tmr === v ? 'b-strip-on text-(--orange-deep)' : 'opacity-75')}
|
||||
>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
<span className="text-[13px] font-bold opacity-80">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
|
||||
</span>
|
||||
</span>
|
||||
<span className="flex items-center gap-1 [&_svg]:size-[22px] [&_svg]:stroke-[2]">
|
||||
{post && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={like.toggle}
|
||||
aria-pressed={like.liked}
|
||||
aria-label={like.failed ? '좋아요를 반영하지 못했어요. 다시 눌러 주세요' : '오늘 날씨 좋아요'}
|
||||
className={cx(HERO_ACT, TAP44, !like.liked && 'opacity-80')}
|
||||
>
|
||||
<HeartIcon className={like.liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-current'} />
|
||||
{like.count > 0 && like.count.toLocaleString()}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'comments', postId: post.post_id })}
|
||||
aria-label="오늘 날씨 댓글"
|
||||
className={cx(HERO_ACT, 'opacity-80', TAP44)}
|
||||
>
|
||||
<CommentIcon className="fill-none stroke-current [stroke-linejoin:round]" />
|
||||
{post.comment_count > 0 && post.comment_count.toLocaleString()}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button type="button" onClick={share} aria-label="오늘 날씨 보내기" className={cx(HERO_ACT, 'opacity-80', TAP44)}>
|
||||
<SendIcon className="fill-none stroke-current [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
<div className="relative h-[146px]">
|
||||
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
|
||||
<span key={c.cls} className={cx('b-cloud b-fall z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true" />
|
||||
))}
|
||||
<div className="b-sun b-fall absolute top-2 left-1/2 -ml-16 grid aspect-square w-32 place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
|
||||
{moon && (
|
||||
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
|
||||
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
|
||||
</svg>
|
||||
)}
|
||||
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}>
|
||||
<small className="block font-jua text-[12px]">{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}</small>
|
||||
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
|
||||
<span key={c.cls} className={cx('b-fall absolute z-[1]', c.cls)} style={fall(c.d, c.f)} aria-hidden="true">
|
||||
<span className="b-cloud b-bob inset-0" />
|
||||
</span>
|
||||
))}
|
||||
<div className={'b-fall absolute top-2 left-1/2 -ml-16 aspect-square w-32'} style={fall('0s', '5.6s')}>
|
||||
<div className="b-sun b-bob relative grid size-full place-items-center rounded-full text-center">
|
||||
{/* 안 보이는 쪽을 덮어 오늘 밤 달 모양으로 */}
|
||||
{moon && (
|
||||
<svg viewBox="-1 -1 2 2" className="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
|
||||
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
|
||||
</svg>
|
||||
)}
|
||||
{/* 점수 근거가 있으면 해를 눌러도 근거 창: 구석 버튼은 구름에 가려져서 상태 줄 끝으로 옮김 */}
|
||||
{(() => {
|
||||
const body = (
|
||||
<>
|
||||
<small className="block font-jua text-[12px]">
|
||||
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
|
||||
</small>
|
||||
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
|
||||
</>
|
||||
)
|
||||
const cls = cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')
|
||||
if (!why || score == null) return <span className={cls}>{body}</span>
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })}
|
||||
aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`}
|
||||
className={cx(cls, 'flex cursor-pointer flex-col items-center')}
|
||||
>
|
||||
{body}
|
||||
</button>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative z-[3] text-center">
|
||||
{/* 다 불러온 높이(한 줄 말·날씨 한 줄·상태 두 줄)를 미리 잡아 둔다: 늦게 채워지며 아래 피드가 밀려 내려가지 않게 */}
|
||||
<div className="relative z-[3] min-h-[103px] text-center">
|
||||
{top1 ? (
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: top1.index_id })} aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`} className="cursor-pointer font-jua text-[24px] leading-tight">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: top1.index_id })}
|
||||
aria-label={`${bubble ?? ''} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기`}
|
||||
className="cursor-pointer font-jua text-[24px] leading-tight"
|
||||
>
|
||||
{bubble}
|
||||
</button>
|
||||
) : (
|
||||
@@ -155,25 +424,41 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||
<p className="m-0 mt-1.5 flex flex-wrap justify-center gap-x-1.5 font-jua text-[14px]">
|
||||
{status.map((x, i) => (
|
||||
<Fragment key={x.label}>
|
||||
{i > 0 && <span className="opacity-30" aria-hidden="true">·</span>}
|
||||
{i > 0 && (
|
||||
<span className="opacity-30" aria-hidden="true">
|
||||
·
|
||||
</span>
|
||||
)}
|
||||
<span className={cx('whitespace-nowrap', x.tone === 'warn' && 'b-warn')}>
|
||||
<span className={cx(x.tone !== 'warn' && 'opacity-75')}>{x.label}</span> <b className="font-normal">{x.value}</b>
|
||||
</span>
|
||||
</Fragment>
|
||||
))}
|
||||
{why && score != null && (
|
||||
<button type="button" onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })} aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} className={cx('relative cursor-pointer whitespace-nowrap text-(--orange-deep)', TAP44)}>
|
||||
· 점수 근거 ›
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="b-strip relative z-[3] mt-2.5 grid grid-cols-4 gap-1 rounded-[18px] p-[3px]" role="tablist" aria-label="하루 흐름, 누르면 그 시간대 하늘로">
|
||||
{KINDS.map((k) => {
|
||||
const isNow = k === nowKind
|
||||
const isNow = !tmr && k === nowKind
|
||||
const s = slotOf(isNow ? 'now' : k)
|
||||
const on = k === kind
|
||||
return (
|
||||
<button key={k} type="button" role="tab" aria-selected={on} onClick={() => setPreview(isNow ? null : k)} className={cx('flex cursor-pointer flex-col items-center rounded-[14px] py-1.5', on && 'b-strip-on')}>
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={on}
|
||||
onClick={() => (tmr ? setTmrKind(k) : setPreview(isNow ? null : k))}
|
||||
className={cx('flex cursor-pointer flex-col items-center rounded-[14px] py-1.5', on && 'b-strip-on')}
|
||||
>
|
||||
<span className={cx('text-[13px] font-bold', on ? 'text-(--orange-deep)' : 'opacity-75')}>{isNow ? '지금' : PREVIEW[k].label}</span>
|
||||
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} className="my-0.5 h-[22px] w-[22px] object-contain" />
|
||||
<b className="font-jua text-[15px] font-normal">{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
|
||||
<b className="font-jua text-[15px] font-normal">{heroVal(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</b>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
@@ -182,27 +467,54 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
|
||||
)
|
||||
}
|
||||
|
||||
function Stories({ items }: { items: TopIndex[] }) {
|
||||
const WANING = ['기우는 달', '하현달', '그믐달']
|
||||
|
||||
/**
|
||||
* 반지름 r 인 달에서 밝은 쪽(lit) 또는 어두운 쪽 경로. 차오르는 달 기준(오른쪽이 밝음), 기우는 달은 좌우를 뒤집어 쓴다.
|
||||
* 바깥 반원과 명암 경계(가로 반지름 r·|1-2k| 인 타원 호)로 이루어진다.
|
||||
*/
|
||||
function moonPath(pct: number, r: number, lit: boolean) {
|
||||
const k = pct / 100
|
||||
const edge = `A${r * Math.abs(1 - 2 * k)},${r} 0 0 ${k < 0.5 ? 0 : 1} 0,${-r}`
|
||||
return `M0,${-r} A${r},${r} 0 0 ${lit ? 1 : 0} 0,${r} ${edge}`
|
||||
}
|
||||
|
||||
function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) {
|
||||
const { open } = useSheet()
|
||||
const tplRef = useRef<HTMLDivElement>(null)
|
||||
const top = items.filter((g) => g.active).slice(0, 5)
|
||||
return (
|
||||
<Rail label="오늘의 각 순위">
|
||||
{items.map((g, i) => (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={g.active ? `${g.rank}위 ${g.name} ${g.score}점` : `${g.name}, 지금 시간대 아님`} className={cx('flex w-[72px] cursor-pointer flex-col items-center gap-1', !g.active && 'opacity-55')}>
|
||||
<span className={cx('relative size-[68px] rounded-full p-[3px]', !g.active || g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
|
||||
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
|
||||
<Ic name={g.icon} className="w-[42px]" />
|
||||
</i>
|
||||
{i < 3 && g.active && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
|
||||
</span>
|
||||
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
|
||||
{g.active ? (
|
||||
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
) : (
|
||||
<small className="text-[11px] leading-none font-extrabold text-(--ink3)">지금 아님</small>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
<PostFrame
|
||||
title={`오늘의 각 · ${place}`}
|
||||
account="오늘의 각"
|
||||
avatar="rabbit"
|
||||
more={<Link to="/gak">전체 보기</Link>}
|
||||
caption="누르면 계산 근거를 보여 줘요"
|
||||
shot={tplRef}
|
||||
pinned={{ key: 'gak_post', post }}
|
||||
>
|
||||
<GakShareCard items={top} title={`오늘의 각 · ${place} ${at}`} ref={tplRef} />
|
||||
<div className="b-band-2 px-4 pt-3.5 pb-3">
|
||||
<p className="m-0 font-jua text-[19px]">
|
||||
오늘의 각 · {place} {at}
|
||||
</p>
|
||||
<ol className="m-0 mt-2 grid list-none gap-1.5 p-0">
|
||||
{top.map((g, i) => (
|
||||
<li key={g.index_id}>
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="flex w-full cursor-pointer items-center gap-2.5 rounded-[18px] bg-white px-3 py-2 text-left shadow-[inset_0_-4px_0_var(--shade)]">
|
||||
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
|
||||
<Ic name={g.icon} className="w-[34px] shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<b className="block font-jua text-[16px] leading-tight font-normal">{g.name}</b>
|
||||
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
|
||||
</span>
|
||||
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</PostFrame>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -215,39 +527,21 @@ function PostsSkel() {
|
||||
)
|
||||
}
|
||||
|
||||
const STORY_SKELS = Array.from({ length: 6 }, (_, i) => i)
|
||||
|
||||
/** Stories 와 같은 칸(68px 동그라미 + 이름 + 점수)을 6개 */
|
||||
function StoriesSkel() {
|
||||
/** 띠도 포스트 틀에 담아 좋아요·댓글·보내기를 단다 (post 는 서버의 띠 자리) */
|
||||
function Band({ tone, title, sub, to, avatar, post, pinKey, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; avatar: string; post?: PostReaction | null; pinKey: PinnedKey; children: ReactNode }) {
|
||||
return (
|
||||
<SkelRail>
|
||||
{STORY_SKELS.map((i) => (
|
||||
<span key={i} className="flex w-[72px] flex-col items-center gap-1">
|
||||
<Skel shape className="size-[68px] rounded-full" />
|
||||
<b className="font-jua text-[13px] font-normal">
|
||||
<Skel className="w-12" />
|
||||
</b>
|
||||
<em className="font-bagel text-[12.5px] leading-none not-italic">
|
||||
<Skel className="w-6" />
|
||||
</em>
|
||||
</span>
|
||||
))}
|
||||
</SkelRail>
|
||||
<PostFrame title={title} account={title} avatar={avatar} pinned={{ key: pinKey, post }}>
|
||||
<section className={cx('pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
|
||||
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
|
||||
{children}
|
||||
</section>
|
||||
</PostFrame>
|
||||
)
|
||||
}
|
||||
|
||||
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
|
||||
function EventsBand({ events, post }: { events: BandEvent[]; post?: PostReaction | null }) {
|
||||
return (
|
||||
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
|
||||
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
|
||||
{children}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function EventsBand({ events }: { events: BandEvent[] }) {
|
||||
return (
|
||||
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week">
|
||||
<Band tone={1} title="이번 주 가까운 행사" sub="30km 안 · 날씨까지 같이 보고 골라요" to="/week" avatar="fireworks" post={post} pinKey="events_post">
|
||||
<Rail>
|
||||
{events.map((e, i) => (
|
||||
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
@@ -264,29 +558,10 @@ function EventsBand({ events }: { events: BandEvent[] }) {
|
||||
)
|
||||
}
|
||||
|
||||
function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
|
||||
function SeasonBand({ news, post }: { news: BandArticle[]; post?: PostReaction | null }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
|
||||
<Rail>
|
||||
{items.slice(0, 5).map((g, i) => (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="relative flex w-[138px] cursor-pointer flex-col items-start gap-1 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="absolute top-2 left-2 w-[26px]" /> : <span className="absolute top-2.5 left-3 font-jua text-(--ink3)">{i + 1}위</span>}
|
||||
<Ic name={g.icon} className="w-[58px] self-center" />
|
||||
<b className="font-jua text-base font-normal">{g.name}</b>
|
||||
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
{g.summary && <small className="text-xs font-semibold text-(--ink2)">{g.summary}</small>}
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
</Band>
|
||||
)
|
||||
}
|
||||
|
||||
function SeasonBand({ news }: { news: BandArticle[] }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
|
||||
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season" avatar="fallen_leaf" post={post} pinKey="season_post">
|
||||
<Rail>
|
||||
{news.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
@@ -307,6 +582,7 @@ export function TodayPage() {
|
||||
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
||||
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
||||
const { preview } = useSky()
|
||||
const { open } = useSheet()
|
||||
const f = feed.data
|
||||
const posts = f?.posts ?? []
|
||||
const stories = atSlot(f?.stories ?? [], preview)
|
||||
@@ -314,25 +590,72 @@ export function TodayPage() {
|
||||
const bands = f?.bands
|
||||
const nowAt = f?.hero?.now_at
|
||||
const load = loadOf(feed)
|
||||
const [mine, setMine] = useState<TalkData[]>([])
|
||||
// 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 방금 올린 내 글은 글쓰기 칸 아래에 따로 있으니 빼고
|
||||
const talkGroups = useTalkGroups()
|
||||
const groupOf = (topic: number) => (talkGroups.groups.get(topic) ?? []).filter((t) => !mine.some((m) => m.talk_id === t.talk_id))
|
||||
const group = (topic: number) => {
|
||||
const talks = groupOf(topic)
|
||||
return talks.length ? <TalkGroup key={`talk-${topic}`} title={topicName(topic)} topic={topic} talks={talks} /> : null
|
||||
}
|
||||
// 비·눈이 오거나 2시간 안에 올 때만 비·눈 묶음을 히어로 바로 아래로
|
||||
const at = nowAt ? Date.parse(nowAt) : 0
|
||||
const nowSlot = (today.data?.slots ?? []).filter((x) => x.temp_c != null).reduce<WeatherSlot | undefined>((a, b) => (!a || Math.abs(Date.parse(b.at) - at) < Math.abs(Date.parse(a.at) - at) ? b : a), undefined)
|
||||
const raining = ['rain', 'snow', 'sleet'].includes(weatherOf(nowSlot)) || !!f?.hero?.will_rain_2h
|
||||
const sunsetAt = posts.findIndex((p) => p.post_type === PostType.SUNSET)
|
||||
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [region.code])
|
||||
|
||||
// 친구가 보낸 내 각 링크(/?my=...)로 들어오면 내 동네 기준으로 보여 준다
|
||||
useEffect(() => {
|
||||
const url = new URL(window.location.href)
|
||||
const code = url.searchParams.get('my')
|
||||
if (!code) return
|
||||
url.searchParams.delete('my')
|
||||
window.history.replaceState(window.history.state, '', url)
|
||||
const g = fromShare(code)
|
||||
if (g) open({ type: 'mix', shared: g })
|
||||
}, [open])
|
||||
|
||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [
|
||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
||||
[6, bands?.top5?.length ? <TopBand key="top5" items={sloted ? stories.filter((g) => g.active) : bands.top5} sub={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
||||
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
|
||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} post={f?.events_post} /> : null],
|
||||
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} post={f?.season_post} /> : null],
|
||||
]
|
||||
|
||||
// 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게
|
||||
const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : []), ...(posts.length < 2 ? [TalkTopic.FOLIAGE] : [])].filter((tp) => groupOf(tp).length)
|
||||
const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)])
|
||||
const spreadAt = new Map<number, ReactNode>()
|
||||
let spreadN = 0
|
||||
for (let i = 0; i < posts.length && spreadN < spreadTopics.length; i++) {
|
||||
if (taken.has(i) || spreadAt.has(i - 1)) continue
|
||||
spreadAt.set(i, group(spreadTopics[spreadN++]))
|
||||
}
|
||||
const spreadLeft = spreadTopics.slice(spreadN).map((tp) => group(tp))
|
||||
|
||||
return (
|
||||
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
|
||||
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
|
||||
<Hero hero={f?.hero} today={today.data} ranked={stories} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */}
|
||||
{stories.length ? <Stories items={stories} /> : load === 'loading' ? <StoriesSkel /> : <StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<StoriesSkel />} className="inset-x-3 top-3 bottom-1" />}
|
||||
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
|
||||
<FeedComposer onPosted={(t) => setMine((m) => [t, ...m])} />
|
||||
{mine.map((t) => (
|
||||
<TalkCard key={t.talk_id} t={t} onGone={() => setMine((m) => m.filter((x) => x.talk_id !== t.talk_id))} />
|
||||
))}
|
||||
{raining && group(TalkTopic.RAIN)}
|
||||
<MyGakRow />
|
||||
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */}
|
||||
{stories.some((g) => g.active) ? (
|
||||
<GakCard items={stories} post={f?.gak_post} place={region.name.split(' ').at(-1)!} at={sloted ? `${PREVIEW[preview].label} 기준` : nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} />
|
||||
) : load === 'loading' ? (
|
||||
<PostCardSkel />
|
||||
) : (
|
||||
<StateBox load={load} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." hold={<PostCardSkel />} className="inset-x-3 top-3 bottom-1" />
|
||||
)}
|
||||
<NearTalks talks={groupOf(0)} loaded={talkGroups.loaded} />
|
||||
<InstallBanner />
|
||||
<div>
|
||||
{load === 'loading' && <PostsSkel />}
|
||||
{/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */}
|
||||
@@ -342,9 +665,15 @@ export function TodayPage() {
|
||||
{posts.map((p, i) => (
|
||||
<Fragment key={p.post_id}>
|
||||
<PostCard post={p} />
|
||||
{i === sunsetAt && group(TalkTopic.SKY)}
|
||||
{i === 1 && <FoliageCard post={f?.foliage_post} />}
|
||||
{i === 1 && group(TalkTopic.FOLIAGE)}
|
||||
{bandAt.find(([at]) => at === i + 1)?.[1]}
|
||||
{spreadAt.get(i)}
|
||||
</Fragment>
|
||||
))}
|
||||
{/* 글이 모자라 끼울 자리가 없던 묶음은 맨 뒤에 */}
|
||||
{feed.isSuccess && spreadLeft}
|
||||
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
+20
-9
@@ -22,11 +22,12 @@
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* 하늘에서 떨어진 뒤 둥둥 */
|
||||
/* 하늘에서 떨어진 뒤(.b-fall) 둥둥(.b-bob, 그 안쪽 요소). 한 요소에 transform 애니메이션 둘이 겹치면 GPU로 못 넘겨 매 프레임 메인 스레드가 일한다 */
|
||||
.b-fall {
|
||||
animation:
|
||||
b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) both,
|
||||
b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
|
||||
animation: b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) backwards;
|
||||
}
|
||||
.b-bob {
|
||||
animation: b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
|
||||
}
|
||||
@keyframes b-drop {
|
||||
0% {
|
||||
@@ -53,7 +54,7 @@
|
||||
transform: translateY(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(calc(var(--amp, 9px) * -1)) rotate(var(--tilt, 1.2deg));
|
||||
transform: translateY(-9px) rotate(1.2deg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -509,6 +510,9 @@
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 0 6px rgb(255 255 255 / 0.8);
|
||||
}
|
||||
/* 별은 밤에만 보이니 반짝임·별똥별도 밤에만 돌린다 (낮에 안 보이는 채로 돌면 매 프레임 일을 한다) */
|
||||
.b-skybg[data-t='night'] .b-skystars i {
|
||||
animation: b-twinkle var(--tw, 5s) ease-in-out infinite;
|
||||
animation-delay: var(--dl, 0s);
|
||||
}
|
||||
@@ -523,8 +527,14 @@
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(90deg, rgb(255 255 255 / 0), #fff);
|
||||
opacity: 0;
|
||||
}
|
||||
:is(.b-skybg, .b-hero)[data-t='night'] .b-shoot {
|
||||
animation: b-shoot var(--dur, 8s) ease-in var(--dl, 0s) infinite;
|
||||
}
|
||||
/* 아래 창이 열려 있는 동안 뒤 화면 움직임은 멈춘다 (창이 버벅이지 않게) */
|
||||
html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot, .b-stars i) {
|
||||
animation-play-state: paused !important;
|
||||
}
|
||||
@keyframes b-shoot {
|
||||
0%, 86% { opacity: 0; transform: rotate(-24deg) translateX(0); }
|
||||
89% { opacity: 1; }
|
||||
@@ -543,13 +553,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* 위·아래 바는 반투명으로 하늘이 비치게 */
|
||||
/* 위 바는 반투명으로 하늘이 비치게, 아래 탭 바는 홈 바 자리까지 글이 비치지 않게 불투명 */
|
||||
.b-topbg {
|
||||
background: rgb(255 255 255 / 0.18);
|
||||
transition: background 1.4s ease;
|
||||
}
|
||||
.b-tabbar {
|
||||
background: rgb(255 255 255 / 0.6);
|
||||
background: #f7faff;
|
||||
overflow: visible;
|
||||
border-color: rgb(255 255 255 / 0.4);
|
||||
}
|
||||
@@ -557,7 +567,7 @@
|
||||
background: rgb(14 20 51 / 0.35);
|
||||
}
|
||||
.b-app[data-t='night'] .b-tabbar {
|
||||
background: rgb(18 24 60 / 0.62);
|
||||
background: #121838;
|
||||
border-color: rgb(255 255 255 / 0.08);
|
||||
}
|
||||
|
||||
@@ -601,7 +611,8 @@
|
||||
.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 '@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]'
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import type { PostReaction } from '@nalssigak/shared/api/client/types.gen'
|
||||
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'
|
||||
|
||||
const TAP_R = 24
|
||||
const RANK_N = 7
|
||||
|
||||
/** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */
|
||||
export function FoliageCard({ post }: { post?: PostReaction | null }) {
|
||||
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 { 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" pinned={{ key: 'foliage_post', post }} 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">{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>
|
||||
<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>
|
||||
)
|
||||
}
|
||||
@@ -76,8 +76,7 @@ export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) =>
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div ref={box} className="flex min-h-[44px] justify-center" aria-busy={login.isPending} />
|
||||
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 아이디로 로그인해 주세요.</p>}
|
||||
<p className="m-0 flex items-center gap-2 text-[12.5px] font-bold text-(--ink3) before:h-px before:flex-1 before:bg-(--line) after:h-px after:flex-1 after:bg-(--line)">또는 아이디로</p>
|
||||
{broken && <p className="m-0 text-center text-[13px] font-bold text-(--ink3)">구글 로그인을 불러오지 못했어요. 잠시 뒤에 다시 해 주세요.</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import { track } from '../lib/analytics'
|
||||
import { useSheet } from './sheetContext'
|
||||
|
||||
type InstallPromptEvent = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }> }
|
||||
|
||||
const DISMISS_KEY = 'nalssigak.b.installDismissed'
|
||||
const DISMISS_DAYS = 14
|
||||
|
||||
// 안드로이드 Chrome 은 설치할 수 있을 때 이 이벤트를 한 번 준다. 앱이 뜨기 전에 올 수 있어 모듈을 불러올 때 바로 받아 둔다
|
||||
let deferred: InstallPromptEvent | null = null
|
||||
const listeners = new Set<() => void>()
|
||||
const notify = () => listeners.forEach((cb) => cb())
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('beforeinstallprompt', (e) => {
|
||||
e.preventDefault()
|
||||
deferred = e as InstallPromptEvent
|
||||
notify()
|
||||
})
|
||||
window.addEventListener('appinstalled', () => {
|
||||
deferred = null
|
||||
track('install_done', {})
|
||||
notify()
|
||||
})
|
||||
}
|
||||
|
||||
export type Platform = 'standalone' | 'inapp' | 'ios' | 'android' | 'other'
|
||||
|
||||
/** 지금 이 기기에서 홈 화면 추가를 어떻게 안내할지 */
|
||||
export function platform(): Platform {
|
||||
const ua = navigator.userAgent
|
||||
if (window.matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone) return 'standalone'
|
||||
if (/KAKAOTALK|Instagram|FBAN|FBAV|NAVER\(inapp|; wv\)|Line\//i.test(ua)) return 'inapp'
|
||||
if (/iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return 'ios'
|
||||
if (/Android/.test(ua)) return 'android'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
const onPhone = () => ['ios', 'android', 'inapp'].includes(platform())
|
||||
|
||||
/** 설치를 권할 곳: 휴대폰 브라우저, 그리고 설치창을 띄울 수 있는 PC 브라우저(Chrome·Edge). PC Safari·Firefox 와 이미 설치해 연 화면은 뺀다 */
|
||||
export function useInstallable() {
|
||||
const canPrompt = useCanPrompt()
|
||||
return platform() !== 'standalone' && (onPhone() || canPrompt)
|
||||
}
|
||||
|
||||
/** 설치창을 바로 띄울 수 있는지 (안드로이드 Chrome 등) */
|
||||
export function useCanPrompt() {
|
||||
return useSyncExternalStore(
|
||||
(cb) => {
|
||||
listeners.add(cb)
|
||||
return () => listeners.delete(cb)
|
||||
},
|
||||
() => deferred != null,
|
||||
)
|
||||
}
|
||||
|
||||
/** 설치창을 띄운다. 띄웠으면 true */
|
||||
export async function promptInstall(): Promise<boolean> {
|
||||
if (!deferred) return false
|
||||
const e = deferred
|
||||
deferred = null
|
||||
notify()
|
||||
try {
|
||||
await e.prompt()
|
||||
} catch (err) {
|
||||
// 이미 한 번 띄웠거나 브라우저가 막으면 안내 창으로 넘긴다
|
||||
console.warn('[install] prompt', err)
|
||||
return false
|
||||
}
|
||||
const { outcome } = await e.userChoice
|
||||
track('install_choice', { outcome })
|
||||
return true
|
||||
}
|
||||
|
||||
export function dismissed(): boolean {
|
||||
try {
|
||||
const at = Number(localStorage.getItem(DISMISS_KEY))
|
||||
return at > 0 && Date.now() - at < DISMISS_DAYS * 86_400_000
|
||||
} catch {
|
||||
// 저장소를 못 쓰는 브라우저에선 이번 방문 동안만 보인다
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function dismiss() {
|
||||
try {
|
||||
localStorage.setItem(DISMISS_KEY, String(Date.now()))
|
||||
} catch (e) {
|
||||
console.warn('[install] 닫은 시각을 저장하지 못함', e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 홈 화면에 추가: 설치창을 띄울 수 있으면 띄우고, 아니면 기기별 안내 창을 연다 */
|
||||
export function useInstall() {
|
||||
const { open } = useSheet()
|
||||
const canPrompt = useCanPrompt()
|
||||
return async (from: 'banner' | 'menu') => {
|
||||
const shown = canPrompt && (await promptInstall())
|
||||
track('install_click', { from, method: shown ? 'prompt' : 'guide' })
|
||||
if (!shown) open({ type: 'install' })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import { track } from '../lib/analytics'
|
||||
import { dismiss, dismissed, platform, promptInstall, useCanPrompt, useInstall, useInstallable } from './install'
|
||||
|
||||
const SITE = 'https://weather.o2o.kr'
|
||||
|
||||
/** 오늘 탭의 작은 설치 카드. 오늘의 각까지 본 뒤 자리에 놓고, 설치할 수 있는 곳(휴대폰, PC Chrome·Edge)에서만 보인다. 닫으면 2주 숨긴다 */
|
||||
export function InstallBanner() {
|
||||
const install = useInstall()
|
||||
const installable = useInstallable()
|
||||
const [closed, setClosed] = useState(dismissed)
|
||||
const hidden = !installable || closed
|
||||
|
||||
useEffect(() => {
|
||||
if (!hidden) track('install_banner_view', {})
|
||||
}, [hidden])
|
||||
|
||||
if (hidden) return null
|
||||
return (
|
||||
<aside aria-label="홈 화면에 추가" className="mx-3 mt-3.5 flex items-center gap-3 rounded-[22px] bg-white p-3.5 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<img src="/app/icon-192.png" alt="" className="size-12 shrink-0 rounded-[14px]" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="m-0 font-jua text-[16.5px] leading-snug">내일도 우산각·빨래각, 바로 확인하세요</p>
|
||||
<p className="m-0 mt-0.5 text-[12.5px] font-semibold text-(--ink2)">날씨각을 홈 화면에 추가하고 한 번에 열어보세요.</p>
|
||||
<div className="mt-2 flex gap-1.5">
|
||||
<button type="button" onClick={() => install('banner')} className="cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">
|
||||
📲 홈 화면에 추가
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
dismiss()
|
||||
setClosed(true)
|
||||
}}
|
||||
className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2)"
|
||||
>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function Steps({ items }: { items: ReactNode[] }) {
|
||||
return (
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{items.map((t, i) => (
|
||||
<li key={i} className="flex items-start gap-2.5 rounded-2xl bg-[#f3f6fb] px-3.5 py-3 text-[14.5px] font-bold">
|
||||
<b className="grid size-6 shrink-0 place-items-center rounded-full bg-(--orange) font-jua text-[14px] font-normal text-white">{i + 1}</b>
|
||||
<span>{t}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)
|
||||
}
|
||||
|
||||
// 사파리 아래 가운데 공유 버튼과 공유 목록의 '홈 화면에 추가' 모양 그대로
|
||||
const ShareGlyph = () => (
|
||||
<svg viewBox="0 0 24 24" className="mx-0.5 inline size-[22px] -translate-y-0.5 fill-none stroke-[#2f7cf6] stroke-2 [stroke-linecap:round] [stroke-linejoin:round]" aria-label="공유 버튼">
|
||||
<path d="M12 3v12M8 7l4-4 4 4M6 11H5v10h14V11h-1" />
|
||||
</svg>
|
||||
)
|
||||
const AddGlyph = () => (
|
||||
<svg viewBox="0 0 24 24" className="mx-0.5 inline size-[22px] -translate-y-0.5 fill-none stroke-(--ink) stroke-2 [stroke-linecap:round]" aria-hidden="true">
|
||||
<rect x="4" y="4" width="16" height="16" rx="4" />
|
||||
<path d="M12 8v8M8 12h8" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
/** 설치창을 띄울 수 없는 기기의 안내. 안드로이드는 열어 둔 사이 크롬이 설치를 허락하면 바로 설치 버튼으로 바뀐다 */
|
||||
export function InstallSheet() {
|
||||
const p = platform()
|
||||
const canPrompt = useCanPrompt()
|
||||
const [copied, setCopied] = useState(false)
|
||||
const copy = () =>
|
||||
navigator.clipboard.writeText(SITE).then(
|
||||
() => setCopied(true),
|
||||
(e: unknown) => console.error('[install] copy', e),
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
|
||||
{p === 'standalone' && <p className="m-0 text-[15px] font-bold">이미 홈 화면에서 열었어요. 다음에도 아이콘을 눌러 바로 여세요.</p>}
|
||||
{p === 'ios' && (
|
||||
<>
|
||||
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">아이폰은 Safari에서 이렇게 추가해요.</p>
|
||||
<Steps
|
||||
items={[
|
||||
<>화면 아래 <ShareGlyph /> 공유 버튼을 눌러요. 안 보이면 오른쪽 아래 ··· 를 누른 뒤 공유</>,
|
||||
<>목록을 올려 <AddGlyph /> 홈 화면에 추가를 눌러요</>,
|
||||
"오른쪽 위 '추가'를 누르면 끝이에요",
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{p === 'android' && canPrompt && (
|
||||
<button type="button" onClick={() => void promptInstall()} className="w-full cursor-pointer rounded-full bg-(--orange) py-3 font-jua text-[17px] text-white">
|
||||
📲 지금 설치하기
|
||||
</button>
|
||||
)}
|
||||
{p === 'android' && !canPrompt && (
|
||||
<>
|
||||
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">지금 브라우저에선 설치창을 바로 띄울 수 없어요. 메뉴에서 추가해 주세요.</p>
|
||||
<Steps items={['오른쪽 위 ⋮ 메뉴를 눌러요', "'홈 화면에 추가' 또는 '앱 설치'를 눌러요", "'추가' 또는 '설치'를 누르면 끝이에요"]} />
|
||||
</>
|
||||
)}
|
||||
{p === 'inapp' && (
|
||||
<>
|
||||
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">카카오톡 같은 앱 안에서는 홈 화면에 추가할 수 없어요. Safari나 Chrome에서 열어 주세요.</p>
|
||||
<Steps items={["오른쪽 위 ⋮ 또는 공유 버튼에서 '다른 브라우저로 열기'를 눌러요", '안 보이면 아래 주소를 복사해 Safari·Chrome에 붙여 넣어요', "열린 화면에서 '홈 화면에 추가'를 눌러요"]} />
|
||||
</>
|
||||
)}
|
||||
{p === 'other' && (
|
||||
<>
|
||||
<p className="m-0 mb-3 text-[14px] font-semibold text-(--ink2)">휴대폰에서 열면 홈 화면에 추가할 수 있어요.</p>
|
||||
<Steps items={['휴대폰 Safari(아이폰)나 Chrome(갤럭시)에서 아래 주소를 열어요', "공유 버튼이나 ⋮ 메뉴에서 '홈 화면에 추가'를 눌러요"]} />
|
||||
</>
|
||||
)}
|
||||
{(p === 'inapp' || p === 'other') && (
|
||||
<div className="mt-3 flex items-center gap-2 rounded-2xl border border-(--line) px-3.5 py-2.5">
|
||||
<span className="min-w-0 flex-1 truncate text-[14.5px] font-bold select-all">{SITE}</span>
|
||||
<button type="button" onClick={copy} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
|
||||
{copied ? '복사함' : '주소 복사'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
import { ARTICLE_LABEL } from '@nalssigak/shared/lib'
|
||||
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain', 'hangang', 'themepark', 'date', 'frizz', 'boiler', 'sunscreen', 'mosquito', 'tennis', 'hyodo', 'thanks', 'gift', 'party', 'game', 'selfie', 'sentimental', 'ginkgo'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
|
||||
@@ -11,6 +11,6 @@ export function iconSrc(name: string) {
|
||||
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
||||
}
|
||||
|
||||
export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties
|
||||
export const fall = (d: string, f = '4.8s') => ({ '--d': d, '--f': f }) as CSSProperties
|
||||
|
||||
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: [ARTICLE_LABEL[1], 'text-[#1f9d62]'], 2: [ARTICLE_LABEL[2], 'text-[#7a5cd6]'], 3: [ARTICLE_LABEL[3], 'text-(--orange)'] }
|
||||
@@ -0,0 +1,235 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import type { MyGakPreset, MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { gakName, shareUrl, SLOTS, type MyGak, type Slot, useMyGak, useMyGakScores, usePresets } from './myGakState'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, Rail, Sec } from './ui'
|
||||
|
||||
const SLOT_WORD = Object.fromEntries(SLOTS) as Record<Slot, string>
|
||||
|
||||
function Score({ s, big }: { s?: MyGakScore; big?: boolean }) {
|
||||
const v = s?.score
|
||||
return (
|
||||
<em className={cx('ml-auto font-bagel leading-none not-italic', big ? 'text-[36px]' : 'text-[28px]', v == null || v < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>
|
||||
{v ?? '–'}
|
||||
</em>
|
||||
)
|
||||
}
|
||||
|
||||
function Reasons({ s }: { s?: MyGakScore }) {
|
||||
if (!s?.slot) return <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">예보를 불러오는 중이에요</p>
|
||||
return (
|
||||
<p className="m-0 text-[12.5px] leading-snug font-semibold text-(--ink2)">
|
||||
<b className="mr-1 text-(--ink)">{SLOT_WORD[s.slot as Slot]}</b>
|
||||
{s.reasons?.join(' · ')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
/** 오늘 탭의 내 각 줄: 내가 정한 조건으로 매긴 오늘 점수 */
|
||||
export function MyGakRow() {
|
||||
const { open } = useSheet()
|
||||
const { items, remove } = useMyGak()
|
||||
const scores = useMyGakScores(items.map((g) => g.rule)).data?.scores ?? []
|
||||
const [copied, setCopied] = useState<number | null>(null)
|
||||
const send = (g: MyGak, i: number) => {
|
||||
const url = shareUrl(g)
|
||||
if (navigator.share) {
|
||||
navigator.share({ title: `${g.name} · 날씨각`, url }).catch((e: unknown) => {
|
||||
if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e)
|
||||
})
|
||||
return
|
||||
}
|
||||
navigator.clipboard.writeText(url).then(
|
||||
() => setCopied(i),
|
||||
(e: unknown) => console.error('[myGak] copy', e),
|
||||
)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Sec title="내 각" sub="내가 정한 날씨 조건으로 오늘 점수를 매겨요" />
|
||||
<Rail label="내 각">
|
||||
{items.map((g, i) => (
|
||||
<div key={g.id ?? 'local'} className="flex w-[220px] flex-col gap-1.5 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<div className="flex items-center gap-1">
|
||||
<b className="font-jua text-[17px] leading-tight font-normal">{g.name}</b>
|
||||
<Score s={scores[i]} />
|
||||
</div>
|
||||
<Reasons s={scores[i]} />
|
||||
<div className="mt-auto flex gap-1.5 pt-0.5">
|
||||
<button type="button" onClick={() => send(g, i)} className="cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-[12.5px] font-extrabold text-white">
|
||||
{copied === i ? '링크 복사함' : '친구에게 보내기'}
|
||||
</button>
|
||||
<button type="button" onClick={() => remove(g)} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[12.5px] font-extrabold text-(--ink2)">
|
||||
지우기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" onClick={() => open({ type: 'mix' })} className="flex w-[120px] cursor-pointer flex-col items-center justify-center gap-1 rounded-[22px] border-2 border-dashed border-(--line) p-3 font-jua text-[15px] text-(--ink2)">
|
||||
<span className="text-[26px] leading-none">+</span>
|
||||
내 각 만들기
|
||||
</button>
|
||||
</Rail>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ label, on, onToggle, children }: { label: string; on: boolean; onToggle: () => void; children: ReactNode }) {
|
||||
return (
|
||||
<div className={cx('flex min-h-[44px] flex-wrap items-center gap-2 border-b border-(--line) py-2', !on && 'opacity-60')}>
|
||||
<label className="flex w-[84px] cursor-pointer items-center gap-1.5 text-[14px] font-extrabold">
|
||||
<input type="checkbox" checked={on} onChange={onToggle} className="size-4 accent-(--orange)" />
|
||||
{label}
|
||||
</label>
|
||||
{on ? <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 text-[13.5px] font-bold">{children}</div> : <span className="text-[13px] font-semibold text-(--ink3)">상관없음</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Num({ value, onChange, min, max, label }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string }) {
|
||||
return (
|
||||
<input
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
aria-label={label}
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
onChange={(e) => {
|
||||
const v = Number(e.target.value)
|
||||
if (e.target.value !== '' && Number.isFinite(v)) onChange(Math.min(max, Math.max(min, v)))
|
||||
}}
|
||||
className="w-[58px] rounded-xl bg-[#f3f6fb] px-2 py-1.5 text-center tabular-nums"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Choice<T extends string>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<span className="flex gap-1" role="radiogroup" aria-label={label}>
|
||||
{options.map(([k, word]) => (
|
||||
<button key={k} type="button" role="radio" aria-checked={value === k} onClick={() => onChange(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', value === k ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
|
||||
{word}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
type Filled<T> = { [K in keyof T]-?: NonNullable<T[K]> }
|
||||
const DEFAULT_RULE: Filled<MyGakRule> = { temp: [15, 25], rain: 'dry', wind_max: 4, air: 'normal', humidity: [30, 60], slots: ['morning', 'day', 'evening', 'night'] }
|
||||
type Cond = 'temp' | 'rain' | 'wind_max' | 'air' | 'humidity'
|
||||
|
||||
const condsOf = (r: MyGakRule): Record<Cond, boolean> => ({ temp: !!r.temp, rain: !!r.rain, wind_max: r.wind_max != null, air: !!r.air, humidity: !!r.humidity })
|
||||
|
||||
/** 있는 각을 골라 그 각 조건으로 채운다 */
|
||||
function PresetPicker({ picked, onPick }: { picked: string | null; onPick: (p: MyGakPreset) => void }) {
|
||||
const items = usePresets().data ?? []
|
||||
if (!items.length) return null
|
||||
return (
|
||||
<div className="mb-3">
|
||||
<span className="font-jua text-[19px]">있는 각에서 불러오기</span>
|
||||
<div className="-mx-4">
|
||||
<Rail label="있는 각에서 불러오기">
|
||||
{items.map((p) => (
|
||||
<button
|
||||
key={p.code}
|
||||
type="button"
|
||||
aria-pressed={picked === p.code}
|
||||
onClick={() => onPick(p)}
|
||||
className={cx('flex w-[68px] cursor-pointer flex-col items-center gap-1 rounded-2xl px-1 py-2 text-[12px] leading-tight font-extrabold', picked === p.code ? 'bg-(--orange) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
|
||||
>
|
||||
<Ic name={p.icon} className="size-9" />
|
||||
<span className="w-full truncate">{p.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 내 각 만들기(이름과 조건)와 미리보기. shared 면 받은 각을 내 동네 점수로 보여 주고 가져오기만 */
|
||||
export function MixSheet({ shared, onDone }: { shared?: MyGak; onDone: () => void }) {
|
||||
const { region } = useRegion()
|
||||
const { create, pending, failed } = useMyGak()
|
||||
const [name, setName] = useState(shared?.name ?? '')
|
||||
const [vals, setVals] = useState({ ...DEFAULT_RULE, ...(shared?.rule ?? {}) } as typeof DEFAULT_RULE)
|
||||
const [on, setOn] = useState<Record<Cond, boolean>>(shared ? condsOf(shared.rule) : { temp: true, rain: true, wind_max: false, air: false, humidity: false })
|
||||
const [picked, setPicked] = useState<string | null>(null)
|
||||
const pick = (p: MyGakPreset) => {
|
||||
setPicked(p.code)
|
||||
setName(p.name)
|
||||
setVals({ ...DEFAULT_RULE, ...p.rule } as typeof DEFAULT_RULE)
|
||||
setOn(condsOf(p.rule))
|
||||
}
|
||||
const set = <K extends keyof typeof vals>(k: K, v: (typeof vals)[K]) => setVals((x) => ({ ...x, [k]: v }))
|
||||
const toggle = (k: Cond) => setOn((x) => ({ ...x, [k]: !x[k] }))
|
||||
const rule: MyGakRule = { slots: vals.slots, ...(Object.fromEntries((Object.keys(on) as Cond[]).filter((k) => on[k]).map((k) => [k, vals[k]])) as Partial<MyGakRule>) }
|
||||
const valid = Object.values(on).some(Boolean) && vals.slots.length > 0 && (!on.temp || vals.temp[0] < vals.temp[1]) && (!on.humidity || vals.humidity[0] < vals.humidity[1])
|
||||
const score = useMyGakScores(valid ? [rule] : []).data?.scores?.[0]
|
||||
const title = gakName(name) || '이름 없는 각'
|
||||
const toggleSlot = (s: Slot) => set('slots', vals.slots.includes(s) ? vals.slots.filter((x) => x !== s) : SLOTS.map(([k]) => k).filter((k) => k === s || vals.slots.includes(k)))
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-3.5 pb-[18px]">
|
||||
{shared ? (
|
||||
<p className="m-0 text-[13px] font-bold text-(--ink2)">친구가 보낸 각이에요. {region.name} 기준 점수예요</p>
|
||||
) : (
|
||||
<>
|
||||
<PresetPicker picked={picked} onPick={pick} />
|
||||
<label className="block">
|
||||
<span className="font-jua text-[19px]">이름</span>
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} maxLength={11} placeholder="소맥, 야독, 새우깡" className="mt-1.5 w-full rounded-2xl bg-[#f3f6fb] px-3.5 py-2.5 text-[15px]" />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
<fieldset disabled={!!shared} className="m-0 mt-3 border-0 p-0">
|
||||
<legend className="font-jua text-[19px]">조건</legend>
|
||||
<Row label="기온" on={on.temp} onToggle={() => toggle('temp')}>
|
||||
<Num label="최저 기온" value={vals.temp[0]} min={-20} max={40} onChange={(v) => set('temp', [v, vals.temp[1]])} />~
|
||||
<Num label="최고 기온" value={vals.temp[1]} min={-20} max={40} onChange={(v) => set('temp', [vals.temp[0], v])} />° 체감
|
||||
</Row>
|
||||
<Row label="비" on={on.rain} onToggle={() => toggle('rain')}>
|
||||
<Choice label="비" value={vals.rain} onChange={(v) => set('rain', v)} options={[['dry', '안 와야'], ['wet', '와야']]} />
|
||||
</Row>
|
||||
<Row label="바람" on={on.wind_max} onToggle={() => toggle('wind_max')}>
|
||||
초속 <Num label="바람 상한" value={vals.wind_max} min={1} max={20} onChange={(v) => set('wind_max', v)} />m 이하
|
||||
</Row>
|
||||
<Row label="미세먼지" on={on.air} onToggle={() => toggle('air')}>
|
||||
<Choice label="미세먼지" value={vals.air} onChange={(v) => set('air', v)} options={[['good', '좋음만'], ['normal', '보통까지']]} />
|
||||
</Row>
|
||||
<Row label="습도" on={on.humidity} onToggle={() => toggle('humidity')}>
|
||||
<Num label="최저 습도" value={vals.humidity[0]} min={0} max={100} onChange={(v) => set('humidity', [v, vals.humidity[1]])} />~
|
||||
<Num label="최고 습도" value={vals.humidity[1]} min={0} max={100} onChange={(v) => set('humidity', [vals.humidity[0], v])} />%
|
||||
</Row>
|
||||
<div className="flex flex-wrap items-center gap-1.5 py-2.5 text-[13.5px] font-bold">
|
||||
<span className="w-[84px] text-[14px] font-extrabold">시간대</span>
|
||||
{SLOTS.map(([k, word]) => (
|
||||
<button key={k} type="button" aria-pressed={vals.slots.includes(k)} onClick={() => toggleSlot(k)} className={cx('cursor-pointer rounded-full px-3 py-1.5', vals.slots.includes(k) ? 'bg-(--orange) text-white' : 'bg-[#eef4fc]')}>
|
||||
{word}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<div className="mt-2 flex flex-col gap-1.5 rounded-[20px] bg-[#f3f6fb] p-3.5">
|
||||
<div className="flex items-center">
|
||||
<b className="font-jua text-[20px] font-normal">{title}</b>
|
||||
<Score s={valid ? score : undefined} big />
|
||||
</div>
|
||||
{valid ? <Reasons s={score} /> : <p className="m-0 text-[12.5px] font-semibold text-(--ink3)">조건과 시간대를 하나 이상 골라요</p>}
|
||||
</div>
|
||||
{failed && <p className="mt-2 mb-0 text-xs font-bold text-(--heart)">저장하지 못했어요. 이름에 링크나 긴 숫자가 있으면 빼 주세요</p>}
|
||||
<button
|
||||
type="button"
|
||||
disabled={!valid || !gakName(name) || pending}
|
||||
onClick={() => create({ name, rule }, onDone)}
|
||||
className="mt-3.5 w-full cursor-pointer rounded-2xl bg-(--orange) py-3 font-jua text-[17px] text-white disabled:cursor-default disabled:opacity-45"
|
||||
>
|
||||
{shared ? '내 각으로 가져오기' : '내 각으로 저장'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useSyncExternalStore } from 'react'
|
||||
import { SITE_URL } from '../api/setup'
|
||||
import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey, listPresetsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { scoreMyGak } from '@nalssigak/shared/api/client/sdk.gen'
|
||||
import type { MyGakRule, MyGakScore } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { useAuth } from './authContext'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
|
||||
const KEY = 'nalssigak.b.myRule'
|
||||
|
||||
export type Slot = 'morning' | 'day' | 'evening' | 'night'
|
||||
export const SLOTS: [Slot, string][] = [
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['evening', '저녁'],
|
||||
['night', '밤'],
|
||||
]
|
||||
|
||||
/** 내 각 하나. 로그인하지 않으면 이 기기에 하나만(id 없음) */
|
||||
export type MyGak = { id?: number; name: string; rule: MyGakRule }
|
||||
|
||||
function readLocal(): MyGak | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY)
|
||||
return raw ? (JSON.parse(raw) as MyGak) : null
|
||||
} catch {
|
||||
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 시트와 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다
|
||||
let local = readLocal()
|
||||
const listeners = new Set<() => void>()
|
||||
const subscribe = (cb: () => void) => {
|
||||
listeners.add(cb)
|
||||
return () => listeners.delete(cb)
|
||||
}
|
||||
|
||||
function setLocal(g: MyGak | null) {
|
||||
local = g
|
||||
listeners.forEach((cb) => cb())
|
||||
try {
|
||||
if (g) localStorage.setItem(KEY, JSON.stringify(g))
|
||||
else localStorage.removeItem(KEY)
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 기기에 저장하지 못함', e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 이름 끝에 '각'을 붙인다 (서버와 같은 규칙) */
|
||||
export const gakName = (name: string) => {
|
||||
const n = name.trim().replace(/\s+/g, ' ')
|
||||
return n && !n.endsWith('각') ? `${n}각` : n
|
||||
}
|
||||
|
||||
/** 받은 링크(/?my=...)에 이름과 조건을 그대로 담는다 */
|
||||
export function shareUrl(g: MyGak) {
|
||||
const json = JSON.stringify({ n: g.name, r: g.rule })
|
||||
const b64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)))
|
||||
return `${SITE_URL}/?my=${b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
|
||||
}
|
||||
|
||||
export function fromShare(code: string): MyGak | null {
|
||||
try {
|
||||
const bin = atob(code.replace(/-/g, '+').replace(/_/g, '/'))
|
||||
const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)))) as { n?: unknown; r?: unknown }
|
||||
return typeof v.n === 'string' && v.r && typeof v.r === 'object' ? { name: v.n, rule: v.r as MyGakRule } : null
|
||||
} catch (e) {
|
||||
console.warn('[myGak] 받은 링크를 읽지 못함', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 조건들의 우리 동네 오늘 점수. 조건이 같으면 캐시를 같이 쓴다 */
|
||||
export function useMyGakScores(rules: MyGakRule[]) {
|
||||
const { region } = useRegion()
|
||||
return useQuery({
|
||||
queryKey: ['myGakScore', region.code, rules],
|
||||
enabled: rules.length > 0,
|
||||
staleTime: 5 * 60_000,
|
||||
queryFn: async (): Promise<{ nowSlot?: Slot | null; scores: MyGakScore[] }> => {
|
||||
const { data } = await scoreMyGak({ body: { region_code: region.code, rules } })
|
||||
if (!data.result?.success) throw new Error(data.result?.desc ?? 'score')
|
||||
return { nowSlot: data.now_slot, scores: data.scores ?? [] }
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** 공식 각을 내 각 조건으로 옮긴 목록 (내 각 만들기에서 골라 채우기) */
|
||||
export function usePresets() {
|
||||
return useQuery({ ...listPresetsOptions(), staleTime: Infinity, select: (d) => d.items ?? [] })
|
||||
}
|
||||
|
||||
export function useMyGak() {
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const queryClient = useQueryClient()
|
||||
const q = useQuery({ ...listMyGakOptions(), enabled: loggedIn })
|
||||
const saved = useSyncExternalStore(subscribe, () => local)
|
||||
const refresh = () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() })
|
||||
const add = useMutation({ ...addMyGakMutation(), onSuccess: refresh })
|
||||
const del = useMutation({ ...deleteMyGakMutation(), onSuccess: refresh })
|
||||
|
||||
// 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다
|
||||
const { mutate } = add
|
||||
useEffect(() => {
|
||||
if (!loggedIn || !saved) return
|
||||
mutate({ body: { name: saved.name, rule: saved.rule } }, { onSuccess: () => setLocal(null) })
|
||||
}, [loggedIn, saved, mutate])
|
||||
|
||||
const items: MyGak[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, name: g.name, rule: g.rule })) : saved ? [saved] : []
|
||||
|
||||
/** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */
|
||||
const create = (g: MyGak, onDone?: () => void) => {
|
||||
const item = { name: gakName(g.name), rule: g.rule }
|
||||
if (loggedIn) {
|
||||
add.mutate({ body: item }, { onSuccess: (res) => res.result?.success && onDone?.() })
|
||||
return
|
||||
}
|
||||
if (saved) {
|
||||
open({ type: 'login' })
|
||||
return
|
||||
}
|
||||
setLocal(item)
|
||||
onDone?.()
|
||||
}
|
||||
|
||||
const remove = (g: MyGak) => {
|
||||
if (g.id != null) return del.mutate({ path: { my_gak_id: g.id } })
|
||||
setLocal(null)
|
||||
}
|
||||
|
||||
return { items, create, remove, pending: add.isPending, failed: add.data?.result?.success === false }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { likePostMutation, unlikePostMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import type { PostReaction, ResFeed } from '@nalssigak/shared/api/client/types.gen'
|
||||
|
||||
export type PinnedKey = 'hero_post' | 'gak_post' | 'foliage_post' | 'events_post' | 'season_post'
|
||||
|
||||
/** 히어로·오늘의 각·단풍 지도·띠처럼 포스트 틀이 아닌 카드의 좋아요. 화면을 먼저 바꾸고 실패하면 되돌린다 */
|
||||
export function usePinnedLike(key: PinnedKey, r?: PostReaction | null) {
|
||||
const queryClient = useQueryClient()
|
||||
const like = useMutation(likePostMutation())
|
||||
const unlike = useMutation(unlikePostMutation())
|
||||
const [failed, setFailed] = useState(false)
|
||||
const liked = !!r?.liked
|
||||
const count = r?.like_count ?? 0
|
||||
const patch = (values: Partial<PostReaction>) =>
|
||||
queryClient.setQueriesData<ResFeed>({ predicate: (q) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'getFeed' }, (feed) =>
|
||||
feed?.[key] && feed[key].post_id === r?.post_id ? { ...feed, [key]: { ...feed[key], ...values } } : feed,
|
||||
)
|
||||
const toggle = () => {
|
||||
if (!r || like.isPending || unlike.isPending) return
|
||||
const on = !liked
|
||||
setFailed(false)
|
||||
patch({ liked: on, like_count: count + (on ? 1 : -1) })
|
||||
const revert = () => {
|
||||
patch({ liked, like_count: count })
|
||||
setFailed(true)
|
||||
}
|
||||
;(on ? like : unlike).mutate(
|
||||
{ path: { post_id: r.post_id } },
|
||||
{
|
||||
onSuccess: (res) => (res.result?.success ? patch({ liked: res.liked ?? on, ...(res.like_count != null ? { like_count: res.like_count } : {}) }) : revert()),
|
||||
onError: revert,
|
||||
},
|
||||
)
|
||||
}
|
||||
return { liked, count, failed, toggle }
|
||||
}
|
||||
@@ -1,19 +1,19 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { matchPath, useLocation, useNavigate } from 'react-router'
|
||||
import { useLocation, useNavigate } from 'react-router'
|
||||
import regionPages from '../../seo/region.json'
|
||||
import { nearestRegion } from '@nalssigak/shared/api/client/sdk.gen'
|
||||
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { track } from '../lib/analytics'
|
||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||
import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
|
||||
type RegionPage = (typeof regionPages)[number]
|
||||
|
||||
/** /today/gyeonggi/seongnam 같은 지역 페이지 주소면 그 페이지 */
|
||||
/** /today/gyeonggi/seongnam, /tomorrow/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */
|
||||
function pageOf(pathname: string): RegionPage | undefined {
|
||||
const m = matchPath('/today/:sido/:place', pathname)
|
||||
return m ? regionPages.find((p) => p.path === `${m.params.sido}/${m.params.place}`) : undefined
|
||||
const path = pathname.match(/^\/(?:today|tomorrow)\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1]
|
||||
return path ? regionPages.find((p) => p.path === path) : undefined
|
||||
}
|
||||
|
||||
/** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */
|
||||
@@ -45,9 +45,11 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate()
|
||||
const page = pageOf(pathname)
|
||||
const pageRef = useRef(page)
|
||||
const dayRef = useRef(pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today')
|
||||
useEffect(() => {
|
||||
pageRef.current = page
|
||||
}, [page])
|
||||
dayRef.current = pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today'
|
||||
}, [page, pathname])
|
||||
const [stored] = useState(readStored)
|
||||
const [landing] = useState(page)
|
||||
const [chosen, setRegionState] = useState<RegionData>(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION)))
|
||||
@@ -60,8 +62,8 @@ export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
const next = regionPages.find((p) => p.regions.some((g) => g.code === r.code))
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`)
|
||||
const next = ownPage(r.code)
|
||||
if (pageRef.current && next && next !== pageRef.current) navigate(`/${dayRef.current}/${next.path}`)
|
||||
}, [navigate])
|
||||
|
||||
// quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import regionPages from '../../seo/region.json'
|
||||
|
||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||
|
||||
@@ -7,6 +8,9 @@ export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void
|
||||
|
||||
export { DEFAULT_REGION } from '@nalssigak/shared/lib'
|
||||
|
||||
/** 구 하나만 보여 주는 지역 페이지: 일반 시군구, 또는 구로 나뉜 시의 구 페이지 */
|
||||
export const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code)
|
||||
|
||||
export const RegionContext = createContext<RegionApi | null>(null)
|
||||
|
||||
export function useRegion() {
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import type { Ref } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { cx } from '../lib/utils'
|
||||
import type { TopIndex } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
|
||||
import { MEDALS, type TimeKind } from '@nalssigak/shared/lib'
|
||||
import { Ic } from './ui'
|
||||
|
||||
/** 공유 이미지 전용 틀. 화면 밖에 그려 두고 보내기 때 이것만 찍는다 (화면의 버튼은 이미지에서 빠지므로 글자만으로 만든다) */
|
||||
function Offscreen({ children }: { children: React.ReactNode }) {
|
||||
return createPortal(
|
||||
<div aria-hidden="true" className="pointer-events-none fixed top-0 -left-[10000px] w-[380px]">
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
export type DayShare = {
|
||||
kind: TimeKind
|
||||
label: string
|
||||
now: boolean
|
||||
icon: string
|
||||
temp: string
|
||||
score?: number | null
|
||||
gak?: { name: string; icon: string } | null
|
||||
}
|
||||
|
||||
function DayLabel({ d, size }: { d: DayShare; size: string }) {
|
||||
return (
|
||||
<span className={cx('flex items-center gap-1.5 font-jua leading-none', size)}>
|
||||
{d.label}
|
||||
{d.now && <small className="rounded-full bg-[#ff7a45] px-2 py-0.5 font-sans text-[13px] font-extrabold text-white">지금</small>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** 히어로 공유: 아침·낮·저녁·밤 네 줄. 줄마다 그 시간대 하늘에 날씨·기온, 날씨 점수, 그 시간 1등 각. 로고·지역·날짜는 공유 틀이 그린다 */
|
||||
export function DayShareCard({ days, ref }: { days: DayShare[]; ref: Ref<HTMLDivElement> }) {
|
||||
return (
|
||||
<Offscreen>
|
||||
<div ref={ref} className="flex aspect-[4/5] flex-col">
|
||||
{days.map((d) => (
|
||||
<div key={d.kind} className="b-hero grid flex-1 grid-cols-[96px_1fr_auto] items-center gap-3 px-4" data-t={d.kind}>
|
||||
<span className="flex flex-col gap-1.5">
|
||||
<DayLabel d={d} size="text-[28px]" />
|
||||
<span className="flex items-center gap-1 font-jua text-[22px] leading-none">
|
||||
<Ic name={d.icon} className="h-7 w-7 object-contain" />
|
||||
{d.temp}
|
||||
</span>
|
||||
</span>
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
{d.gak && <Ic name={d.gak.icon} className="w-10 shrink-0" />}
|
||||
<b className="font-jua text-[24px] leading-tight font-normal break-keep">{d.gak?.name ?? '쉬어 가요'}</b>
|
||||
</span>
|
||||
<span className="text-right">
|
||||
<b className="block font-bagel text-[62px] leading-[0.9] font-normal">{d.score ?? '–'}</b>
|
||||
<small className="text-[13px] font-bold opacity-75">날씨 점수</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Offscreen>
|
||||
)
|
||||
}
|
||||
|
||||
/** 1:1 공유용: 같은 내용을 2×2 칸으로 */
|
||||
export function DayShareGrid({ days, ref }: { days: DayShare[]; ref: Ref<HTMLDivElement> }) {
|
||||
return (
|
||||
<Offscreen>
|
||||
<div ref={ref} className="grid aspect-square grid-cols-2 grid-rows-2">
|
||||
{days.map((d) => (
|
||||
<div key={d.kind} className="b-hero flex flex-col justify-between p-4" data-t={d.kind}>
|
||||
<span className="flex items-center justify-between">
|
||||
<DayLabel d={d} size="text-[26px]" />
|
||||
<span className="flex items-center gap-1 font-jua text-[20px] leading-none">
|
||||
<Ic name={d.icon} className="h-7 w-7 object-contain" />
|
||||
{d.temp}
|
||||
</span>
|
||||
</span>
|
||||
<span>
|
||||
<b className="block font-bagel text-[64px] leading-[0.9] font-normal">{d.score ?? '–'}</b>
|
||||
<small className="text-[12px] font-bold opacity-75">날씨 점수</small>
|
||||
</span>
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
{d.gak && <Ic name={d.gak.icon} className="w-8 shrink-0" />}
|
||||
<b className="truncate font-jua text-[21px] font-normal">{d.gak?.name ?? '쉬어 가요'}</b>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Offscreen>
|
||||
)
|
||||
}
|
||||
|
||||
export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title: string; ref: Ref<HTMLDivElement> }) {
|
||||
return (
|
||||
<Offscreen>
|
||||
<div ref={ref} className="b-band-2 flex aspect-[4/5] flex-col bg-white px-5 pt-5 pb-4">
|
||||
<p className="m-0 font-jua text-[22px]">{title}</p>
|
||||
<ol className="m-0 mt-3 grid list-none gap-2 p-0">
|
||||
{items.map((g, i) => (
|
||||
<li key={g.index_id} className="flex items-center gap-2.5 rounded-[18px] bg-white px-3 py-2.5 shadow-[inset_0_-4px_0_var(--shade)]">
|
||||
{i < 3 ? <Ic name={MEDALS[i]} className="w-[24px] shrink-0" /> : <span className="w-[24px] shrink-0 text-center font-jua text-(--ink3)">{i + 1}</span>}
|
||||
<Ic name={g.icon} className="w-[36px] shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<b className="block font-jua text-[17px] leading-tight font-normal">{g.name}</b>
|
||||
{g.summary && <small className="block truncate text-xs font-semibold text-(--ink2)">{g.summary}</small>}
|
||||
</span>
|
||||
<em className="font-bagel text-[24px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { MyGak } from './myGakState'
|
||||
import type { TalkData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import type { WeatherWhyPayload } from './weatherWhy'
|
||||
import { createContext, use } from 'react'
|
||||
export type SharePayload = { title: string; slides: HTMLElement[] }
|
||||
/** square: 1:1 비율일 때 slides 대신 찍을 틀 (없으면 slides) */
|
||||
export type SharePayload = { title: string; slides: HTMLElement[]; square?: HTMLElement[] }
|
||||
|
||||
type CommentsState = { type: 'comments'; postId: number; draft?: string }
|
||||
|
||||
@@ -12,6 +16,10 @@ export type SheetState =
|
||||
| { type: 'login'; then?: CommentsState }
|
||||
| { type: 'me' }
|
||||
| { type: 'region' }
|
||||
| { type: 'mix'; shared?: MyGak }
|
||||
| { type: 'install' }
|
||||
| { type: 'weatherWhy'; why: WeatherWhyPayload }
|
||||
| { type: 'talk'; talk: TalkData }
|
||||
| null
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
|
||||
|
||||
@@ -35,7 +35,7 @@ export function PinIcon({ className }: P) {
|
||||
)
|
||||
}
|
||||
|
||||
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' }) {
|
||||
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' | 'talk' }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
|
||||
{name === 'today' && <path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
|
||||
@@ -55,6 +55,7 @@ export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky'
|
||||
<circle cx="12" cy="15" r="1.6" />
|
||||
</>
|
||||
)}
|
||||
{name === 'talk' && <path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H10l-4.5 4v-4h0A1.5 1.5 0 0 1 4 14.5zM8 8.5h8M8 12h5" />}
|
||||
{name === 'season' && <path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
|
||||
</svg>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useRef, useState, type ChangeEvent, type FormEvent } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import {
|
||||
addTalkMutation,
|
||||
blockTalkAuthorMutation,
|
||||
deleteTalkMutation,
|
||||
likeTalkMutation,
|
||||
reportTalkMutation,
|
||||
unlikeTalkMutation,
|
||||
} from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { uploadTalkImage } from '@nalssigak/shared/api/client/sdk.gen'
|
||||
import { TalkReport, TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { API_BASE_URL } from '../api/setup'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, kst } from '@nalssigak/shared/lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { topicName, TOPICS, useMyTalks } from './talkState'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Avatar, Rail, TAP44 } from './ui'
|
||||
|
||||
const BODY_MAX = 100
|
||||
const PHOTO_MAX = 10 * 1024 * 1024
|
||||
|
||||
// 서버 ErrorType 이름 → 안내
|
||||
const WRITE_ERRORS: Record<string, string> = {
|
||||
LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.',
|
||||
DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.',
|
||||
INVALID_INPUT: '100자 안으로 써 주세요.',
|
||||
}
|
||||
|
||||
// 글이 이보다 적으면 '동네 사람들' 묶음 대신 첫 글 쓰기 카드
|
||||
const GROUP_MIN = 3
|
||||
const COMPOSE_ID = 'talk-compose'
|
||||
|
||||
const REASONS = [
|
||||
[TalkReport.ABUSE, '욕설·비하'],
|
||||
[TalkReport.SPAM, '광고·도배'],
|
||||
[TalkReport.PRIVACY, '개인정보 노출'],
|
||||
[TalkReport.ETC, '기타'],
|
||||
] as const
|
||||
|
||||
/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */
|
||||
function slotWord(iso: string) {
|
||||
const h = kst(iso).h
|
||||
return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤'
|
||||
}
|
||||
|
||||
function useRefreshTalks() {
|
||||
const queryClient = useQueryClient()
|
||||
return () => queryClient.invalidateQueries({ predicate: (q) => ['listTalks', 'listMyTalks', 'talkGroups'].includes((q.queryKey[0] as { _id?: string } | undefined)?._id ?? '') })
|
||||
}
|
||||
|
||||
function Composer({ onDone }: { onDone?: (t: TalkData) => void }) {
|
||||
const { region } = useRegion()
|
||||
const { loggedIn, me } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const refresh = useRefreshTalks()
|
||||
const add = useMutation(addTalkMutation())
|
||||
const [text, setText] = useState('')
|
||||
const [topic, setTopic] = useState<TalkTopic>(TalkTopic.LOCAL)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [photo, setPhoto] = useState<{ file: File; src: string } | null>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
const busy = add.isPending || uploading
|
||||
|
||||
useEffect(() => {
|
||||
if (!photo) return
|
||||
return () => URL.revokeObjectURL(photo.src)
|
||||
}, [photo])
|
||||
|
||||
const pick = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
e.target.value = ''
|
||||
if (!file) return
|
||||
if (file.size > PHOTO_MAX) return setError('사진은 10MB까지 올릴 수 있어요.')
|
||||
setError(null)
|
||||
setPhoto({ file, src: URL.createObjectURL(file) })
|
||||
}
|
||||
|
||||
// 사진이 있으면 먼저 올려 주소를 받고, 그 주소를 글에 붙인다
|
||||
const upload = async (): Promise<string | undefined> => {
|
||||
if (!photo) return undefined
|
||||
setUploading(true)
|
||||
try {
|
||||
const { data } = await uploadTalkImage({ body: { file: photo.file } })
|
||||
if (!data.result?.success || !data.image) throw new Error(data.result?.desc ?? 'upload')
|
||||
return data.image
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const body = text.trim()
|
||||
if (!body || busy) return
|
||||
setError(null)
|
||||
upload().then(
|
||||
(image) =>
|
||||
add.mutate(
|
||||
{ body: { region_code: region.code, body, image, topic } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.')
|
||||
setText('')
|
||||
setPhoto(null)
|
||||
setTopic(TalkTopic.LOCAL)
|
||||
refresh()
|
||||
if (res.talk) onDone?.(res.talk)
|
||||
},
|
||||
onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'),
|
||||
},
|
||||
),
|
||||
(e: unknown) => {
|
||||
console.error('[talk] photo upload', e)
|
||||
setError('사진을 올리지 못했어요. 사진 파일인지 확인해 주세요.')
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit} className="mx-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<textarea
|
||||
id={COMPOSE_ID}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onFocus={() => !loggedIn && open({ type: 'login' })}
|
||||
readOnly={busy}
|
||||
maxLength={BODY_MAX}
|
||||
rows={2}
|
||||
placeholder={`지금 ${region.name.split(' ').at(-1)} 날씨 어때요?`}
|
||||
aria-label="동네 이야기 쓰기"
|
||||
className="w-full resize-none rounded-2xl bg-[#f3f6fb] px-3 py-2.5 text-[14.5px]"
|
||||
/>
|
||||
{photo && (
|
||||
<div className="relative mt-2 w-[96px]">
|
||||
<img src={photo.src} alt="올릴 사진" className="aspect-[4/5] w-full rounded-xl object-cover" />
|
||||
<button type="button" onClick={() => setPhoto(null)} aria-label="사진 빼기" className="absolute -top-1.5 -right-1.5 grid size-6 cursor-pointer place-items-center rounded-full bg-(--ink) text-[13px] font-extrabold text-white">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-1.5" role="radiogroup" aria-label="글 주제">
|
||||
{TOPICS.map(([k, label]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={topic === k}
|
||||
onClick={() => setTopic(k)}
|
||||
className={cx('cursor-pointer rounded-full px-2.5 py-1 text-[12.5px] font-extrabold', topic === k ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)')}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<input ref={fileRef} type="file" accept="image/*" onChange={pick} hidden />
|
||||
<div className="mt-1.5 flex items-center gap-2 text-xs font-bold text-(--ink3)">
|
||||
<button type="button" onClick={() => (loggedIn ? fileRef.current?.click() : open({ type: 'login' }))} disabled={busy} className="shrink-0 cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1.5 text-[13px] font-extrabold text-(--ink2) disabled:opacity-40">
|
||||
사진
|
||||
</button>
|
||||
<span className="min-w-0 truncate">{me ? `${me.nickname} · ${region.name.split(' ').at(-1)} · 지금 날씨가 함께 올라가요` : '로그인하면 쓸 수 있어요'}</span>
|
||||
<span className="ml-auto tabular-nums">
|
||||
{text.length}/{BODY_MAX}
|
||||
</span>
|
||||
<button type="submit" disabled={busy || (loggedIn && !text.trim())} className="shrink-0 cursor-pointer rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white disabled:opacity-40">
|
||||
{busy ? '올리는 중…' : '올리기'}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="mt-1 mb-0 text-xs font-bold text-(--heart)" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
/** onGone: 내 글을 지웠을 때. 목록을 다시 받아도 빠지지 않는 곳(방금 쓴 글)에서 직접 뺀다 */
|
||||
function TalkRow({ t, onGone, compact }: { t: TalkData; onGone?: () => void; compact?: boolean }) {
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const refresh = useRefreshTalks()
|
||||
const [liked, setLiked] = useState(t.liked)
|
||||
const [count, setCount] = useState(t.like_count)
|
||||
const [menu, setMenu] = useState<'closed' | 'open' | 'report' | 'done'>('closed')
|
||||
const like = useMutation(likeTalkMutation())
|
||||
const unlike = useMutation(unlikeTalkMutation())
|
||||
const remove = useMutation(deleteTalkMutation())
|
||||
const report = useMutation(reportTalkMutation())
|
||||
const block = useMutation(blockTalkAuthorMutation())
|
||||
const [failed, setFailed] = useState(false)
|
||||
|
||||
const toggle = () => {
|
||||
if (like.isPending || unlike.isPending) return
|
||||
const next = !liked
|
||||
setLiked(next)
|
||||
setCount((n) => n + (next ? 1 : -1))
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { talk_id: t.talk_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (res.result?.success && res.like_count != null) return setCount(res.like_count)
|
||||
setLiked(!next)
|
||||
setCount(t.like_count)
|
||||
},
|
||||
onError: () => {
|
||||
setLiked(!next)
|
||||
setCount(t.like_count)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 메뉴의 동작은 끝나면 목록을 다시 받아 숨긴 글·안 보기로 한 사람의 글이 빠지게 한다
|
||||
const after = {
|
||||
onSuccess: (res: { result?: { success?: boolean } }) => {
|
||||
if (!res.result?.success) return setFailed(true)
|
||||
setMenu('done')
|
||||
refresh()
|
||||
},
|
||||
onError: () => setFailed(true),
|
||||
}
|
||||
const guard = (run: () => void) => (loggedIn ? run() : open({ type: 'login' }))
|
||||
const src = t.image?.startsWith('/v1/') ? API_BASE_URL + t.image : (t.image ?? undefined)
|
||||
|
||||
return (
|
||||
<div className={cx('grid grid-cols-[34px_1fr_24px] gap-2.5 border-b border-(--line) py-2.5 last:border-b-0', compact ? 'h-full w-full items-stretch' : 'items-start')}>
|
||||
<span className="self-start">
|
||||
<Avatar character={t.character} color={t.color} mood={t.mood} />
|
||||
</span>
|
||||
{/* 묶음 카드는 옆 카드 높이에 맞춰 늘어나니, 시간·좋아요 줄을 맨 아래에 붙여 빈 곳이 아래에 몰리지 않게 */}
|
||||
<div className={cx('min-w-0', compact && 'flex flex-col')}>
|
||||
<small className={cx('block text-xs font-bold text-(--ink3)', compact && 'truncate')}>
|
||||
<b className="mr-1 font-extrabold text-(--ink)">{t.nickname}</b>
|
||||
{[t.region_name, slotWord(t.created_at), t.weather, t.topic && t.topic !== TalkTopic.LOCAL ? topicName(t.topic) : null].filter(Boolean).join(' · ')}
|
||||
</small>
|
||||
{/* 묶음 안 작은 카드는 글이 잘리니, 누르면 창에서 글 전체·큰 사진을 본다 */}
|
||||
{compact ? (
|
||||
<button type="button" onClick={() => open({ type: 'talk', talk: { ...t, liked, like_count: count } })} aria-label={`${t.nickname}의 글 전체 보기`} className="block w-full cursor-pointer text-left">
|
||||
{t.image && <img src={src} alt="" loading="lazy" className="float-right mt-1 ml-2 size-12 rounded-xl bg-[#eef4fc] object-cover" />}
|
||||
<p className="m-0 mt-0.5 line-clamp-2 min-h-[2lh] text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
|
||||
</button>
|
||||
) : (
|
||||
<p className="m-0 mt-0.5 text-[14.5px] break-words whitespace-pre-wrap">{t.body}</p>
|
||||
)}
|
||||
{t.image && !compact && <img src={src} alt="" loading="lazy" className="mt-2 aspect-[4/5] w-full rounded-2xl bg-[#eef4fc] object-cover" />}
|
||||
<small className={cx('block text-xs font-bold text-(--ink3)', compact ? 'mt-auto pt-1.5' : 'mt-0.5')}>
|
||||
{ago(t.created_at)} · 좋아요 {count}개 ·{' '}
|
||||
<button type="button" onClick={() => setMenu(menu === 'closed' ? 'open' : 'closed')} aria-expanded={menu !== 'closed'} className="cursor-pointer font-bold text-(--ink3)">
|
||||
{t.mine ? '내 글' : '더보기'}
|
||||
</button>
|
||||
</small>
|
||||
{menu !== 'closed' && (
|
||||
<div className="mt-1.5 flex flex-wrap gap-1.5 text-[12.5px] font-extrabold" role="group" aria-label="글 메뉴">
|
||||
{menu === 'done' ? (
|
||||
<span className="text-[#1f9d62]">처리했어요</span>
|
||||
) : t.mine ? (
|
||||
<button type="button" onClick={() => remove.mutate({ path: { talk_id: t.talk_id } }, { ...after, onSuccess: (res) => (after.onSuccess(res), res.result?.success && onGone?.()) })} disabled={remove.isPending} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
|
||||
지우기
|
||||
</button>
|
||||
) : menu === 'report' ? (
|
||||
REASONS.map(([reason, label]) => (
|
||||
<button key={reason} type="button" onClick={() => report.mutate({ path: { talk_id: t.talk_id }, body: { reason } }, after)} disabled={report.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
|
||||
{label}
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<button type="button" onClick={() => guard(() => block.mutate({ path: { talk_id: t.talk_id } }, after))} disabled={block.isPending} className="cursor-pointer rounded-full bg-[#eef4fc] px-3 py-1">
|
||||
이 사람 글 안 보기
|
||||
</button>
|
||||
<button type="button" onClick={() => guard(() => setMenu('report'))} className="cursor-pointer rounded-full bg-[#fdecec] px-3 py-1 text-(--heart)">
|
||||
신고하기
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{failed && (
|
||||
<span className="text-(--heart)" role="alert">
|
||||
못 했어요. 다시 해 주세요
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="좋아요" className={cx('relative cursor-pointer self-start pt-1', TAP44)}>
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 이야기 탭: 쓰기 칸과 전국 최신 글 (아래로 더 받기) */
|
||||
/** 피드 위 쓰는 칸. 늘 펼쳐 두고, 방금 올린 글은 바로 아래에 보인다 (피드 사이 글은 새로 받을 때 섞인다) */
|
||||
export function FeedComposer({ onPosted }: { onPosted: (t: TalkData) => void }) {
|
||||
return (
|
||||
<div className="mt-3.5">
|
||||
<Composer onDone={onPosted} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 묶음에서 누른 글 하나를 창으로: 글 전체·큰 사진·좋아요·더보기 */
|
||||
export function TalkSheet({ talk }: { talk: TalkData }) {
|
||||
return (
|
||||
<div className="flex-1 overflow-auto overscroll-contain px-4 pb-[18px]">
|
||||
<TalkRow t={talk} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 피드에 끼우는 글 한 장 */
|
||||
export function TalkCard({ t, onGone }: { t: TalkData; onGone?: () => void }) {
|
||||
return (
|
||||
<article className="mt-3.5 border-y border-(--line) bg-white px-3" aria-label={`${t.nickname}의 글`}>
|
||||
<TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} onGone={onGone} />
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
/** 오늘 피드의 사람 글 묶음: 옆으로 넘기는 카드, 끝에 그 주제 전체 보기 */
|
||||
export function TalkGroup({ title, topic, talks }: { title: string; topic?: number; talks: TalkData[] }) {
|
||||
return (
|
||||
<section aria-label={title} className="mt-3.5">
|
||||
<div className="flex items-end justify-between px-4">
|
||||
<h2 className="m-0 font-jua text-[19px] font-normal">{title}</h2>
|
||||
<Link to={topic ? `/talk?topic=${topic}` : '/talk'} className="text-[13px] font-bold text-(--ink2)">
|
||||
전체 보기
|
||||
</Link>
|
||||
</div>
|
||||
<Rail label={title}>
|
||||
{talks.map((t) => (
|
||||
<article key={`${t.talk_id}:${t.liked}:${t.like_count}`} className="flex w-[78%] max-w-[320px] rounded-[20px] bg-white px-3 shadow-[inset_0_-4px_0_var(--shade)]" aria-label={`${t.nickname}의 글`}>
|
||||
<TalkRow t={t} compact />
|
||||
</article>
|
||||
))}
|
||||
</Rail>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** '동네 사람들' 글이 적을 때 묶음 대신: 위 쓰기 칸으로 데려간다 */
|
||||
export function FirstTalkCard() {
|
||||
const { region } = useRegion()
|
||||
const place = region.name.split(' ').at(-1)
|
||||
const go = () => {
|
||||
const el = document.getElementById(COMPOSE_ID)
|
||||
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
el?.focus({ preventScroll: true })
|
||||
}
|
||||
return (
|
||||
<button type="button" onClick={go} className="mx-3 mt-3.5 flex w-[calc(100%-1.5rem)] cursor-pointer items-center gap-3 rounded-[22px] bg-white p-3.5 text-left shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<span className="font-jua text-[16.5px] leading-snug">
|
||||
지금 {place} 하늘 어때요?
|
||||
<small className="block font-sans text-[12.5px] font-semibold text-(--ink2)">첫 이야기를 남겨 주세요</small>
|
||||
</span>
|
||||
<span className="ml-auto shrink-0 rounded-full bg-(--orange) px-3.5 py-1.5 text-[13px] font-extrabold text-white">쓰기</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** '동네 사람들' 자리: 글이 GROUP_MIN 개 이상이면 묶음, 아니면 첫 글 쓰기 */
|
||||
export function NearTalks({ talks, loaded }: { talks: TalkData[]; loaded: boolean }) {
|
||||
if (!loaded) return null
|
||||
return talks.length >= GROUP_MIN ? <TalkGroup title="동네 사람들" talks={talks} /> : <FirstTalkCard />
|
||||
}
|
||||
|
||||
/** 내 정보 창의 내가 쓴 글 */
|
||||
export function MyTalks() {
|
||||
const { talks, loaded, more, loadMore } = useMyTalks()
|
||||
if (!loaded) return null
|
||||
return (
|
||||
<section aria-label="내 글">
|
||||
<h4 className="m-0 mb-1 text-sm font-extrabold">내 글</h4>
|
||||
{talks.length ? (
|
||||
talks.map((t) => <TalkRow key={`${t.talk_id}:${t.liked}:${t.like_count}`} t={t} />)
|
||||
) : (
|
||||
<p className="m-0 text-[13px] font-semibold text-(--ink3)">아직 쓴 글이 없어요</p>
|
||||
)}
|
||||
{more && (
|
||||
<button type="button" onClick={() => loadMore()} className="mt-1 w-full cursor-pointer rounded-[14px] bg-[#f3f6fb] py-2.5 text-[13.5px] font-extrabold text-(--ink2)">
|
||||
더 보기
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
||||
import { listMyTalksInfiniteOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
|
||||
import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { useRegion } from './regionContext'
|
||||
|
||||
// 글 주제와 피드 묶음 이름
|
||||
export const TOPICS = [
|
||||
[TalkTopic.LOCAL, '동네 이야기'],
|
||||
[TalkTopic.SKY, '하늘·노을'],
|
||||
[TalkTopic.RAIN, '비·눈'],
|
||||
[TalkTopic.FOLIAGE, '단풍·꽃'],
|
||||
[TalkTopic.OUTFIT, '오늘 옷차림'],
|
||||
] as const
|
||||
export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기'
|
||||
|
||||
/** 오늘 피드 묶음: 0 은 '동네 사람들', 나머지는 주제별(3장 이상일 때만 옴) */
|
||||
export function useTalkGroups() {
|
||||
const { region } = useRegion()
|
||||
const q = useQuery(talkGroupsOptions({ query: { region: region.code } }))
|
||||
const groups = new Map<number, TalkData[]>((q.data?.groups ?? []).map((g) => [g.topic, g.talks ?? []]))
|
||||
return { groups, loaded: q.isSuccess }
|
||||
}
|
||||
|
||||
/** 주제별 글 페이지 목록 (topic 없으면 전체) */
|
||||
export function useTopicTalks(topic?: TalkTopic) {
|
||||
const { region } = useRegion()
|
||||
const list = useInfiniteQuery({
|
||||
...listTalksInfiniteOptions({ query: { region: region.code, ...(topic ? { topic } : {}) } }),
|
||||
initialPageParam: {},
|
||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||||
})
|
||||
return {
|
||||
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
|
||||
loaded: list.isSuccess,
|
||||
more: list.hasNextPage && !list.isFetchingNextPage,
|
||||
loadMore: list.fetchNextPage,
|
||||
}
|
||||
}
|
||||
|
||||
/** 내가 쓴 글 (최신순) */
|
||||
export function useMyTalks() {
|
||||
const list = useInfiniteQuery({
|
||||
...listMyTalksInfiniteOptions(),
|
||||
initialPageParam: {},
|
||||
getNextPageParam: (last) => last.next_cursor ?? undefined,
|
||||
})
|
||||
return {
|
||||
talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [],
|
||||
loaded: list.isSuccess,
|
||||
more: list.hasNextPage && !list.isFetchingNextPage,
|
||||
loadMore: list.fetchNextPage,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { WeatherWhy } from '@nalssigak/shared/api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
|
||||
/** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
|
||||
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[]; status?: { label: string; value: string; tone?: string; detail?: string | null }[] }
|
||||
|
||||
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게
|
||||
const COLOR: Record<string, string> = {
|
||||
기온: '#ff7a45',
|
||||
비: '#4f97e3',
|
||||
햇볕: '#ffb02e',
|
||||
바람: '#5fb8b0',
|
||||
습도: '#8e8cf0',
|
||||
미세먼지: '#b59a86',
|
||||
}
|
||||
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8'
|
||||
|
||||
// 상태 줄 항목마다 단계를 나누는 기준 (backend/services/hero_stats.py 와 같은 값)
|
||||
const RULE: Record<string, string> = {
|
||||
습도: '30% 아래는 건조, 60% 넘으면 습함이에요',
|
||||
불쾌지수: '68 아래는 쾌적, 75부터 불쾌예요',
|
||||
자외선: '3 아래는 낮음, 6부터 높음이에요',
|
||||
미세먼지: '에어코리아 기준 등급이에요',
|
||||
}
|
||||
|
||||
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
|
||||
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
|
||||
return (
|
||||
<div className="flex-1 overflow-auto overscroll-contain px-4 pt-4 pb-[18px]">
|
||||
<p className="m-0 flex items-baseline gap-2">
|
||||
<b className="font-bagel text-[44px] leading-none font-normal">{d.score}</b>
|
||||
<span className="font-jua text-[17px] text-(--ink2)">{d.label} 날씨 점수</span>
|
||||
</p>
|
||||
|
||||
<div className="mt-3 flex h-7 gap-[3px] overflow-hidden rounded-[10px]" role="img" aria-label={d.why.map((w) => `${w.label} 비중 ${w.weight}% 중 ${w.score}점`).join(', ')}>
|
||||
{d.why.map((w) => (
|
||||
<span key={w.label} className="relative h-full bg-[#eef2f8]" style={{ width: `${w.weight}%` }}>
|
||||
<span className="absolute inset-y-0 left-0" style={{ width: `${w.score}%`, background: colorOf(w.label) }} />
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<p className="m-0 mt-1.5 text-[12.5px] font-semibold text-(--ink3)">칸 넓이는 비중, 채운 만큼이 얻은 점수예요</p>
|
||||
|
||||
<ul className="m-0 mt-3 flex list-none flex-col gap-1.5 p-0">
|
||||
{d.why.map((w) => (
|
||||
<li key={w.label} className="flex items-center gap-3 rounded-2xl bg-[#f5f8fc] px-3.5 py-2.5">
|
||||
<i className="size-3 shrink-0 rounded-full" style={{ background: colorOf(w.label) }} aria-hidden="true" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<b className="block font-jua text-[16px] leading-tight font-normal">
|
||||
{w.label} <small className="font-sans text-[12px] font-bold text-(--ink3)">비중 {w.weight}%</small>
|
||||
</b>
|
||||
<small className="block text-[13px] font-semibold text-(--ink2)">{w.note}</small>
|
||||
</span>
|
||||
<b className="font-jua text-[20px] font-normal tabular-nums">{w.score}</b>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{d.status && d.status.length > 0 && (
|
||||
<>
|
||||
<h4 className="m-0 mt-5 font-jua text-[17px] font-normal">지금 상태</h4>
|
||||
<ul className="m-0 mt-2 flex list-none flex-col gap-1.5 p-0">
|
||||
{d.status.map((s) => (
|
||||
<li key={s.label} className="flex items-center gap-3 rounded-2xl bg-[#f5f8fc] px-3.5 py-2.5">
|
||||
<span className="min-w-0 flex-1">
|
||||
<b className="block font-jua text-[16px] leading-tight font-normal">{s.label}</b>
|
||||
{RULE[s.label] && <small className="block text-[12.5px] font-semibold text-(--ink3)">{RULE[s.label]}</small>}
|
||||
</span>
|
||||
<span className="shrink-0 text-right">
|
||||
<b className={cx('block font-jua text-[18px] leading-tight font-normal', s.tone === 'warn' && 'b-warn')}>{s.value}</b>
|
||||
{s.detail?.split(' · ').map((x) => (
|
||||
<small key={x} className="block text-[12px] font-bold whitespace-nowrap text-(--ink2) tabular-nums">
|
||||
{x}
|
||||
</small>
|
||||
))}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="m-0 mt-3 text-[13px] leading-relaxed font-semibold text-(--ink2)">
|
||||
조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user