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 { PostType, RainType, Sky, TalkTopic, type BandArticle, type BandEvent, type Hero as HeroData, type PostReaction, type ResWeatherToday, 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 { useAuth } from './authContext' import { FoliageCard } from './foliageMap' import { InstallBanner } from './installBanner' import { MoonArt } from './moon' import { MyGakRow } from './myGak' import { MY_GAK_ID, TodayIcons } from './todayIcons' import { fromShare } from './myGakState' import { PostCard, PostCardSkel, PostFrame } from './Post' import { usePinnedLike } from './pinnedLike' import { ShortsRail } from './Shorts' import { FeedComposer, NearTalks, TalkGroup } from './talk' import { topicName, useTalkGroups, useTodayMyTalks } from './talkState' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' import { useSky } from './skyContext' 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 { track } from '../lib/analytics' type Mode = 'now' | TimeKind // 하루 흐름 칸 순서와 칸마다 볼 예보 시각 const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night'] const PREVIEW: Record = { morning: { label: '아침', hour: 7 }, day: { label: '낮', hour: 13 }, sunset: { label: '저녁', hour: 18 }, night: { label: '밤', hour: 22 }, } // 비·눈 줄기: 위치·주기를 엇갈려 고르게 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' }, { top: '20%', left: '52%', '--len': '70px', '--dur': '9s', '--dl': '4s' }, { top: '34%', left: '94%', '--len': '80px', '--dur': '11s', '--dl': '6.5s' }, ] 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' // 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간 const SLOT_KEY: Record = { 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 = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow', } // 구름 수: 구름 많음 둘, 흐림·비·눈 셋 // 히어로 오른쪽 위 좋아요·댓글·보내기: 아이콘마다 좌우 여백을 같게, 숫자가 붙어도 아이콘 사이 간격이 그대로 const HERO_ACT = 'relative flex h-8 cursor-pointer items-center justify-center gap-1 px-[5px] text-[13px] leading-none font-extrabold tabular-nums' 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 = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3, } 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(null) const gridRef = useRef(null) // 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다 // 내일 날씨 페이지(/tomorrow/...)로 들어오면 내일이 켜진 채로 const { pathname } = useLocation() const [tmr, setTmr] = useState(() => pathname.startsWith('/tomorrow/')) const [tmrKind, setTmrKind] = useState('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 = tmr ? tmrKind : (preview ?? 'now') const clock = useNow() 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]) // 내일을 볼 땐 배경·글자색도 내일 고른 칸을 따른다 (오늘 밤을 고른 채 내일 낮을 보면 낮 하늘에 흰 글자가 되던 것) useEffect(() => { if (tmr) setPreview(tmrKind) }, [tmr, tmrKind, setPreview]) const slots = (tmr ? tomorrowQ.data?.slots : today?.slots) ?? [] const slotsLoad = tmr ? loadOf(tomorrowQ) : todayLoad // 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸 // 지금은 가장 가까운 3시간 칸(17시면 18시 칸). 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸 const slotOf = (k: TimeKind | 'now') => { if (k === 'now') { const known = slots.filter((x) => x.temp_c != null) const at = t.h + t.mi / 60 return known.length ? known.reduce((a, b) => (Math.abs(kst(b.at).h - at) < Math.abs(kst(a.at).h - at) ? b : a)) : undefined } const h = PREVIEW[k].hour const s = slots.length ? slotAt(slots, h) : undefined 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 : (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 = !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 tmrWhen = mode === 'now' ? '내일' : `내일 ${PREVIEW[mode].label}` const bubble = tmr ? top1 ? top1.score >= 70 ? `${tmrWhen}은 ${top1.name}!` : `${tmrWhen}은 쉬어 가요` : 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 (
{(rain || snow) && ( )}
{( [ [false, '오늘'], [true, '내일'], ] as const ).map(([v, l]) => ( ))} {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 {post && ( <> )}
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
{/* 다 불러온 높이(한 줄 말·날씨 한 줄·상태 두 줄)를 미리 잡아 둔다: 늦게 채워지며 아래 피드가 밀려 내려가지 않게 */}
{top1 ? ( ) : (

{bubble ?? }

)}

{top1?.summary ?? (feedLoad === 'loading' ? : null)}

{/* 상태 한 줄: 습도·불쾌지수·자외선·미세먼지 단계 이름. 조심할 것만 색 */} {status.length > 0 && (

{status.map((x, i) => ( {i > 0 && ( )} {x.label} {x.value} ))} {why && score != null && ( )}

)}
{KINDS.map((k) => { const isNow = !tmr && k === nowKind const s = slotOf(isNow ? 'now' : k) const on = k === kind return ( ) })}
) } const WANING = ['기우는 달', '하현달', '그믐달'] function GakCard({ items, post, place, at }: { items: TopIndex[]; post?: PostReaction | null; place: string; at: string }) { const { open } = useSheet() const tplRef = useRef(null) const top = items.filter((g) => g.active).slice(0, 5) return ( 전체 보기} caption="누르면 계산 근거를 보여 줘요" shot={tplRef} pinned={{ key: 'gak_post', post }} >

오늘의 각 · {place} {at}

    {top.map((g, i) => (
  1. ))}
) } function PostsSkel() { return ( <> ) } 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 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 { preview } = useSky() const { open } = useSheet() const f = feed.data const posts = f?.posts ?? [] const stories = atSlot(f?.stories ?? [], preview) const sloted = preview != null && stories !== f?.stories const bands = f?.bands const nowAt = f?.hero?.now_at const load = loadOf(feed) // 사람 글은 묶음으로: '동네 사람들'은 오늘의 각 아래, 주제 묶음은 같은 주제 포스트 아래. 오늘 쓴 내 글은 글쓰기 칸 아래 '오늘 내 글'에 따로 있으니 빼고 const { loggedIn } = useAuth() const mine = useTodayMyTalks(loggedIn) 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 ? : null } // 비·눈이 오거나 2시간 안에 올 때만 비·눈 묶음을 히어로 바로 아래로 const at = nowAt ? Date.parse(nowAt) : 0 const nowSlot = (today.data?.slots ?? []).filter((x) => x.temp_c != null).reduce((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 ? : null], [9, bands?.season?.length ? : null], ] // 사람 글 묶음은 포스트 사이사이에 하나씩: 묶음·띠·단풍 카드가 이미 붙는 자리와 바로 앞 자리는 건너뛰어 가로 목록이 연달아 나오지 않게 const spreadTopics = [TalkTopic.OUTFIT, ...(raining ? [] : [TalkTopic.RAIN]), ...(sunsetAt < 0 ? [TalkTopic.SKY] : [])].filter((tp) => groupOf(tp).length) const taken = new Set([1, sunsetAt, ...bandAt.map(([at]) => at - 1)]) const spreadAt = new Map() 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 ( // 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
{mine.length > 0 && } {raining && group(TalkTopic.RAIN)}
{/* 실패 안내는 여기 한 번만, 각 카드 스켈레톤과 같은 크기로 */} {stories.some((g) => g.active) ? ( ) : 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" /> )} {/* 단풍철엔 단풍 지도를 포스트 맨 앞에, 단풍 이야기 묶음은 바로 아래 */} {load !== 'loading' && posts.length > 0 && ( <> {group(TalkTopic.FOLIAGE)} )} {posts.map((p, i) => ( {i === sunsetAt && group(TalkTopic.SKY)} {bandAt.find(([at]) => at === i + 1)?.[1]} {spreadAt.get(i)} ))} {/* 글이 모자라 끼울 자리가 없던 묶음은 맨 뒤에 */} {feed.isSuccess && spreadLeft} {feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => {node})}
) }