Files
o2o-weather/mobile/src/components/today/hero.tsx
T

240 lines
14 KiB
TypeScript

import type { Hero as HeroData, ResWeatherToday, TopIndex } from '@nalssigak/shared/api/client/types.gen';
import { kindOfHour, kst, 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 { useEffect, 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 { Shoot, type ShootSpec } from '@/components/sky-bg';
import { Ic, Skel } from '@/components/ui';
import { useSheet } from '@/lib/sheet';
import { useSky } from '@/lib/sky';
type Mode = 'now' | TimeKind;
const HERO_BG: Record<TimeKind | 'gray', readonly [string, string, string]> = {
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<Weather, number> = { 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 (
<View style={{ width: w, height: h }}>
<View style={{ position: 'absolute', left: w * 0.16, top: -h * 0.58, width: big, height: big, borderRadius: big, backgroundColor: bg }} />
<View style={{ position: 'absolute', left: w * 0.5, top: -h * 0.36, width: small, height: small, borderRadius: small, backgroundColor: bg }} />
<View style={{ width: w, height: h, borderRadius: h, backgroundColor: bg, boxShadow: '0 16px 28px rgb(40 70 120 / 0.13)' }} />
</View>
);
}
/** 비 줄기·눈송이 하나: 위에서 아래로 계속 떨어진다. 동작 줄이기면 제자리에 멈춘다 */
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 <Animated.View style={[place, { width: 7, height: 7, borderRadius: 7, backgroundColor: '#fff', boxShadow: '0 0 4px rgb(120 150 200 / 0.5)' }, anim]} />;
return (
<Animated.View style={[place, anim]}>
<LinearGradient colors={['transparent', light ? 'rgba(220,230,255,0.7)' : 'rgba(80,130,200,0.7)']} style={{ width: 2, height: 18, borderRadius: 2 }} />
</Animated.View>
);
}
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 <Skel className={skel} />;
return <Text className="opacity-50">?</Text>;
}
type Props = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load };
export function Hero({ hero, today, ranked, feedLoad, todayLoad }: Props) {
const { open } = useSheet();
const { preview, setServerKind, setPreview } = useSky();
const mode: Mode = preview ?? 'now';
const t = kst(useNow());
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 ?? [];
// 지금은 가장 가까운 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 : 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 dark = kind === 'sunset' || kind === 'night';
const moon = 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 bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null;
const status = hero?.status ?? [];
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 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 (
<View className="mx-3 mt-1 overflow-hidden rounded-[28px] px-4 pt-3 pb-3">
<LinearGradient colors={HERO_BG[gray ? 'gray' : kind]} locations={kind === 'night' ? [0, 0.6, 1] : [0, 0.5, 1]} style={{ position: 'absolute', inset: 0 }} />
{kind === 'night' && STARS.map((s, i) => <View key={i} className="absolute size-[3px] rounded-full bg-white" style={{ left: s.left, top: s.top, opacity: s.opacity }} />)}
{kind === 'night' && SHOOTS.map((s, i) => <Shoot key={i} {...s} />)}
{(rain || snow) && (
<View pointerEvents="none" style={{ position: 'absolute', inset: 0 }}>
{rain && DROPS.map((p, i) => <Particle key={`r${i}`} {...p} snow={false} light={dark} />)}
{snow && FLAKES.map((p, i) => <Particle key={`s${i}`} {...p} snow light={dark} />)}
</View>
)}
<Text className={`text-[14px] font-bold opacity-80 ${text}`}>
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</Text>
<View className="h-[146px] items-center">
<Fall d={0} f={5600} amp={8}>
<View className="mt-2 size-32 items-center justify-center" style={moon ? undefined : { boxShadow: `0 20px 40px ${kind === 'night' ? 'rgb(190 180 255 / 0.35)' : kind === 'sunset' ? 'rgb(255 150 110 / 0.4)' : 'rgb(240 106 58 / 0.32)'}`, borderRadius: 64 }}>
{/* 저녁·밤엔 오늘 밤 실제 모양의 달 (빛 번짐까지 그려서 공보다 크게) */}
{moon ? (
<View pointerEvents="none" style={{ position: 'absolute', top: -32, left: -32 }}>
<MoonArt pct={moon.pct} waxing={!moon.waning} tone={kind === 'sunset' ? 'dusk' : 'night'} size={192} />
</View>
) : (
<Svg viewBox="-1 -1 2 2" width={128} height={128} style={{ position: 'absolute' }}>
<Defs>
<RadialGradient id="orb" cx="-0.32" cy="-0.4" r="1.4" gradientUnits="userSpaceOnUse">
<Stop offset="0" stopColor={orb.stops[0]} />
<Stop offset="0.3" stopColor={orb.stops[1]} />
<Stop offset="0.68" stopColor={orb.stops[2]} />
<Stop offset="1" stopColor={orb.stops[3]} />
</RadialGradient>
</Defs>
<Rect x="-1" y="-1" width="2" height="2" rx="1" fill="url(#orb)" opacity={gray ? 0.85 : 1} />
</Svg>
)}
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
</Text>
<Text className="font-bagel text-[52px] leading-[52px]" style={orbText}>
{heroVal(feedLoad, score, 'w-[84px] h-10')}
</Text>
</View>
</Fall>
{CLOUDS.slice(0, CLOUD_N[weather]).map((c) => (
<Fall key={c.left} d={c.d} f={c.f} style={{ position: 'absolute', top: c.top, left: c.left }}>
<Cloud w={c.w} h={c.h} night={kind === 'night'} />
</Fall>
))}
</View>
<View className="items-center">
{bubble ? (
<Pressable disabled={!top1} onPress={() => top1 && open({ type: 'gak', indexId: top1.index_id })} accessibilityLabel={top1 ? `${bubble} 1위 ${top1.name} ${top1.score}점, 계산 근거 보기` : undefined}>
<Text className={`text-center font-jua text-[24px] leading-tight ${text}`}>{bubble}</Text>
</Pressable>
) : (
<Skel className="h-6 w-[160px]" />
)}
{top1?.summary ? <Text className={`mt-0.5 text-center text-[15px] font-bold opacity-80 ${text}`}>{top1.summary}</Text> : feedLoad === 'loading' ? <Skel className="mt-1 w-[140px]" /> : null}
{/* 상태 한 줄: 습도·불쾌지수·자외선·미세먼지 단계 이름. 조심할 것만 색 */}
{status.length > 0 && (
<Text className={`mt-1.5 text-center font-jua text-[14px] ${text}`}>
{status.map((x, i) => (
<Text key={x.label}>
{i > 0 && <Text className="opacity-30"> · </Text>}
<Text style={x.tone === 'warn' ? { color: dark ? '#ffb38a' : '#d4552a' } : undefined}>
<Text className={x.tone !== 'warn' ? 'opacity-75' : undefined}>{x.label}</Text> {x.value}
</Text>
</Text>
))}
</Text>
)}
</View>
<View className="mt-2.5 flex-row gap-1 rounded-[18px] p-[3px]" style={{ backgroundColor: dark ? 'rgb(255 255 255 / 0.14)' : 'rgb(255 255 255 / 0.42)' }} accessibilityRole="tablist" accessibilityLabel="하루 흐름, 누르면 그 시간대 하늘로">
{KINDS.map((k) => {
const isNow = k === nowKind;
const s = slotOf(isNow ? 'now' : k);
const on = k === kind;
return (
<Pressable key={k} accessibilityRole="tab" accessibilityState={{ selected: on }} onPress={() => 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}>
<Text className={`text-[13px] font-bold ${on ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{isNow ? '지금' : PREVIEW[k].label}</Text>
<Ic name={k === 'night' && weatherOf(s) === 'clear' ? 'moon' : WEATHER_ICON[weatherOf(s)]} size={22} style={{ marginVertical: 2 }} />
<Text className={`font-jua text-[15px] ${on ? 'text-[#28304a]' : text}`}>{heroVal(todayLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</Text>
</Pressable>
);
})}
</View>
</View>
);
}