|
| 1 | +import { app, Menu, shell } from 'electron' |
| 2 | +import { fileURLToPath } from 'url' |
| 3 | +import path from 'path' |
| 4 | +import { readFile } from 'fs/promises' |
| 5 | + |
| 6 | +const __dirname = fileURLToPath(new URL('.', import.meta.url)) |
| 7 | + |
| 8 | +const packagePath = path.join(__dirname, 'package.json') |
| 9 | +const packageJson = JSON.parse(await readFile(packagePath, { encoding: 'utf8' })) |
| 10 | + |
| 11 | +app.whenReady().then(() => { |
| 12 | + // 获取默认菜单 |
| 13 | + const applicationMenu = Menu.getApplicationMenu() |
| 14 | + |
| 15 | + // 深度克隆菜单结构的工具函数 |
| 16 | + const convertMenuItem = (menuItem) => { |
| 17 | + return { |
| 18 | + role: menuItem.role, |
| 19 | + submenu: menuItem.submenu ? menuItem.submenu.items.map(convertMenuItem) : [], |
| 20 | + type: menuItem.type, |
| 21 | + accelerator: menuItem.accelerator, |
| 22 | + icon: menuItem.icon, |
| 23 | + label: menuItem.label, |
| 24 | + sublabel: menuItem.sublabel, |
| 25 | + toolTip: menuItem.toolTip, |
| 26 | + enabled: menuItem.enabled, |
| 27 | + visible: menuItem.visible, |
| 28 | + checked: menuItem.checked, |
| 29 | + acceleratorWorksWhenHidden: menuItem.acceleratorWorksWhenHidden, |
| 30 | + registerAccelerator: menuItem.registerAccelerator, |
| 31 | + commandId: menuItem.commandId, |
| 32 | + click: menuItem.click, |
| 33 | + menu: menuItem.menu, |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // 克隆原有菜单结构(支持嵌套) |
| 38 | + const newTemplate = applicationMenu.items.map(convertMenuItem) |
| 39 | + |
| 40 | + // 查找 Help 菜单:中英文适配 |
| 41 | + const helpMenu = newTemplate.find((item) => item.label === 'Help' || item.label === '帮助') |
| 42 | + |
| 43 | + if (helpMenu) { |
| 44 | + // 初始化 submenu 数组(如果不存在) |
| 45 | + helpMenu.submenu = helpMenu.submenu || [] |
| 46 | + |
| 47 | + // 添加新子菜单项(追加到末尾) |
| 48 | + helpMenu.submenu.push( |
| 49 | + { type: 'separator' }, |
| 50 | + { |
| 51 | + label: 'GitHub', |
| 52 | + click: () => { |
| 53 | + shell.openExternal(packageJson.homepage).then((_) => {}) |
| 54 | + }, |
| 55 | + }, |
| 56 | + { |
| 57 | + label: 'Issues', |
| 58 | + click: () => { |
| 59 | + shell.openExternal(packageJson.bugs.url).then((_) => {}) |
| 60 | + }, |
| 61 | + }, |
| 62 | + ) |
| 63 | + } else { |
| 64 | + // 如果不存在 Help 菜单则创建(可选) |
| 65 | + newTemplate.push({ |
| 66 | + label: 'Help', |
| 67 | + submenu: [ |
| 68 | + { |
| 69 | + label: 'GitHub', |
| 70 | + click: () => { |
| 71 | + shell.openExternal(packageJson.homepage).then((_) => {}) |
| 72 | + }, |
| 73 | + }, |
| 74 | + { |
| 75 | + label: 'Issues', |
| 76 | + click: () => { |
| 77 | + shell.openExternal(packageJson.bugs.url).then((_) => {}) |
| 78 | + }, |
| 79 | + }, |
| 80 | + ], |
| 81 | + }) |
| 82 | + } |
| 83 | + |
| 84 | + // 重新构建菜单 |
| 85 | + const updatedMenu = Menu.buildFromTemplate(newTemplate) |
| 86 | + Menu.setApplicationMenu(updatedMenu) |
| 87 | +}) |
0 commit comments