import { getWeatherTodayOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; import type { Hero as HeroData, PostReaction, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen'; import { kindOfHour, kst, loadOf, type Load, type TimeKind, WEEKDAYS } from '@nalssigak/shared/lib'; import { KINDS, PREVIEW, SLOT_KEY, WANING, type Weather, WEATHER_ICON, weatherOf } from '@nalssigak/shared/lib/today'; import { deg, slotAt } from '@nalssigak/shared/lib/weatherText'; import { useQuery } from '@tanstack/react-query'; import { useEffect, useRef, useState, type ReactNode } from 'react'; import { Pressable, View, type DimensionValue, type ViewStyle } from 'react-native'; import { Text } from '@/components/text'; import Animated, { cancelAnimation, Easing, useAnimatedStyle, useReducedMotion, useSharedValue, withDelay, withRepeat, withTiming } from 'react-native-reanimated'; import { LinearGradient } from 'expo-linear-gradient'; import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg'; import { Fall } from '@/components/fall'; import { MoonArt } from '@/components/moon'; import { CommentIcon, HeartIcon, SendIcon } from '@/components/post/icons'; import { Shoot, type ShootSpec } from '@/components/sky-bg'; import { Ic, Skel } from '@/components/ui'; import { track } from '@/lib/analytics'; import { usePinnedLike } from '@/lib/pinned-like'; import { useRegion } from '@/lib/region'; import { useShare } from '@/lib/share-image'; import { useSheet } from '@/lib/sheet'; import { SITE_URL } from '@/lib/site'; import { useSky } from '@/lib/sky'; type Mode = 'now' | TimeKind; const HERO_BG: Record = { morning: ['#ffd9b8', '#ffe9d4', '#dff0ff'], day: ['#9fd3ff', '#cfe9ff', '#f1f8ff'], sunset: ['#4c42b0', '#6a48b0', '#9a4a88'], night: ['#141b3d', '#27306a', '#3d3f86'], gray: ['#a9bbd0', '#cbd7e4', '#eef2f7'], }; // 가운데 해(낮)·달(저녁·밤) 색과 글자색 const ORB: Record<'sun' | 'sunset' | 'night', { stops: [string, string, string, string]; text: string }> = { sun: { stops: ['#fff5cf', '#ffc86e', '#ff8e4e', '#ee6436'], text: '#5c1f08' }, sunset: { stops: ['#fff4e6', '#ffd9b8', '#f7a991', '#e07a8f'], text: '#4a2442' }, night: { stops: ['#ffffff', '#e7e3ff', '#b9b0f2', '#8f86d9'], text: '#2b2a5c' }, }; const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }) as const); // 구름 자리·떨어지는 지연·둥둥 주기 (웹 CLOUDS). 구름 수: 구름 많음 둘, 흐림·비·눈 셋 // 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게 (웹 TodayPage SHOOTS, 밀리초) const SHOOTS: ShootSpec[] = [ { top: '6%', left: '80%', len: 90, dur: 7000, dl: 1500 }, { top: '20%', left: '52%', len: 70, dur: 9000, dl: 4000 }, { top: '34%', left: '94%', len: 80, dur: 11000, dl: 6500 }, ]; const CLOUDS = [ { top: 36, left: '5%', w: 84, h: 32, d: 100, f: 6000 }, { top: 96, left: '63%', w: 96, h: 36, d: 250, f: 6400 }, { top: 30, left: '72%', w: 64, h: 28, d: 400, f: 5400 }, ] as const; const CLOUD_N: Record = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 }; // 비·눈 줄기: 위치·주기를 엇갈려 고르게 const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, top: `${(i * 29) % 90}%`, delay: ((i * 37) % 100) * 10, dur: 550 + ((i * 13) % 5) * 100 }) as const); const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, top: `${(i * 31) % 90}%`, delay: ((i * 53) % 100) * 40, dur: 3200 + ((i * 7) % 5) * 500 }) as const); /** 둥근 구름: 몸통 위에 동그라미 둘을 겹친다 (웹 .b-cloud ::before/::after) */ function Cloud({ w, h, night }: { w: number; h: number; night: boolean }) { const bg = night ? '#c9cdf0' : '#fff'; const big = w * 0.46; const small = w * 0.36; return ( ); } /** 비 줄기·눈송이 하나: 위에서 아래로 계속 떨어진다. 동작 줄이기면 제자리에 멈춘다 */ function Particle({ left, top, delay, dur, snow, light }: { left: DimensionValue; top: DimensionValue; delay: number; dur: number; snow: boolean; light: boolean }) { const reduce = useReducedMotion(); const t = useSharedValue(0); useEffect(() => { if (reduce) return; t.value = withDelay(delay, withRepeat(withTiming(1, { duration: dur, easing: Easing.linear }), -1, false)); return () => cancelAnimation(t); }, [reduce, delay, dur, t]); const anim = useAnimatedStyle(() => ({ transform: [{ translateX: (snow ? 18 : -8) * t.value }, { translateY: 440 * t.value }] })); const place: ViewStyle = { position: 'absolute', left, top: reduce ? top : -24 }; if (snow) return ; return ( ); } function useNow(ms = 20000) { const [now, setNow] = useState(() => new Date()); useEffect(() => { const id = setInterval(() => setNow(new Date()), ms); return () => clearInterval(id); }, [ms]); return now; } const failed = (load: Load) => load === 'error' || load === 'retrying'; // 값이 오기 전엔 스켈레톤, 못 불러왔거나 값이 없으면 '?' function heroVal(load: Load, v: ReactNode, skel: string) { if (v != null) return v; if (load === 'loading') return ; return ?; } type Props = { hero?: HeroData | null; post?: PostReaction | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load }; export function Hero({ hero, post, today, ranked, feedLoad, todayLoad }: Props) { const { open } = useSheet(); const { region } = useRegion(); const like = usePinnedLike('hero_post', post); const shot = useRef(null); // 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다 (웹 TodayPage Hero) const [tmr, setTmr] = useState(false); const [tmrKind, setTmrKind] = useState('day'); const tomorrowQ = useQuery({ ...getWeatherTodayOptions({ query: { region: region.code, day: 'tomorrow' } }), enabled: tmr }); const ahead = hero?.tomorrow; 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시간 칸. 시간대는 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸 const slotOf = (k: Mode) => { 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 dark = kind === 'sunset' || kind === 'night'; const moon = !tmr && dark && hero?.moon_name && hero.moon_pct != null ? { 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 openWhy = () => why && score != null && open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } }); const switchDay = (v: boolean) => { // 내일로 넘어갈 땐 지금 보던 시간대 그대로 시작해 배경이 튀지 않게 if (v && !tmr) setTmrKind(kind); if (v !== tmr) track('hero_day_switch', { day: v ? 'tomorrow' : 'today' }); setTmr(v); }; const shareView = useShare(); const share = () => { const title = `${region.name} ${tmr ? '내일' : '오늘'} 날씨`; void shareView(shot, { title, message: `${title} · 날씨각 ${SITE_URL}` }); }; const gray = !dark && weather !== 'clear' && weather !== 'partly'; const rain = weather === 'rain' || weather === 'sleet'; const snow = weather === 'snow' || weather === 'sleet'; const orb = ORB[kind === 'sunset' ? 'sunset' : kind === 'night' ? 'night' : 'sun']; const text = dark ? 'text-white' : 'text-[#28304a]'; const icon = dark ? '#ffffff' : '#28304a'; const strip = dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)'; // 가운데가 밝은 달이면 진한 글씨에 흰 번짐, 가운데가 어두운 달(초승·그믐·삭)이면 흰 글씨 const orbText: { color: string; textShadowColor?: string; textShadowRadius?: number } = !moon ? { color: orb.text } : moon.pct >= 50 ? { color: orb.text, textShadowColor: '#fff', textShadowRadius: 8 } : { color: '#fff', textShadowColor: 'rgba(10,14,40,0.6)', textShadowRadius: 8 }; return ( {kind === 'night' && STARS.map((s, i) => )} {kind === 'night' && SHOOTS.map((s, i) => )} {(rain || snow) && ( {rain && DROPS.map((p, i) => )} {snow && FLAKES.map((p, i) => )} )} {( [ [false, '오늘'], [true, '내일'], ] as const ).map(([v, l]) => ( switchDay(v)} accessibilityRole="radio" accessibilityState={{ checked: tmr === v }} className={`rounded-full px-2.5 py-0.5 ${tmr === v ? 'bg-white' : ''}`}> {l} ))} {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 {post && ( <> {like.count > 0 && {like.count.toLocaleString()}} open({ type: 'comments', postId: post.post_id })} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 댓글" className="h-8 flex-row items-center gap-1 px-[5px] opacity-80"> {post.comment_count > 0 && {post.comment_count.toLocaleString()}} )} {/* 저녁·밤엔 오늘 밤 실제 모양의 달 (빛 번짐까지 그려서 공보다 크게) */} {moon ? ( ) : ( )} {/* 점수 근거가 있으면 해를 눌러도 근거 창 */} {failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`} {heroVal(feedLoad, score, 'w-[84px] h-10')} {CLOUDS.slice(0, CLOUD_N[weather]).map((c) => ( ))} {bubble ? ( top1 && open({ type: 'gak', indexId: top1.index_id })} accessibilityLabel={top1 ? `${bubble} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기` : undefined}> {bubble} ) : ( )} {top1?.summary ? {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 ( (tmr ? setTmrKind(k) : setPreview(isNow ? null : k))} className={`flex-1 items-center rounded-[14px] py-1.5 ${on ? 'bg-white' : ''}`} style={on ? { boxShadow: '0 4px 12px rgb(40 48 74 / 0.1)' } : undefined}> {isNow ? '지금' : PREVIEW[k].label} {heroVal(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')} ); })} ); }