示例工程 14-react-bootstrap

14-react-bootstrap/app/main/index.ts

typescript · 7.4 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 Counts, type LabInfo } from "../shared/ipc";

app.setName("React Bootstrap Lab");

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

const mainStartedAt = Date.now();
const counts = new Map<string, number>();
const seenOps = new Set<string>();
let idemRequests = 0;

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(): BrowserWindow {
  const win = new BrowserWindow({
    width: 1100,
    height: 760,
    show: false,
    title: "React 接入实验室",
    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) {
    void win.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void win.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  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");
}

function snapshot(): Counts {
  return {
    counts: Object.fromEntries(counts),
    idem: { requests: idemRequests, records: seenOps.size },
  };
}

type SmokeResult = {
  naive: number;
  ref: number;
  idemRequests: number;
  idemRecords: number;
  event: number;
};

async function runDiagnostics(): Promise<void> {
  try {
    const win = createWindow();
    await waitForRenderer(win);
    const result = await evalRenderer<{
      ok: boolean;
      name?: string;
      message?: string;
      stack?: string[];
    }>(
      win,
      `(() => {
        try {
          window.__mountError();
          return { ok: true };
        } catch (error) {
          return {
            ok: false,
            name: error.name,
            message: error.message,
            stack: String(error.stack || "").split("\\n").slice(0, 4),
          };
        }
      })()`,
    );
    process.stdout.write(
      `${JSON.stringify({ evt: "diagnostics", ...result })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "diagnostics", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

async function runSmoke(): Promise<void> {
  try {
    const win = createWindow();
    await waitForRenderer(win);
    await delay(600);
    await waitForRenderer(win);
    const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.naive === 2 &&
          result.ref === 1 &&
          result.idemRequests === 2 &&
          result.idemRecords === 1 &&
          result.event === 0,
        ...result,
      })}\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/14-react-bootstrap",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    const win = createWindow();
    await waitForRenderer(win);
    await delay(600);
    await waitForRenderer(win);
    await evalRenderer(win, "window.__smoke()");
    await delay(300);
    await setTab(win, "strict");
    await delay(200);
    await capture(win, dir, "14-01-strictmode.png");
    await setTab(win, "architecture");
    await delay(200);
    await capture(win, dir, "14-02-architecture.png");
    await setTab(win, "hmr");
    await delay(200);
    await capture(win, dir, "14-03-hmr.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.reset, () => {
  counts.clear();
  seenOps.clear();
  idemRequests = 0;
});

ipcMain.handle(CH.bump, (_event, key: unknown) => {
  if (typeof key !== "string" || key.length === 0 || key.length > 40) return 0;
  const next = (counts.get(key) ?? 0) + 1;
  counts.set(key, next);
  return next;
});

ipcMain.handle(CH.idem, (_event, opId: unknown): Counts["idem"] => {
  if (typeof opId !== "string" || opId.length === 0) {
    return { requests: idemRequests, records: seenOps.size };
  }
  idemRequests += 1;
  seenOps.add(opId);
  return { requests: idemRequests, records: seenOps.size };
});

ipcMain.handle(CH.counts, () => snapshot());

ipcMain.handle(CH.info, (): LabInfo => ({
  mainPid: process.pid,
  mainStartedAt,
  electron: process.versions.electron,
  chrome: process.versions.chrome,
  node: process.versions.node,
}));

app.whenReady().then(() => {
  if (isDiagnostics) {
    void runDiagnostics();
  } else if (isSmoke) {
    void runSmoke();
  } else if (isShots) {
    void runShots();
  } else {
    createWindow();
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

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();
});