示例工程 01-what-is-electron

01-what-is-electron/app/main/index.ts

typescript · 5.0 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import { CH, type AppInfo, type TabId } from "../shared/ipc";

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");

let mainWindow: BrowserWindow | null = null;
let started = false;

function log(record: Record<string, unknown>): void {
  process.stdout.write(`${JSON.stringify(record)}\n`);
}

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(): void {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 720,
    show: false,
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });

  mainWindow.once("ready-to-show", () => {
    mainWindow?.show();
  });

  mainWindow.webContents.on("did-finish-load", () => {
    if (started) return;
    started = true;
    const pid = mainWindow?.webContents.getOSProcessId() ?? -1;
    log({ evt: "window-created", id: mainWindow?.id, pid });
    if (isSmoke) {
      void runSmoke();
    } else if (isShots) {
      void runShots();
    }
  });

  mainWindow.on("closed", () => {
    if (!isSmoke) log({ evt: "window-closed" });
    mainWindow = null;
  });

  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void mainWindow.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
}

function collectInfo(): AppInfo {
  const rendererPid = mainWindow?.webContents.getOSProcessId() ?? -1;
  const metric = app.getAppMetrics().find((item) => item.pid === rendererPid);
  const memoryMB = metric ? Math.round(metric.memory.workingSetSize / 1024) : 0;
  return {
    electron: process.versions.electron ?? "unknown",
    node: process.versions.node,
    chrome: process.versions.chrome,
    platform: process.platform,
    arch: process.arch,
    mainPid: process.pid,
    rendererPid,
    memoryMB,
  };
}

async function runSmoke(): Promise<void> {
  try {
    await new Promise((resolve) => setTimeout(resolve, 300));
    const rawTitle = await mainWindow?.webContents.executeJavaScript(
      "document.querySelector('[data-testid=app-title]')?.textContent ?? ''",
    );
    const title = String(rawTitle ?? "");
    const info = collectInfo();
    log({
      evt: "smoke",
      ok: title.length > 0 && info.rendererPid > 0,
      electron: info.electron,
      node: info.node,
      chrome: info.chrome,
      rendererPid: info.rendererPid,
    });
    app.quit();
  } catch (error) {
    log({ evt: "error", message: String(error) });
    app.exit(1);
  }
}

async function runShots(): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/01-what-is-electron",
    );
    await fs.mkdir(path.join(dir, "raw"), { recursive: true });
    await mainWindow?.webContents.executeJavaScript(
      `new Promise((resolve) => {
        const started = Date.now();
        const tick = () => {
          if (typeof window.__setTab === "function") resolve(true);
          else if (Date.now() - started > 3000) resolve(false);
          else setTimeout(tick, 20);
        };
        tick();
      })`,
    );
    const shots: Array<{ tab: TabId; file: string }> = [
      { tab: "overview", file: "01-01-overview.png" },
      { tab: "processes", file: "01-02-processes.png" },
      { tab: "security", file: "01-03-security.png" },
    ];
    for (const shot of shots) {
      await mainWindow?.webContents.executeJavaScript(
        `window.__setTab(${JSON.stringify(shot.tab)})`,
      );
      await new Promise((resolve) => setTimeout(resolve, 120));
      const image = await mainWindow?.webContents.capturePage();
      if (!image) throw new Error("capturePage returned null");
      const png = image.toPNG();
      await fs.writeFile(path.join(dir, shot.file), png);
      await fs.writeFile(path.join(dir, "raw", shot.file), png);
      log({ evt: "shot", file: shot.file, bytes: png.byteLength });
    }
    app.quit();
  } catch (error) {
    log({ evt: "error", message: String(error) });
    app.exit(1);
  }
}

ipcMain.handle(CH.info, () => collectInfo());

app.whenReady().then(() => {
  log({ evt: "app-ready", electron: process.versions.electron });
  createWindow();
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

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