示例工程 02-first-app
02-first-app/app/.tsc/main/index.js
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import { CH } from "../shared/ipc";
const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
let mainWindow = null;
let started = false;
function log(record) {
process.stdout.write(`${JSON.stringify(record)}\n`);
}
function resolvePreload() {
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() {
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 readScripts() {
try {
const raw = fsSync.readFileSync(path.join(app.getAppPath(), "package.json"), "utf8");
const parsed = JSON.parse(raw);
return parsed.scripts ?? {};
}
catch {
return {};
}
}
function collectInfo() {
return {
appName: app.getName(),
appVersion: app.getVersion(),
isPackaged: app.isPackaged,
appPath: app.getAppPath(),
resourcesPath: process.resourcesPath,
hasDevServerUrl: Boolean(MAIN_WINDOW_VITE_DEV_SERVER_URL),
electron: process.versions.electron ?? "unknown",
node: process.versions.node,
chrome: process.versions.chrome,
scripts: readScripts(),
};
}
async function runSmoke() {
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.appPath.length > 0,
isPackaged: info.isPackaged,
hasDevServerUrl: info.hasDevServerUrl,
appPath: info.appPath,
scripts: Object.keys(info.scripts).length,
});
app.quit();
}
catch (error) {
log({ evt: "error", message: String(error) });
app.exit(1);
}
}
async function runShots() {
try {
const dir = path.resolve(process.cwd(), "../../../docs/assets/images/02-first-app");
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 = [
{ tab: "structure", file: "02-01-structure.png" },
{ tab: "modes", file: "02-02-modes.png" },
{ tab: "scripts", file: "02-03-scripts.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();
});
//# sourceMappingURL=index.js.map