示例工程 14-react-bootstrap

14-react-bootstrap/app/src/App.tsx

tsx · 9.7 KB

import { useCallback, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import type { Counts, LabInfo } from "../shared/ipc";
import type { TabId } from "./lib/api";
import { useIpcOnce } from "./hooks/useIpcOnce";

const rendererLoadedAt = Date.now();
let hmrUpdates = 0;
if (import.meta.hot) {
  import.meta.hot.on("vite:afterUpdate", () => {
    hmrUpdates += 1;
  });
}

const tabs: Array<{ id: TabId; label: string }> = [
  { id: "strict", label: "StrictMode" },
  { id: "architecture", label: "目录分层" },
  { id: "hmr", label: "HMR 边界" },
];

const emptyCounts: Counts = {
  counts: {},
  idem: { requests: 0, records: 0 },
};

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

function CountCard({
  label,
  value,
  hint,
  testId,
}: {
  label: string;
  value: number | string;
  hint: string;
  testId?: string;
}) {
  return (
    <div className="card">
      <div className="card-label">{label}</div>
      <div className="card-value" data-testid={testId}>
        {value}
      </div>
      <p className="hint">{hint}</p>
    </div>
  );
}

function NaiveProbe({ refresh }: { refresh: () => Promise<void> }) {
  useEffect(() => {
    void window.api.bump("naive").then(refresh);
  }, [refresh]);
  return null;
}

function RefProbe({ refresh }: { refresh: () => Promise<void> }) {
  useIpcOnce(() => {
    void window.api.bump("ref").then(refresh);
  });
  return null;
}

function IdempotentProbe({ refresh }: { refresh: () => Promise<void> }) {
  useEffect(() => {
    void window.api.idem("strict-mount").then(refresh);
  }, [refresh]);
  return null;
}

function ProbeSet({ refresh }: { refresh: () => Promise<void> }) {
  return (
    <>
      <NaiveProbe refresh={refresh} />
      <RefProbe refresh={refresh} />
      <IdempotentProbe refresh={refresh} />
    </>
  );
}

function EventProbe({ refresh }: { refresh: () => Promise<void> }) {
  return (
    <button
      className="mini"
      data-testid="event-button"
      onClick={() => {
        void window.api.bump("event").then(refresh);
      }}
    >
      点我执行一次 IPC
    </button>
  );
}

function StrictTab({
  counts,
  revision,
  refresh,
}: {
  counts: Counts;
  revision: number;
  refresh: () => Promise<void>;
}) {
  return (
    <div className="section">
      <h2>StrictMode 下的副作用</h2>
      <p className="hint">
        开发模式下 StrictMode 会挂载 → 清理 → 再挂载;写在{" "}
        <code>useEffect</code> 里的 IPC
        会被调用两次。下面四个探针展示问题与三种修法。
      </p>
      <ProbeSet key={revision} refresh={refresh} />
      <div className="grid summary">
        <CountCard
          label="直接调用(反例)"
          value={counts.counts.naive ?? 0}
          hint="effect 里直接 bump,开发模式 2 次"
          testId="naive-count"
        />
        <CountCard
          label="useRef 门闩"
          value={counts.counts.ref ?? 0}
          hint="同一个实例只放行一次"
          testId="ref-count"
        />
        <CountCard
          label="幂等键 records"
          value={counts.idem.records}
          hint={`请求 ${counts.idem.requests} 次,只落库 1 条`}
          testId="idem-count"
        />
        <CountCard
          label="事件触发"
          value={counts.counts.event ?? 0}
          hint="不在挂载时执行,点击才调用"
          testId="event-count"
        />
      </div>
      <div className="row">
        <EventProbe refresh={refresh} />
        <span className="hint">
          事件触发是第三种修法:把副作用从 effect 移到用户动作。
        </span>
      </div>
      <table className="table" data-testid="strategy-table">
        <thead>
          <tr>
            <th>修法</th>
            <th>适用</th>
            <th>代价</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>useRef 门闩</td>
            <td>确实只需要挂载时执行一次</td>
            <td>组件实例重建会重新执行</td>
          </tr>
          <tr>
            <td>幂等键</td>
            <td>请求可重放,主进程能去重</td>
            <td>需要设计稳定的 opId</td>
          </tr>
          <tr>
            <td>事件触发</td>
            <td>操作本来就由用户发起</td>
            <td>不能自动完成初始化</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

function ArchitectureTab() {
  const tree = `src/
├── main.tsx              # createRoot + StrictMode
├── App.tsx               # 页签与探针编排
├── components/
│   └── (本章把探针留在 App.tsx)
├── hooks/
│   └── useIpcOnce.ts     # 只执行一次的 IPC
├── lib/
│   └── api.ts            # window.api 类型声明
└── styles.css            # 最小原生 CSS,ch15 再上 Tailwind`;
  return (
    <div className="section">
      <h2>渲染进程目录分层</h2>
      <div className="two-col">
        <pre className="code tree-code" data-testid="tree-code">
          {tree}
        </pre>
        <div>
          <div className="panel">
            <div className="panel-label">为什么先分层再上组件库</div>
            <p className="hint">
              入口只管挂载;页面管编排;hooks 管复用;lib 管契约。ch15 的
              Tailwind 与 ch16 的组件层只改样式与组件目录,不动 IPC。
            </p>
          </div>
          <div className="panel">
            <div className="panel-label">CSP 与入口</div>
            <p className="hint">
              开发态 Vite 注入样式需要 <code>style-src 'unsafe-inline'</code>;
              生产构建输出独立 CSS 后应收紧到 <code>'self'</code>,第 46
              章复核。
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

function HmrTab({ info }: { info: LabInfo | null }) {
  return (
    <div className="section">
      <h2>HMR 只作用于渲染进程</h2>
      <div className="grid summary">
        <CountCard
          label="main PID"
          value={info?.mainPid ?? "—"}
          hint="改 renderer 不会换 PID"
          testId="main-pid"
        />
        <CountCard
          label="renderer 加载"
          value={new Date(rendererLoadedAt).toLocaleTimeString("zh-CN", {
            hour12: false,
          })}
          hint="HMR 后模块时间会变"
        />
        <CountCard
          label="HMR"
          value={import.meta.hot ? "已连接" : "生产构建"}
          hint="只有 dev server 才有"
          testId="hmr-status"
        />
        <CountCard
          label="HMR 更新"
          value={hmrUpdates}
          hint="本次会话的 afterUpdate 次数"
        />
      </div>
      <div className="panel">
        <div className="panel-label">环境</div>
        <pre className="code" data-testid="env-code">
          {JSON.stringify(
            {
              DEV: import.meta.env.DEV,
              MODE: import.meta.env.MODE,
              protocol: location.protocol,
              electron: info?.electron ?? "—",
              chrome: info?.chrome ?? "—",
              node: info?.node ?? "—",
            },
            null,
            2,
          )}
        </pre>
      </div>
      <p className="hint">
        手动验证:保持窗口打开,修改本文件里的任意文案;页面热更新,main PID
        不变。 改 <code>main/index.ts</code> 会重启应用,PID 变化。
      </p>
    </div>
  );
}

declare global {
  interface Window {
    __mountError?: () => void;
  }
}

if (import.meta.env.DEV) {
  window.__mountError = () => {
    createRoot(document.getElementById("missing-root") as HTMLElement);
  };
}

export default function App() {
  const [tab, setTab] = useState<TabId>("strict");
  const [counts, setCounts] = useState<Counts>(emptyCounts);
  const [info, setInfo] = useState<LabInfo | null>(null);
  const [revision, setRevision] = useState(0);

  const refresh = useCallback(async () => {
    setCounts(await window.api.counts());
  }, []);

  useEffect(() => {
    void refresh();
    void window.api.info().then(setInfo);
  }, [refresh]);

  useEffect(() => {
    window.__setTab = (next) => setTab(next);
    window.__snapshot = () => ({
      tab,
      counts: counts.counts,
      idem: counts.idem,
    });
    window.__smoke = async () => {
      await window.api.reset();
      setRevision((value) => value + 1);
      await sleep(400);
      const next = await window.api.counts();
      setCounts(next);
      setTab("strict");
      return {
        naive: next.counts.naive ?? 0,
        ref: next.counts.ref ?? 0,
        idemRequests: next.idem.requests,
        idemRecords: next.idem.records,
        event: next.counts.event ?? 0,
      };
    };
  }, [counts, tab]);

  return (
    <div>
      <header className="header">
        <div>
          <h1 data-testid="app-title">React 接入实验室</h1>
          <p className="subtitle">React 19 · StrictMode · HMR · 目录分层</p>
        </div>
        <nav className="tabs">
          {tabs.map((item) => (
            <button
              key={item.id}
              className={`tab${tab === item.id ? " active" : ""}`}
              data-testid={`tab-${item.id}`}
              onClick={() => setTab(item.id)}
            >
              {item.label}
            </button>
          ))}
        </nav>
      </header>
      <main className="content">
        {tab === "strict" && (
          <StrictTab counts={counts} revision={revision} refresh={refresh} />
        )}
        {tab === "architecture" && <ArchitectureTab />}
        {tab === "hmr" && <HmrTab info={info} />}
      </main>
    </div>
  );
}