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

17-react-state-and-data/app/main/index.ts

typescript · 9.2 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { CH, type Item, type LoadResult, type Source } from "../shared/ipc";

app.setName("Data Flow Lab");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const smokeData = isSmoke
  ? path.join(os.tmpdir(), `data-flow-smoke-${process.pid}`)
  : "";
if (smokeData) app.setPath("userData", smokeData);

let cache: Item[] | null = null;
let remoteVersion = 0;
let statePath = "";
let secondary: BrowserWindow | null = null;

function baseItems(version: number): Item[] {
  return [
    { id: "note-1", title: `网络数据 ${version}`, updatedAt: Date.now() },
    { id: "note-2", title: "第二条", updatedAt: Date.now() - 1000 },
    { id: "note-3", title: "第三条", updatedAt: Date.now() - 2000 },
  ];
}

function readDisk(): Item[] | null {
  try {
    const raw = fsSync.readFileSync(statePath, "utf8");
    const parsed = JSON.parse(raw) as { items?: Item[] };
    return Array.isArray(parsed.items) ? parsed.items : null;
  } catch {
    return null;
  }
}

function writeDisk(items: Item[]): void {
  try {
    fsSync.mkdirSync(path.dirname(statePath), { recursive: true });
    fsSync.writeFileSync(statePath, JSON.stringify({ items }, null, 2), "utf8");
  } catch {
    // 写盘失败时仍用内存缓存继续。
  }
}

function result(items: Item[], source: Source): LoadResult {
  return { items, source, loadedAt: Date.now() };
}

function load(forceNetwork: boolean): LoadResult {
  if (!forceNetwork && cache) return result(cache, "cache");
  if (!forceNetwork) {
    const disk = readDisk();
    if (disk) {
      cache = disk;
      return result(disk, "disk");
    }
  }
  remoteVersion += 1;
  const items = baseItems(remoteVersion);
  cache = items;
  writeDisk(items);
  return result(items, "network");
}

function broadcast(items: Item[]): void {
  const payload = result(items, "broadcast");
  for (const win of BrowserWindow.getAllWindows()) {
    if (!win.isDestroyed()) win.webContents.send(CH.changed, payload);
  }
}

function resolvePreload(): string {
  const candidates = [
    path.join(__dirname, "preload.cjs"),
    path.join(__dirname, "../preload/index.cjs"),
    path.join(__dirname, "preload.js"),
  ];
  return (
    candidates.find((candidate) => fsSync.existsSync(candidate)) ??
    candidates[0] ??
    ""
  );
}

function createWindow(title: string, role = "A"): BrowserWindow {
  const win = new BrowserWindow({
    width: 1000,
    height: 720,
    show: false,
    title,
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  win.once("ready-to-show", () => {
    if (!win.isDestroyed()) win.show();
  });
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
    url.searchParams.set("role", role);
    void win.loadURL(url.toString());
  } else {
    void win.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
      { query: { role } },
    );
  }
  return win;
}

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

async function evalRenderer<T>(win: BrowserWindow, code: string): Promise<T> {
  let lastError: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await win.webContents.executeJavaScript(code)) as T;
    } catch (error) {
      lastError = error;
      await delay(200);
    }
  }
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

async function waitForRenderer(win: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 120; attempt += 1) {
    if (win.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        win,
        "typeof window.__smoke === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type SmokeResult = {
  first: string;
  second: string;
  disk: string;
  refreshed: string;
  updated: string;
  windows: number;
};

async function runSmoke(): Promise<void> {
  try {
    const win = createWindow("数据流实验室 — 窗口 A");
    await waitForRenderer(win);
    await delay(500);
    await waitForRenderer(win);
    const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");

    const others = BrowserWindow.getAllWindows().filter(
      (candidate) => candidate.id !== win.id && !candidate.isDestroyed(),
    );
    const second = others[0];
    let secondTitle = "";
    if (second) {
      await waitForRenderer(second);
      await delay(200);
      const snapshot = await evalRenderer<{
        items: Array<{ title: string }>;
        windows: number;
      }>(second, "window.__snapshot()");
      secondTitle = snapshot.items[0]?.title ?? "";
    }

    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.first === "network" &&
          result.second === "cache" &&
          result.disk === "disk" &&
          result.refreshed === "network" &&
          result.windows >= 2 &&
          secondTitle === "跨窗口同步的标题",
        ...result,
        secondTitle,
      })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

async function setTab(win: BrowserWindow, tab: string): Promise<void> {
  await evalRenderer(
    win,
    `window.__setTab && window.__setTab(${JSON.stringify(tab)})`,
  );
}

async function capture(
  win: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await win.webContents.capturePage();
  if (image.isEmpty()) throw new Error(`empty capture: ${file}`);
  const png = image.toPNG();
  fsSync.writeFileSync(path.join(dir, file), png);
  fsSync.writeFileSync(path.join(dir, "raw", file), png);
}

async function runShots(): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/17-react-state-and-data",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    const win = createWindow("数据流实验室 — 窗口 A");
    await waitForRenderer(win);
    await delay(500);
    await waitForRenderer(win);
    await evalRenderer(win, "window.__smoke()");
    await delay(300);
    await setTab(win, "local");
    await delay(250);
    await capture(win, dir, "17-01-local-first.png");
    const second = BrowserWindow.getAllWindows().find(
      (candidate) => candidate.id !== win.id && !candidate.isDestroyed(),
    );
    if (second) {
      await waitForRenderer(second);
      await delay(250);
      await capture(second, dir, "17-02-second-window.png");
    }
    await setTab(win, "store");
    await delay(250);
    await capture(win, dir, "17-03-store.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.load, () => load(false));
ipcMain.handle(CH.refresh, () => load(true));
ipcMain.handle(CH.clearCache, () => {
  cache = null;
  return { ok: true };
});
ipcMain.handle(
  CH.update,
  (_event, raw: { id?: string; title?: string } | undefined) => {
    const items = cache ?? readDisk() ?? baseItems(remoteVersion);
    const id = typeof raw?.id === "string" ? raw.id : "";
    const title = typeof raw?.title === "string" ? raw.title : "";
    const next = items.map((item) =>
      item.id === id ? { ...item, title, updatedAt: Date.now() } : item,
    );
    cache = next;
    writeDisk(next);
    broadcast(next);
    return result(next, "broadcast");
  },
);
ipcMain.handle(CH.windows, () => BrowserWindow.getAllWindows().length);
ipcMain.handle(CH.openWindow, () => {
  if (!secondary || secondary.isDestroyed()) {
    secondary = createWindow("数据流实验室 — 窗口 B", "B");
  } else {
    secondary.focus();
  }
  return { ok: true };
});
ipcMain.handle(CH.reset, () => {
  cache = null;
  remoteVersion = 0;
  try {
    fsSync.rmSync(statePath, { force: true });
  } catch {
    // 忽略。
  }
  return { ok: true };
});

app.whenReady().then(() => {
  statePath = path.join(app.getPath("userData"), "state.json");
  if (isSmoke) {
    void runSmoke();
  } else if (isShots) {
    void runShots();
  } else {
    createWindow("数据流实验室 — 窗口 A");
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow("数据流实验室 — 窗口 A");
    }
  });
});

app.on("will-quit", () => {
  if (smokeData) {
    try {
      fsSync.rmSync(smokeData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (!isSmoke && !isShots && process.platform !== "darwin") app.quit();
});