import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; import type { Item, LoadResult, Source } from "../shared/ipc"; import { counterStore, stepStore } from "./lib/store"; type TabId = "local" | "cross" | "store"; declare global { interface Window { api: { load(): Promise; refresh(): Promise; clearCache(): Promise<{ ok: boolean }>; update(id: string, title: string): Promise; windows(): Promise; openWindow(): Promise<{ ok: boolean }>; reset(): Promise<{ ok: boolean }>; onChanged(cb: (result: LoadResult) => void): () => void; }; __setTab?: (tab: TabId) => void; __snapshot?: () => unknown; __smoke?: () => Promise; } } const tabs: Array<{ id: TabId; label: string }> = [ { id: "local", label: "本地优先" }, { id: "cross", label: "跨窗口" }, { id: "store", label: "30 行 store" }, ]; const role = new URLSearchParams(window.location.search).get("role") ?? "A"; const sourceText: Record = { cache: "内存缓存", disk: "磁盘", network: "网络", broadcast: "跨窗口广播", }; function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } export default function App() { const [tab, setTab] = useState("local"); const [items, setItems] = useState([]); const [source, setSource] = useState("cache"); const [loadedAt, setLoadedAt] = useState(0); const [windows, setWindows] = useState(1); const [busy, setBusy] = useState(false); const counter = useSyncExternalStore( counterStore.subscribe, counterStore.get, ); const step = useSyncExternalStore(stepStore.subscribe, stepStore.get); const apply = useCallback((result: LoadResult) => { setItems(result.items); setSource(result.source); setLoadedAt(result.loadedAt); void window.api.windows().then(setWindows); }, []); useEffect(() => { void window.api.load().then(apply); const off = window.api.onChanged(apply); return off; }, [apply]); useEffect(() => { window.__setTab = (next) => setTab(next); window.__snapshot = () => ({ tab, items, source, windows }); window.__smoke = async () => { await window.api.reset(); const first = await window.api.load(); const second = await window.api.load(); await window.api.clearCache(); const disk = await window.api.load(); const refreshed = await window.api.refresh(); await window.api.openWindow(); await sleep(350); const updated = await window.api.update("note-1", "跨窗口同步的标题"); await sleep(450); const count = await window.api.windows(); apply(updated); setWindows(count); setTab("local"); return { first: first.source, second: second.source, disk: disk.source, refreshed: refreshed.source, updated: updated.source, windows: count, }; }; }, [apply, items, source, tab, windows]); const run = async (action: () => Promise) => { if (busy) return; setBusy(true); try { apply(await action()); } finally { setBusy(false); } }; return (

数据流实验室

缓存 → 磁盘 → 网络 · 主进程广播 · 不引状态库

窗口 {role} 共 {windows} 个窗口
{tab === "local" && (
来源:{sourceText[source]} 加载于 {new Date(loadedAt).toLocaleTimeString("zh-CN")}
{items.map((item) => ( ))}
id 标题 更新时间
{item.id} {item.title} {new Date(item.updatedAt).toLocaleTimeString("zh-CN")}

加载顺序:内存缓存 → 磁盘 JSON → 网络;网络成功后写回磁盘与缓存。

)} {tab === "cross" && (

主进程是唯一写者

两个窗口共享同一份内存缓存与磁盘文件;更新先写主进程,再广播。

当前窗口数: {windows}

同步规则

  • 窗口不直接写磁盘,只发更新请求
  • 主进程写成功后广播 `data:changed`
  • 广播中的来源标记为「跨窗口广播」
  • 窗口关闭后从广播列表移除
)} {tab === "store" && (

30 行订阅式 store

`createStore` 只有 get/set/subscribe,配合 `useSyncExternalStore`。

{counter.count}
步长 step={step.step}

三种做法怎么选

做法 适合 代价
Context + reducer 单窗口、层级深 订阅粒度粗
订阅 store 跨组件、跨窗口 要自己管生命周期
按窗口分片 多窗口状态隔离 同步要主进程参与
)}
); }