示例工程 29-menu-tray
29-menu-tray/app/.tsc/main/index.js
import { app, BrowserWindow, Menu, Tray, ipcMain, nativeImage, shell, } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { assertFlagReq, assertInvokeReq, assertPopupReq, CH, } from "../shared/ipc";
import { TRAY_ICON_DATA_URL } from "../shared/tray-icon";
app.setName("Menu & Tray 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(), `menu-tray-smoke-${process.pid}`)
: "";
if (smokeData)
app.setPath("userData", smokeData);
const DOCS_URL = "https://www.electronjs.org/docs/latest";
let win = null;
let tray = null;
let compact = false;
let statusbar = true;
let syncing = false;
let lastEvent = "就绪";
let events = [];
const COMMANDS = new Set([
"window.new",
"window.close",
"window.hide",
"window.show",
"view.compact",
"view.statusbar",
"tools.sync",
"tools.check",
"events.clear",
"tray.toggle",
"context.copy",
"context.paste",
"context.timestamp",
"context.clearlog",
"app.about",
]);
const LABELS = {
"window.new": "新建窗口",
"window.close": "关闭窗口",
"window.hide": "隐藏窗口",
"window.show": "显示窗口",
"view.compact": "切换紧凑模式",
"view.statusbar": "切换状态栏",
"tools.sync": "同步数据",
"tools.check": "运行检查",
"events.clear": "清空事件",
"tray.toggle": "托盘:显示/隐藏窗口",
"context.copy": "复制",
"context.paste": "粘贴",
"context.timestamp": "插入时间戳",
"context.clearlog": "清空事件",
"app.about": "关于检查器",
};
function record(id, source) {
events = [
{
at: Date.now(),
source,
id,
label: LABELS[id] ?? id,
},
...events,
].slice(0, 20);
}
function toggleFlag(key) {
if (key === "compact")
compact = !compact;
if (key === "statusbar")
statusbar = !statusbar;
}
function runCommand(id, source) {
if (!COMMANDS.has(id))
return;
record(id, source);
if (id === "view.compact")
toggleFlag("compact");
if (id === "view.statusbar")
toggleFlag("statusbar");
if (id === "window.hide")
win?.hide();
if (id === "window.show") {
win?.show();
win?.focus();
}
if (id === "window.new") {
lastEvent = "新建窗口(演示只记录)";
}
if (id === "window.close") {
win?.close();
}
if (id === "tray.toggle") {
if (win?.isVisible())
win.hide();
else {
win?.show();
win?.focus();
}
}
if (id === "events.clear" || id === "context.clearlog") {
events = [];
lastEvent = "事件已清空";
}
if (id === "context.timestamp") {
lastEvent = `插入时间戳 ${new Date().toLocaleTimeString("zh-CN")}`;
}
if (id === "context.copy")
lastEvent = "已复制示例文本";
if (id === "context.paste")
lastEvent = "粘贴(演示)";
if (id === "tools.check" || id === "tools.sync") {
if (!syncing) {
syncing = true;
lastEvent = id === "tools.sync" ? "同步中…" : "检查中…";
setTimeout(() => {
syncing = false;
lastEvent = id === "tools.sync" ? "同步完成" : "检查完成";
refresh();
}, 800);
}
}
if (id.startsWith("window.")) {
lastEvent = LABELS[id] ?? id;
}
refresh();
}
function appMenuTemplate() {
const isMac = process.platform === "darwin";
const template = [];
if (isMac) {
template.push({
label: app.name,
submenu: [
{
id: "app.about",
label: `关于 ${app.name}`,
click: () => runCommand("app.about", "menu"),
},
{ type: "separator" },
{ role: "hide", label: "隐藏" },
{ role: "hideOthers", label: "隐藏其它" },
{ role: "unhide", label: "显示全部" },
{ type: "separator" },
{ role: "quit", label: `退出 ${app.name}` },
],
});
}
template.push({
label: "文件",
submenu: [
{
id: "window.new",
label: "新建窗口",
accelerator: "CmdOrCtrl+N",
click: () => runCommand("window.new", "menu"),
},
{
id: "window.close",
label: "关闭窗口",
accelerator: "CmdOrCtrl+W",
click: () => runCommand("window.close", "menu"),
},
{ type: "separator" },
{ role: isMac ? "minimize" : "quit", label: isMac ? "最小化" : "退出" },
],
});
template.push({
label: "编辑",
submenu: [
{ role: "undo", label: "撤销" },
{ role: "redo", label: "重做" },
{ type: "separator" },
{ role: "cut", label: "剪切" },
{ role: "copy", label: "复制" },
{ role: "paste", label: "粘贴" },
{ role: "selectAll", label: "全选" },
],
});
template.push({
label: "视图",
submenu: [
{ role: "reload", label: "重新加载" },
{ role: "toggleDevTools", label: "开发者工具" },
{ type: "separator" },
{
id: "view.compact",
label: "紧凑模式",
type: "checkbox",
checked: compact,
accelerator: "CmdOrCtrl+Shift+C",
click: () => runCommand("view.compact", "menu"),
},
{
id: "view.statusbar",
label: "显示状态栏",
type: "checkbox",
checked: statusbar,
click: () => runCommand("view.statusbar", "menu"),
},
],
});
template.push({
label: "工具",
submenu: [
{
id: "tools.sync",
label: syncing ? "同步中…" : "同步数据",
enabled: !syncing,
click: () => runCommand("tools.sync", "menu"),
},
{
id: "tools.check",
label: syncing ? "检查中…" : "运行检查",
enabled: !syncing,
click: () => runCommand("tools.check", "menu"),
},
{ type: "separator" },
{
id: "events.clear",
label: "清空事件",
click: () => runCommand("events.clear", "menu"),
},
],
});
template.push({
role: "help",
label: "帮助",
submenu: [
{
label: "Electron 文档",
click: () => {
void shell.openExternal(DOCS_URL);
},
},
{ type: "separator" },
{
id: "help.about",
label: "关于检查器",
click: () => runCommand("app.about", "menu"),
},
],
});
return template;
}
function trayMenuTemplate() {
return [
{
id: "tray.toggle",
label: win?.isVisible() ? "隐藏窗口" : "显示窗口",
click: () => runCommand("tray.toggle", "tray"),
},
{
label: `状态:${lastEvent}`,
enabled: false,
},
{ type: "separator" },
{
id: "view.compact",
label: "紧凑模式",
type: "checkbox",
checked: compact,
click: () => runCommand("view.compact", "tray"),
},
{
id: "view.statusbar",
label: "显示状态栏",
type: "checkbox",
checked: statusbar,
click: () => runCommand("view.statusbar", "tray"),
},
{ type: "separator" },
{
id: "tray.quit",
label: "退出",
click: () => app.quit(),
},
];
}
function contextMenuTemplate() {
return [
{
id: "context.copy",
label: "复制",
accelerator: "CmdOrCtrl+C",
click: () => runCommand("context.copy", "context"),
},
{
id: "context.paste",
label: "粘贴",
accelerator: "CmdOrCtrl+V",
click: () => runCommand("context.paste", "context"),
},
{ type: "separator" },
{
id: "context.timestamp",
label: "插入时间戳",
click: () => runCommand("context.timestamp", "context"),
},
{
id: "view.compact",
label: "紧凑模式",
type: "checkbox",
checked: compact,
click: () => runCommand("view.compact", "context"),
},
{ type: "separator" },
{
id: "context.clearlog",
label: "清空事件",
click: () => runCommand("context.clearlog", "context"),
},
];
}
const ROLE_LABELS = {
undo: "撤销",
redo: "重做",
cut: "剪切",
copy: "复制",
paste: "粘贴",
selectAll: "全选",
reload: "重新加载",
toggleDevTools: "开发者工具",
minimize: "最小化",
quit: "退出",
hide: "隐藏",
hideOthers: "隐藏其它",
unhide: "显示全部",
about: "关于",
close: "关闭",
};
function serializeItems(items) {
return items.map((item) => {
if (item.type === "separator") {
return { label: "", type: "separator" };
}
return {
id: item.id,
label: item.label ?? ROLE_LABELS[item.role ?? ""] ?? item.role ?? "",
accelerator: typeof item.accelerator === "string" ? item.accelerator : undefined,
type: item.type === "checkbox" ? "checkbox" : "normal",
checked: item.checked,
enabled: item.enabled !== false,
role: item.role,
};
});
}
function appMenuGroups() {
return appMenuTemplate().map((menu) => ({
label: menu.label ?? ROLE_LABELS[menu.role ?? ""] ?? "",
role: menu.role,
items: serializeItems(menu.submenu ?? []),
}));
}
function snapshot() {
return {
platform: process.platform,
compact,
statusbar,
syncing,
lastEvent,
appMenu: appMenuGroups(),
trayMenu: serializeItems(trayMenuTemplate()),
contextMenu: serializeItems(contextMenuTemplate()),
events: [...events],
trayIcon: TRAY_ICON_DATA_URL,
windowVisible: win?.isVisible() ?? false,
trayCreated: tray !== null,
};
}
function broadcast() {
const state = snapshot();
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed())
window.webContents.send(CH.changed, state);
}
}
function rebuildMenus() {
Menu.setApplicationMenu(Menu.buildFromTemplate(appMenuTemplate()));
if (tray) {
tray.setContextMenu(Menu.buildFromTemplate(trayMenuTemplate()));
}
}
function refresh() {
rebuildMenus();
broadcast();
}
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() {
const window = new BrowserWindow({
width: 1100,
height: 820,
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,
},
});
window.once("ready-to-show", () => window.show());
window.on("show", broadcast);
window.on("hide", broadcast);
window.on("closed", () => {
if (win === window)
win = null;
broadcast();
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
}
else {
void window.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
}
win = window;
return window;
}
function createTray() {
if (tray)
return;
const image = nativeImage.createFromDataURL(TRAY_ICON_DATA_URL);
if (process.platform === "darwin")
image.setTemplateImage(true);
tray = new Tray(image);
tray.setToolTip("菜单与托盘工作台");
tray.on("click", () => runCommand("tray.toggle", "tray"));
tray.setContextMenu(Menu.buildFromTemplate(trayMenuTemplate()));
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer(window, code) {
let lastError = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await window.webContents.executeJavaScript(code));
}
catch (error) {
lastError = error;
await delay(200);
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
async function waitForRenderer(window) {
for (let attempt = 0; attempt < 160; attempt += 1) {
if (window.isDestroyed())
return;
try {
const ready = await evalRenderer(window, "typeof window.__smoke === 'function'");
if (ready)
return;
}
catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
async function runSmoke() {
try {
const window = createWindow();
await waitForRenderer(window);
await delay(500);
await waitForRenderer(window);
const result = await evalRenderer(window, "window.__smoke()");
const nativeCompact = Menu.getApplicationMenu()?.getMenuItemById("view.compact")?.checked;
process.stdout.write(`${JSON.stringify({
evt: "smoke",
ok: result.appMenus >= 4 &&
result.appItems > 0 &&
result.trayItems >= 5 &&
result.contextItems >= 5 &&
result.compact === true &&
result.statusbar === false &&
result.syncDone &&
result.eventIds.includes("context.timestamp") &&
result.trayCreated &&
tray !== null &&
!tray.isDestroyed() &&
nativeCompact === true &&
window.isVisible(),
nativeCompact,
...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(window, dir, file) {
const image = await window.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() {
try {
const dir = path.resolve(process.cwd(), "../../../docs/assets/images/29-menu-tray");
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
const window = createWindow();
await waitForRenderer(window);
await delay(500);
await waitForRenderer(window);
await evalRenderer(window, `window.__prepareShots("app")`);
await delay(1100);
await capture(window, dir, "29-01-app-menu.png");
await evalRenderer(window, `window.__prepareShots("tray")`);
await delay(1100);
await capture(window, dir, "29-02-tray.png");
await evalRenderer(window, `window.__prepareShots("context")`);
await delay(400);
await capture(window, dir, "29-03-context-menu.png");
app.quit();
}
catch (error) {
process.stdout.write(`${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`);
app.exit(1);
}
}
ipcMain.handle(CH.get, () => snapshot());
ipcMain.handle(CH.invoke, (_event, raw) => {
try {
assertInvokeReq(raw);
if (!COMMANDS.has(raw.id))
throw new Error("UNKNOWN_COMMAND");
runCommand(raw.id, "inspector");
return snapshot();
}
catch {
throw new Error("MENU_INVOKE_FAILED");
}
});
ipcMain.handle(CH.setFlag, (_event, raw) => {
try {
assertFlagReq(raw);
if (raw.key === "compact")
compact = raw.value;
if (raw.key === "statusbar")
statusbar = raw.value;
refresh();
return snapshot();
}
catch {
throw new Error("MENU_FLAG_FAILED");
}
});
ipcMain.handle(CH.popup, (_event, raw) => {
try {
assertPopupReq(raw);
const menu = Menu.buildFromTemplate(contextMenuTemplate());
menu.popup({
window: win ?? undefined,
x: Math.round(raw.x),
y: Math.round(raw.y),
});
return undefined;
}
catch {
throw new Error("MENU_POPUP_FAILED");
}
});
ipcMain.handle(CH.reset, () => {
compact = false;
statusbar = true;
syncing = false;
lastEvent = "就绪";
events = [];
refresh();
return snapshot();
});
app.whenReady().then(() => {
createTray();
rebuildMenus();
if (isSmoke) {
void runSmoke();
}
else if (isShots) {
void runShots();
}
else {
createWindow();
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
else {
win?.show();
}
});
});
app.on("before-quit", () => {
tray?.destroy();
tray = null;
});
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();
});
//# sourceMappingURL=index.js.map