nomadro/src/lib/use-remote-config.ts
eric 3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00

92 lines
2.1 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.

"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<NomadroRemoteConfig> };
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 {
// SSR / 首屏:包内默认即 ready,避免整页挡「加载配置」
return {
config: DEFAULT_REMOTE_CONFIG,
fromOffline: true,
ready: true,
};
}
/** 门户远程配置:首屏默认可开 → 网络刷新 → localStorage 兜底 */
export function useRemoteConfig(): Result {
const [state, setState] = useState<Result>(initialState);
useEffect(() => {
let cancelled = false;
const cached = readCache();
if (cached) {
setState({ config: cached, fromOffline: true, ready: true });
}
(async () => {
try {
const res = await fetch("/api/config", { cache: "no-store" });
const data = await res.json().catch(() => ({}));
if (cancelled) return;
if (res.ok && data?.config) {
const config = mergeRemoteConfig(data.config);
writeCache(config);
setState({ config, fromOffline: false, ready: true });
return;
}
} catch {
/* fallthrough */
}
if (cancelled) return;
if (!cached) {
setState({
config: DEFAULT_REMOTE_CONFIG,
fromOffline: true,
ready: true,
});
}
})();
return () => {
cancelled = true;
};
}, []);
return state;
}