import { kindOfHour, kst, type TimeKind } from '@nalssigak/shared/lib'; import { createContext, use, useEffect, useMemo, useState, type ReactNode } from 'react'; import { Uniwind } from 'uniwind'; /** 화면 전체 하늘의 시간대. 히어로에서 고른 미리보기는 탭을 옮겨도 유지된다 */ export type SkyApi = { kind: TimeKind; preview: TimeKind | null; setServerKind: (k: TimeKind | null) => void; setPreview: (k: TimeKind | null) => void }; const SkyContext = createContext(null); /** 밤에만 어두운 테마 (기기 다크 모드와 상관없이 하늘 시간대를 따른다). 같으면 건드리지 않는다 */ function applyTheme(kind: TimeKind) { const theme = kind === 'night' ? 'dark' : 'light'; if (Uniwind.currentTheme !== theme) Uniwind.setTheme(theme); } // 첫 화면을 그리기 전에 지금 시각의 테마로 맞춰, 그리는 도중에 테마가 바뀌지 않게 한다 const t0 = kst(new Date()); applyTheme(kindOfHour(t0.h, t0.mo, t0.mi)); export function useSky() { const ctx = use(SkyContext); if (!ctx) throw new Error('useSky must be used inside SkyProvider'); return ctx; } export function SkyProvider({ children }: { children: ReactNode }) { const [preview, setPreview] = useState(null); const [serverKind, setServerKind] = useState(null); const [now, setNow] = useState(() => new Date()); useEffect(() => { const id = setInterval(() => setNow(new Date()), 60000); return () => clearInterval(id); }, []); const t = kst(now); const kind = preview ?? serverKind ?? kindOfHour(t.h, t.mo, t.mi); useEffect(() => applyTheme(kind), [kind]); const api = useMemo(() => ({ kind, preview, setPreview, setServerKind }), [kind, preview]); return {children}; }