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

350 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<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; 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<View>(null);
// 내일 스위치: 내일 칸 날씨는 켤 때 받고, 시간대는 화면 전체 하늘과 따로 히어로 안에서만 고른다 (웹 TodayPage Hero)
const [tmr, setTmr] = useState(false);
const [tmrKind, setTmrKind] = useState<TimeKind>('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 (
<View ref={shot} collapsable={false} 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>
)}
<View className="z-[3] flex-row items-center justify-between">
<View className="flex-row items-center gap-2">
<View className="flex-row rounded-full p-[3px]" style={{ backgroundColor: strip }} accessibilityRole="radiogroup" accessibilityLabel="오늘 또는 내일 날씨">
{(
[
[false, '오늘'],
[true, '내일'],
] as const
).map(([v, l]) => (
<Pressable key={l} onPress={() => switchDay(v)} accessibilityRole="radio" accessibilityState={{ checked: tmr === v }} className={`rounded-full px-2.5 py-0.5 ${tmr === v ? 'bg-white' : ''}`}>
<Text className={`font-jua text-[13px] ${tmr === v ? 'text-[#d4552a]' : `opacity-75 ${text}`}`}>{l}</Text>
</Pressable>
))}
</View>
<Text className={`text-[13px] font-bold opacity-80 ${text}`}>
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일
</Text>
</View>
<View className="flex-row items-center">
{post && (
<>
<Pressable onPress={like.toggle} hitSlop={6} accessibilityRole="button" accessibilityState={{ selected: like.liked }} accessibilityLabel={like.failed ? '좋아요를 반영하지 못했어요. 다시 눌러 주세요' : '오늘 날씨 좋아요'} className={`h-8 flex-row items-center gap-1 px-[5px] ${like.liked ? '' : 'opacity-80'}`}>
<HeartIcon size={22} color={like.liked ? '#ff3b5c' : icon} filled={like.liked} />
{like.count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{like.count.toLocaleString()}</Text>}
</Pressable>
<Pressable onPress={() => 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">
<CommentIcon size={22} color={icon} />
{post.comment_count > 0 && <Text className={`text-[13px] font-extrabold ${text}`}>{post.comment_count.toLocaleString()}</Text>}
</Pressable>
</>
)}
<Pressable onPress={share} hitSlop={6} accessibilityRole="button" accessibilityLabel="오늘 날씨 보내기" className="h-8 flex-row items-center px-[5px] opacity-80">
<SendIcon size={22} color={icon} />
</Pressable>
</View>
</View>
<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>
)}
{/* 점수 근거가 있으면 해를 눌러도 근거 창 */}
<Pressable disabled={!why || score == null} onPress={openWhy} className="items-center" accessibilityLabel={why && score != null ? `${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기` : undefined}>
<Text className="font-jua text-[12px]" style={orbText}>
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : 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>
</Pressable>
</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>
))}
{why && score != null && (
<Text onPress={openWhy} accessibilityRole="button" accessibilityLabel={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} style={{ color: dark ? '#ffb38a' : '#d4552a' }}>
{' '}· 점수 근거 ›
</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 = !tmr && k === nowKind;
const s = slotOf(isNow ? 'now' : k);
const on = k === kind;
return (
<Pressable key={k} accessibilityRole="tab" accessibilityState={{ selected: on }} onPress={() => (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}>
<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(slotsLoad, s?.temp_c != null ? deg(s.temp_c) : null, 'w-7')}</Text>
</Pressable>
);
})}
</View>
</View>
);
}