"use client"; import { useEffect, useState } from "react"; import { DEFAULT_REMOTE_CONFIG, mergeRemoteConfig, type NomadroRemoteConfig, } from "~/lib/remote-config"; const CACHE_KEY = "nomadro_web_remote_config_v1"; type Result = { config: NomadroRemoteConfig; fromOffline: boolean; ready: boolean; }; function readCache(): NomadroRemoteConfig | null { try { if (typeof window === "undefined") return null; const raw = localStorage.getItem(CACHE_KEY); if (!raw) return null; const parsed = JSON.parse(raw) as { config?: Partial }; return mergeRemoteConfig(parsed.config); } catch { return null; } } function writeCache(config: NomadroRemoteConfig) { try { localStorage.setItem( CACHE_KEY, JSON.stringify({ ts: Date.now(), config }), ); } catch { /* ignore */ } } function initialState(): Result { return { config: DEFAULT_REMOTE_CONFIG, fromOffline: true, ready: true, }; } async function fetchFullConfig(): Promise { try { const res = await fetch("/api/config", { cache: "no-store" }); const data = await res.json().catch(() => ({})); if (res.ok && data?.config) return mergeRemoteConfig(data.config); } catch { /* ignore */ } return null; } /** * 门户远程配置: * - 首屏默认 / 缓存兜底 * - SSE `/api/config/stream` 实时推送 version 变更 → 全量拉取 * - visibility / focus 兜底强制检查 */ export function useRemoteConfig(): Result { const [state, setState] = useState(initialState); useEffect(() => { let cancelled = false; let knownVersion = Number(state.config.version) || 0; let es: EventSource | null = null; let reconnectTimer: ReturnType | null = null; const apply = (config: NomadroRemoteConfig, fromOffline: boolean) => { if (cancelled) return; knownVersion = Number(config.version) || knownVersion; writeCache(config); setState({ config, fromOffline, ready: true }); }; const pull = async () => { const config = await fetchFullConfig(); if (!config || cancelled) return; if (Number(config.version) === knownVersion && knownVersion > 0) return; apply(config, false); }; const cached = readCache(); if (cached) { knownVersion = Number(cached.version) || 0; setState({ config: cached, fromOffline: true, ready: true }); } void (async () => { const config = await fetchFullConfig(); if (cancelled) return; if (config) apply(config, false); else if (!cached) { setState({ config: DEFAULT_REMOTE_CONFIG, fromOffline: true, ready: true, }); } })(); const connectSse = () => { if (cancelled || typeof EventSource === "undefined") return; try { es?.close(); es = new EventSource("/api/config/stream"); es.addEventListener("config", (ev) => { try { const data = JSON.parse(String((ev as MessageEvent).data || "{}")) as { version?: number; }; const v = Number(data.version) || 0; if (v && v !== knownVersion) void pull(); } catch { void pull(); } }); es.onerror = () => { es?.close(); es = null; if (cancelled) return; reconnectTimer = setTimeout(connectSse, 5000); }; } catch { /* SSE 不可用时靠 visibility 兜底 */ } }; connectSse(); const onVisible = () => { if (document.visibilityState === "visible") void pull(); }; window.addEventListener("focus", onVisible); document.addEventListener("visibilitychange", onVisible); return () => { cancelled = true; es?.close(); if (reconnectTimer) clearTimeout(reconnectTimer); window.removeEventListener("focus", onVisible); document.removeEventListener("visibilitychange", onVisible); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- mount once }, []); return state; }