import { Fragment, useEffect, useState, type ReactNode } from 'react' import { Link } from 'react-router' import { useQuery } from '@tanstack/react-query' import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen' import type { BandArticle, BandEvent, Hero as HeroData, HeroStat as HeroStatData, ResWeatherToday, TopIndex } from '../api/client/types.gen' import { cx } from '../lib/utils' import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib' import { PostCard, PostCardSkel } from './Post' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' import { useSky } from './skyContext' import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui' import { deg, skyText, slotAt } from './weatherText' type Mode = 'now' | TimeKind const MODES: [Mode, string][] = [ ['now', '지금 시간'], ['morning', '아침'], ['day', '낮'], ['sunset', '저녁'], ['night', '밤'], ] // 미리보기 시간대마다 보여 줄 시계와 그 시각의 예보 칸 const PREVIEW: Record = { morning: { label: '아침', clock: '07:40', hour: 7 }, day: { label: '낮', clock: '13:20', hour: 13 }, sunset: { label: '저녁', clock: '18:25', hour: 18 }, night: { label: '밤', clock: '22:10', 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 SHOOTS = [ { top: '6%', left: '80%', '--len': '90px', '--dur': '7s', '--dl': '1.5s' }, { top: '20%', left: '52%', '--len': '70px', '--dur': '9s', '--dl': '4s' }, { top: '34%', left: '94%', '--len': '80px', '--dur': '11s', '--dl': '6.5s' }, ] const ORB_POS = { left: '66%', top: '6px', d: '.5s', f: '4.4s' } function useNow(ms = 20000) { const [now, setNow] = useState(() => new Date()) useEffect(() => { const id = setInterval(() => setNow(new Date()), ms) return () => clearInterval(id) }, [ms]) return now } // 값이 오기 전엔 그 글자 자리(같은 줄 높이)에 스켈레톤, 못 불러왔거나 값이 없으면 같은 글꼴의 '?' function heroVal(load: Load, v: ReactNode, skel: string) { if (v != null) return v if (load === 'loading') return ( <> 불러오는 중 ) return ( <> {load === 'ready' ? '정보 없음' : '못 불러왔어요'} ) } const failed = (load: Load) => load === 'error' || load === 'retrying' type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Load; todayLoad: Load } function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) { const { open } = useSheet() const [mode, setMode] = useState('now') const clock = useNow() const t = kst(clock) const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)) : mode const { setServerKind, setPreview } = useSky() // 화면 전체 하늘 배경도 같은 시간대로 맞춘다 useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind]) useEffect(() => setPreview(mode === 'now' ? null : mode), [mode, setPreview]) useEffect(() => () => setPreview(null), [setPreview]) const slots = today?.slots ?? [] const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined // 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다 const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c const feels = mode === 'now' && hero ? hero.feels_c : slot?.feels_c const top1 = hero?.top1 const who = kind === 'night' ? 'bear' : 'rabbit' // 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다 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 tempLoad = mode === 'now' ? feedLoad : todayLoad const feelsLine = temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : failed(tempLoad) ? '날씨를 못 불러왔어요' : tempLoad === 'ready' ? '체감 ?°' : null const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null // 아래 값은 모두 로딩·완료·실패 사이 높이가 같다: 글자 자리 스켈레톤, 비 칸은 두 줄 높이로 고정 return (
{MODES.map(([m, l]) => ( ))}

{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 · {mode === 'now' ? '지금' : `${PREVIEW[mode].label} 미리보기`}

{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}
{heroVal(tempLoad, temp != null ? deg(temp) : null, 'w-[72px]')} {feelsLine ?? }
{/* 두 칸은 서버가 지금 챙길 것(비·미세먼지·자외선·일교차 등) 순서로 골라 준다 */} {hero?.stats?.length ? hero.stats.map((s) => ( {s.value} )) : STAT_HOLD.map((k) => ( {heroVal(feedLoad, null, 'w-16')} ))}
{bubble ?? }
) } 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}` } const STAT_HOLD = ['a', 'b'] function HeroStat({ icon, label, tone = 'normal', children }: { icon: string; label: string; tone?: HeroStatData['tone']; children: ReactNode }) { return (
{label} {/* 한국어가 글자 단위로 끊기지 않게 단어 단위로 줄바꿈 */} {children}
) } function Stories({ items }: { items: TopIndex[] }) { const { open } = useSheet() return ( {items.map((g, i) => ( ))} ) } function PostsSkel() { return ( <> ) } const STORY_SKELS = Array.from({ length: 6 }, (_, i) => i) /** Stories 와 같은 칸(68px 동그라미 + 이름 + 점수)을 6개 */ function StoriesSkel() { return ( {STORY_SKELS.map((i) => ( ))} ) } function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) { return (
{children}
) } function EventsBand({ events }: { events: BandEvent[] }) { return ( {events.map((e, i) => ( {e.status_label} {e.name} ))} ) } function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) { const { open } = useSheet() return ( {items.slice(0, 5).map((g, i) => ( ))} ) } function SeasonBand({ news }: { news: BandArticle[] }) { const { open } = useSheet() return ( {news.map((a) => ( ))} ) } export function TodayPage() { const { region } = useRegion() const feed = useQuery(getFeedOptions({ query: { region: region.code } })) const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } })) const f = feed.data const posts = f?.posts ?? [] const stories = f?.stories ?? [] const bands = f?.bands const nowAt = f?.hero?.now_at const load = loadOf(feed) useEffect(() => { window.scrollTo({ top: 0 }) }, [region.code]) // 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다 const bandAt: [number, ReactNode][] = [ [3, bands?.events?.length ? : null], [6, bands?.top5?.length ? : null], [9, bands?.season?.length ? : null], ] return ( // 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
{/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */} {stories.length ? : load === 'loading' ? : feed.refetch()} empty="오늘 계산된 각이 없어요." hold={} className="inset-x-3 top-3 bottom-1" />}
{load === 'loading' && } {/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */} {load !== 'loading' && !posts.length && ( } className="inset-x-3 top-3.5 bottom-auto" /> )} {posts.map((p, i) => ( {bandAt.find(([at]) => at === i + 1)?.[1]} ))} {feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => {node})}
) }