示例工程 17-react-state-and-data

17-react-state-and-data/app/src/App.tsx

tsx · 13 KB

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<LoadResult>;
      refresh(): Promise<LoadResult>;
      clearCache(): Promise<{ ok: boolean }>;
      update(id: string, title: string): Promise<LoadResult>;
      windows(): Promise<number>;
      openWindow(): Promise<{ ok: boolean }>;
      reset(): Promise<{ ok: boolean }>;
      onChanged(cb: (result: LoadResult) => void): () => void;
    };
    __setTab?: (tab: TabId) => void;
    __snapshot?: () => unknown;
    __smoke?: () => Promise<unknown>;
  }
}

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<Source, string> = {
  cache: "内存缓存",
  disk: "磁盘",
  network: "网络",
  broadcast: "跨窗口广播",
};

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export default function App() {
  const [tab, setTab] = useState<TabId>("local");
  const [items, setItems] = useState<Item[]>([]);
  const [source, setSource] = useState<Source>("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<LoadResult>) => {
    if (busy) return;
    setBusy(true);
    try {
      apply(await action());
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="min-h-screen bg-surface px-8 py-7 text-text">
      <header className="flex items-end justify-between gap-6 border-b border-border pb-4">
        <div>
          <h1 className="text-2xl font-semibold" data-testid="app-title">
            数据流实验室
          </h1>
          <p className="mt-1 text-sm text-muted">
            缓存 → 磁盘 → 网络 · 主进程广播 · 不引状态库
          </p>
        </div>
        <div className="flex items-center gap-2">
          <span className="rounded-full bg-primary-soft px-3 py-1 text-xs text-primary">
            窗口 {role}
          </span>
          <span
            className="rounded-full border border-border px-3 py-1 text-xs text-muted"
            data-testid="window-count"
          >
            共 {windows} 个窗口
          </span>
        </div>
      </header>

      <nav className="mt-5 flex gap-1" data-testid="tabs">
        {tabs.map((item) => (
          <button
            key={item.id}
            className={`rounded-md border px-3 py-1.5 text-sm ${
              tab === item.id
                ? "border-border bg-panel font-semibold text-primary"
                : "border-transparent text-muted hover:bg-panel"
            }`}
            data-testid={`tab-${item.id}`}
            onClick={() => setTab(item.id)}
          >
            {item.label}
          </button>
        ))}
      </nav>

      <main className="mt-6">
        {tab === "local" && (
          <section>
            <div className="flex items-center gap-3">
              <span
                className="rounded-full bg-primary-soft px-3 py-1 text-xs text-primary"
                data-testid="source-badge"
              >
                来源:{sourceText[source]}
              </span>
              <span className="text-xs text-muted">
                加载于 {new Date(loadedAt).toLocaleTimeString("zh-CN")}
              </span>
            </div>
            <div className="mt-3 flex flex-wrap gap-2">
              <button
                className="rounded-card bg-primary px-3 py-1.5 text-sm text-primary-foreground"
                onClick={() => void run(() => window.api.refresh())}
                disabled={busy}
                data-testid="refresh-button"
              >
                刷新(网络)
              </button>
              <button
                className="rounded-card border border-border px-3 py-1.5 text-sm"
                onClick={() => void window.api.clearCache()}
                data-testid="clear-cache-button"
              >
                清内存缓存
              </button>
              <button
                className="rounded-card border border-border px-3 py-1.5 text-sm"
                onClick={() =>
                  void run(() => window.api.update("note-1", "手动更新的标题"))
                }
                data-testid="update-button"
              >
                更新第一条
              </button>
            </div>
            <table
              className="mt-4 w-full border-collapse text-sm"
              data-testid="item-table"
            >
              <thead>
                <tr className="bg-panel text-left text-xs text-muted">
                  <th className="border border-border px-3 py-2">id</th>
                  <th className="border border-border px-3 py-2">标题</th>
                  <th className="border border-border px-3 py-2">更新时间</th>
                </tr>
              </thead>
              <tbody>
                {items.map((item) => (
                  <tr key={item.id} data-testid="item-row">
                    <td className="border border-border px-3 py-2 font-mono text-xs">
                      {item.id}
                    </td>
                    <td className="border border-border px-3 py-2">
                      {item.title}
                    </td>
                    <td className="border border-border px-3 py-2 font-mono text-xs">
                      {new Date(item.updatedAt).toLocaleTimeString("zh-CN")}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            <p className="mt-3 text-xs text-muted">
              加载顺序:内存缓存 → 磁盘 JSON → 网络;网络成功后写回磁盘与缓存。
            </p>
          </section>
        )}

        {tab === "cross" && (
          <section>
            <div className="grid grid-cols-2 gap-4">
              <div className="rounded-card border border-border bg-panel p-5">
                <h2 className="text-sm font-semibold">主进程是唯一写者</h2>
                <p className="mt-1 text-sm text-muted">
                  两个窗口共享同一份内存缓存与磁盘文件;更新先写主进程,再广播。
                </p>
                <button
                  className="mt-4 rounded-card bg-primary px-3 py-1.5 text-sm text-primary-foreground"
                  onClick={() => void window.api.openWindow()}
                  data-testid="open-window-button"
                >
                  打开第二个窗口
                </button>
                <p className="mt-3 text-xs text-muted">
                  当前窗口数:
                  <code data-testid="cross-window-count">{windows}</code>
                </p>
              </div>
              <div className="rounded-card border border-border bg-panel p-5">
                <h2 className="text-sm font-semibold">同步规则</h2>
                <ul className="mt-2 list-disc pl-5 text-sm text-muted">
                  <li>窗口不直接写磁盘,只发更新请求</li>
                  <li>主进程写成功后广播 `data:changed`</li>
                  <li>广播中的来源标记为「跨窗口广播」</li>
                  <li>窗口关闭后从广播列表移除</li>
                </ul>
              </div>
            </div>
          </section>
        )}

        {tab === "store" && (
          <section>
            <div className="grid grid-cols-2 gap-4">
              <div className="rounded-card border border-border bg-panel p-5">
                <h2 className="text-sm font-semibold">30 行订阅式 store</h2>
                <p className="mt-1 text-sm text-muted">
                  `createStore` 只有 get/set/subscribe,配合
                  `useSyncExternalStore`。
                </p>
                <div className="mt-4 flex items-center gap-3">
                  <button
                    className="h-9 rounded-card border border-border px-3"
                    onClick={() =>
                      counterStore.set({ count: counter.count - step.step })
                    }
                    data-testid="store-minus"
                  >
                    −
                  </button>
                  <span
                    className="min-w-16 text-center font-mono text-2xl"
                    data-testid="store-count"
                  >
                    {counter.count}
                  </span>
                  <button
                    className="h-9 rounded-card bg-primary px-3 text-primary-foreground"
                    onClick={() =>
                      counterStore.set({ count: counter.count + step.step })
                    }
                    data-testid="store-plus"
                  >
                    +
                  </button>
                </div>
                <div className="mt-4 flex items-center gap-2 text-sm">
                  <span className="text-muted">步长</span>
                  <button
                    className="h-8 rounded border border-border px-2"
                    onClick={() => stepStore.set({ step: 1 })}
                  >
                    1
                  </button>
                  <button
                    className="h-8 rounded border border-border px-2"
                    onClick={() => stepStore.set({ step: 5 })}
                  >
                    5
                  </button>
                  <code className="text-xs text-muted">step={step.step}</code>
                </div>
              </div>
              <div className="rounded-card border border-border bg-panel p-5">
                <h2 className="text-sm font-semibold">三种做法怎么选</h2>
                <table className="mt-2 w-full text-xs">
                  <thead>
                    <tr className="text-left text-muted">
                      <th className="py-1">做法</th>
                      <th className="py-1">适合</th>
                      <th className="py-1">代价</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td className="py-1">Context + reducer</td>
                      <td>单窗口、层级深</td>
                      <td>订阅粒度粗</td>
                    </tr>
                    <tr>
                      <td className="py-1">订阅 store</td>
                      <td>跨组件、跨窗口</td>
                      <td>要自己管生命周期</td>
                    </tr>
                    <tr>
                      <td className="py-1">按窗口分片</td>
                      <td>多窗口状态隔离</td>
                      <td>同步要主进程参与</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </section>
        )}
      </main>
    </div>
  );
}