示例工程 22-theming-and-native-appearance
22-theming-and-native-appearance/app/main/index.ts
import {
app,
BrowserWindow,
ipcMain,
nativeTheme,
type IpcMainInvokeEvent,
} from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
assertThemeSet,
CH,
isThemeSource,
type ThemeSource,
type ThemeState,
} from "../shared/ipc";
app.setName("Appearance 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(), `appearance-lab-smoke-${process.pid}`)
: "";
if (smokeData) app.setPath("userData", smokeData);
function storeFile(): string {
return path.join(app.getPath("userData"), "theme.json");
}
function readStoredSource(): ThemeSource {
try {
const raw: unknown = JSON.parse(fsSync.readFileSync(storeFile(), "utf8"));
if (
typeof raw === "object" &&
raw !== null &&
isThemeSource((raw as { source?: unknown }).source)
) {
return (raw as { source: ThemeSource }).source;
}
} catch {
// 首次启动或文件损坏:回到跟随系统。
}
return "system";
}
function writeStoredSource(source: ThemeSource): void {
const file = storeFile();
const temp = `${file}.tmp`;
fsSync.mkdirSync(path.dirname(file), { recursive: true });
fsSync.writeFileSync(
temp,
`${JSON.stringify({ source }, null, 2)}\n`,
"utf8",
);
fsSync.renameSync(temp, file);
}
function themeState(): ThemeState {
return {
source: nativeTheme.themeSource,
shouldUseDarkColors: nativeTheme.shouldUseDarkColors,
platform: process.platform,
};
}
function broadcastTheme(): void {
const state = themeState();
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) win.webContents.send(CH.themeChanged, state);
}
}
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 initial = nativeTheme.shouldUseDarkColors ? "dark" : "light";
const win = new BrowserWindow({
width: 1100,
height: 860,
minWidth: 860,
minHeight: 640,
show: false,
title: "主题与原生外观工作台",
backgroundColor: initial === "dark" ? "#0f172a" : "#ffffff",
titleBarStyle: process.platform === "darwin" ? "hiddenInset" : "default",
trafficLightPosition:
process.platform === "darwin" ? { x: 18, y: 20 } : undefined,
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("theme", initial);
void win.loadURL(url.toString());
} else {
void win.loadFile(
path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
{ query: { theme: initial } },
);
}
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 = {
initialSource: string;
darkApplied: boolean;
lightApplied: boolean;
systemSource: string;
darkSurface: string;
lightSurface: string;
mediaDark: boolean;
platform: string;
};
async function runSmoke(): Promise<void> {
try {
const win = createWindow();
await waitForRenderer(win);
await delay(500);
await waitForRenderer(win);
const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");
const stored: unknown = JSON.parse(
fsSync.readFileSync(storeFile(), "utf8"),
);
const storedSource =
typeof stored === "object" && stored !== null
? (stored as { source?: unknown }).source
: "";
process.stdout.write(
`${JSON.stringify({
evt: "smoke",
ok:
result.darkApplied &&
result.lightApplied &&
result.systemSource === "system" &&
result.darkSurface === "#0f172a" &&
result.lightSurface === "#ffffff" &&
storedSource === "system" &&
nativeTheme.themeSource === "system" &&
/^#(?:ffffff|0f172a)$/i.test(win.getBackgroundColor()),
storedSource,
nativeSource: nativeTheme.themeSource,
background: win.getBackgroundColor(),
...result,
})}\n`,
);
app.quit();
} catch (error) {
process.stdout.write(
`${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
);
app.exit(1);
}
}
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/22-theming-and-native-appearance",
);
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
const win = createWindow();
await waitForRenderer(win);
await delay(500);
await waitForRenderer(win);
await evalRenderer(win, `window.__setTheme("light")`);
await evalRenderer(win, "window.__setRegions(false)");
await delay(350);
await capture(win, dir, "22-01-light.png");
await evalRenderer(win, `window.__setTheme("dark")`);
await delay(350);
await capture(win, dir, "22-02-dark.png");
await evalRenderer(win, `window.__setTheme("light")`);
await evalRenderer(win, "window.__setRegions(true)");
await delay(350);
await capture(win, dir, "22-03-drag-regions.png");
app.quit();
} catch (error) {
process.stdout.write(
`${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
);
app.exit(1);
}
}
ipcMain.handle(CH.themeGet, () => {
try {
return themeState();
} catch {
throw new Error("THEME_GET_FAILED");
}
});
ipcMain.handle(CH.themeSet, (_event: IpcMainInvokeEvent, raw: unknown) => {
try {
assertThemeSet(raw);
nativeTheme.themeSource = raw.source;
writeStoredSource(raw.source);
broadcastTheme();
return themeState();
} catch {
throw new Error("THEME_SET_FAILED");
}
});
nativeTheme.on("updated", () => {
broadcastTheme();
});
app.whenReady().then(() => {
nativeTheme.themeSource = readStoredSource();
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();
});