electron/lib/browser/api/menu.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

296 lines
9.3 KiB
TypeScript
Raw Normal View History

import { BaseWindow, MenuItem, webContents, Menu as MenuType, BrowserWindow, MenuItemConstructorOptions } from 'electron/main';
import { sortMenuItems } from '@electron/internal/browser/api/menu-utils';
import { setApplicationMenuWasSet } from '@electron/internal/browser/default-menu';
const bindings = process._linkedBinding('electron_browser_menu');
2016-01-12 02:40:23 +00:00
2020-07-06 20:24:54 +00:00
const { Menu } = bindings as { Menu: typeof MenuType };
const checked = new WeakMap<MenuItem, boolean>();
2020-07-06 20:24:54 +00:00
let applicationMenu: MenuType | null = null;
2017-10-24 02:22:39 +00:00
let groupIdIndex = 0;
2017-10-23 18:47:47 +00:00
/* Instance Methods */
2017-10-23 22:35:16 +00:00
Menu.prototype._init = function () {
2017-10-23 18:47:47 +00:00
this.commandsMap = {};
this.groupsMap = {};
this.items = [];
2020-04-02 23:07:56 +00:00
};
Menu.prototype._isCommandIdChecked = function (id) {
const item = this.commandsMap[id];
if (!item) return false;
return item.getCheckStatus();
2020-04-02 23:07:56 +00:00
};
Menu.prototype._isCommandIdEnabled = function (id) {
2020-07-06 20:24:54 +00:00
return this.commandsMap[id] ? this.commandsMap[id].enabled : false;
2020-04-02 23:07:56 +00:00
};
Menu.prototype._shouldCommandIdWorkWhenHidden = function (id) {
2020-07-06 20:24:54 +00:00
return this.commandsMap[id] ? !!this.commandsMap[id].acceleratorWorksWhenHidden : false;
2020-04-02 23:07:56 +00:00
};
Menu.prototype._isCommandIdVisible = function (id) {
2020-07-06 20:24:54 +00:00
return this.commandsMap[id] ? this.commandsMap[id].visible : false;
2020-04-02 23:07:56 +00:00
};
Menu.prototype._getAcceleratorForCommandId = function (id, useDefaultAccelerator) {
const command = this.commandsMap[id];
if (!command) return;
if (command.accelerator != null) return command.accelerator;
if (useDefaultAccelerator) return command.getDefaultRoleAccelerator();
};
Menu.prototype._shouldRegisterAcceleratorForCommandId = function (id) {
2020-07-06 20:24:54 +00:00
return this.commandsMap[id] ? this.commandsMap[id].registerAccelerator : false;
2020-04-02 23:07:56 +00:00
};
if (process.platform === 'darwin') {
Menu.prototype._getSharingItemForCommandId = function (id) {
return this.commandsMap[id] ? this.commandsMap[id].sharingItem : null;
};
}
2020-04-02 23:07:56 +00:00
Menu.prototype._executeCommand = function (event, id) {
const command = this.commandsMap[id];
if (!command) return;
2020-07-06 20:24:54 +00:00
const focusedWindow = BaseWindow.getFocusedWindow();
command.click(event, focusedWindow instanceof BrowserWindow ? focusedWindow : undefined, webContents.getFocusedWebContents());
2020-04-02 23:07:56 +00:00
};
Menu.prototype._menuWillShow = function () {
// Ensure radio groups have at least one menu item selected
for (const id of Object.keys(this.groupsMap)) {
const found = this.groupsMap[id].find(item => item.checked) || null;
if (!found) checked.set(this.groupsMap[id][0], true);
2020-04-02 23:07:56 +00:00
}
2017-10-23 18:47:47 +00:00
};
Menu.prototype.popup = function (options = {}) {
if (options == null || typeof options !== 'object') {
throw new TypeError('Options must be an object');
}
let { window, x, y, positioningItem, sourceType, callback } = options;
2017-10-23 22:35:16 +00:00
2018-02-20 01:59:27 +00:00
// no callback passed
2018-02-20 16:10:53 +00:00
if (!callback || typeof callback !== 'function') callback = () => {};
2017-10-23 22:35:16 +00:00
// set defaults
2018-02-20 01:59:27 +00:00
if (typeof x !== 'number') x = -1;
if (typeof y !== 'number') y = -1;
2018-02-20 16:28:34 +00:00
if (typeof positioningItem !== 'number') positioningItem = -1;
if (typeof sourceType !== 'string' || !sourceType) sourceType = 'mouse';
2018-02-20 01:59:27 +00:00
// find which window to use
const wins = BaseWindow.getAllWindows();
if (!wins || !wins.includes(window as any)) {
2020-07-06 20:24:54 +00:00
window = BaseWindow.getFocusedWindow() as any;
if (!window && wins && wins.length > 0) {
2020-07-06 20:24:54 +00:00
window = wins[0] as any;
}
if (!window) {
throw new Error('Cannot open Menu without a BaseWindow present');
}
}
2017-10-23 22:35:16 +00:00
this.popupAt(window as unknown as BaseWindow, x, y, positioningItem, sourceType, callback);
2018-02-20 16:28:34 +00:00
return { browserWindow: window, x, y, position: positioningItem };
2017-10-23 18:47:47 +00:00
};
Menu.prototype.closePopup = function (window) {
if (window instanceof BaseWindow) {
2017-12-21 06:26:32 +00:00
this.closePopupAt(window.id);
} else {
// Passing -1 (invalid) would make closePopupAt close the all menu runners
// belong to this menu.
this.closePopupAt(-1);
}
};
Menu.prototype.getMenuItemById = function (id) {
const items = this.items;
let found = items.find(item => item.id === id) || null;
for (let i = 0; !found && i < items.length; i++) {
2020-07-06 20:24:54 +00:00
const { submenu } = items[i];
if (submenu) {
found = submenu.getMenuItemById(id);
}
}
return found;
};
2017-10-23 22:35:16 +00:00
Menu.prototype.append = function (item) {
2017-10-23 18:47:47 +00:00
return this.insert(this.getItemCount(), item);
};
2017-10-23 22:35:16 +00:00
Menu.prototype.insert = function (pos, item) {
if ((item ? item.constructor : undefined) !== MenuItem) {
2017-10-23 18:47:47 +00:00
throw new TypeError('Invalid item');
}
if (pos < 0) {
throw new RangeError(`Position ${pos} cannot be less than 0`);
} else if (pos > this.getItemCount()) {
throw new RangeError(`Position ${pos} cannot be greater than the total MenuItem count`);
}
// insert item depending on its type
insertItemByType.call(this, item, pos);
// set item properties
2017-10-24 22:52:12 +00:00
if (item.sublabel) this.setSublabel(pos, item.sublabel);
if (item.toolTip) this.setToolTip(pos, item.toolTip);
2017-10-24 22:52:12 +00:00
if (item.icon) this.setIcon(pos, item.icon);
if (item.role) this.setRole(pos, item.role);
2022-07-05 15:49:56 +00:00
// Make menu accessible to items.
2017-10-23 18:47:47 +00:00
item.overrideReadOnlyProperty('menu', this);
2016-01-12 02:40:23 +00:00
// Remember the items.
2017-10-23 18:47:47 +00:00
this.items.splice(pos, 0, item);
this.commandsMap[item.commandId] = item;
2017-10-23 18:47:47 +00:00
};
2017-10-23 22:35:16 +00:00
Menu.prototype._callMenuWillShow = function () {
if (this.delegate) this.delegate.menuWillShow(this);
2017-10-23 22:35:16 +00:00
this.items.forEach(item => {
2017-10-24 22:52:12 +00:00
if (item.submenu) item.submenu._callMenuWillShow();
2017-10-23 22:35:16 +00:00
});
};
/* Static Methods */
Menu.getApplicationMenu = () => applicationMenu;
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder;
// set application menu with a preexisting menu
2020-07-06 20:24:54 +00:00
Menu.setApplicationMenu = function (menu: MenuType) {
if (menu && menu.constructor !== Menu) {
2017-10-23 22:35:16 +00:00
throw new TypeError('Invalid menu');
}
2017-10-23 18:47:47 +00:00
2017-10-23 22:35:16 +00:00
applicationMenu = menu;
setApplicationMenuWasSet();
2017-10-23 18:47:47 +00:00
if (process.platform === 'darwin') {
2017-10-24 22:52:12 +00:00
if (!menu) return;
2017-10-23 18:47:47 +00:00
menu._callMenuWillShow();
bindings.setApplicationMenu(menu);
2017-10-23 18:47:47 +00:00
} else {
const windows = BaseWindow.getAllWindows();
windows.map(w => w.setMenu(menu));
2016-01-12 02:40:23 +00:00
}
};
2016-01-12 02:40:23 +00:00
Menu.buildFromTemplate = function (template) {
if (!Array.isArray(template)) {
throw new TypeError('Invalid template for Menu: Menu template must be an array');
2017-10-23 22:35:16 +00:00
}
if (!areValidTemplateItems(template)) {
throw new TypeError('Invalid template for MenuItem: must have at least one of label, role or type');
}
const sorted = sortTemplate(template);
const filtered = removeExtraSeparators(sorted);
const menu = new Menu();
filtered.forEach(item => {
if (item instanceof MenuItem) {
menu.append(item);
} else {
menu.append(new MenuItem(item));
}
});
2017-10-23 22:35:16 +00:00
return menu;
};
2016-01-12 02:40:23 +00:00
/* Helper Functions */
2017-10-23 18:47:47 +00:00
// validate the template against having the wrong attribute
2020-07-06 20:24:54 +00:00
function areValidTemplateItems (template: (MenuItemConstructorOptions | MenuItem)[]) {
return template.every(item =>
item != null &&
typeof item === 'object' &&
(Object.hasOwn(item, 'label') || Object.hasOwn(item, 'role') || item.type === 'separator'));
}
2020-07-06 20:24:54 +00:00
function sortTemplate (template: (MenuItemConstructorOptions | MenuItem)[]) {
const sorted = sortMenuItems(template);
for (const item of sorted) {
if (Array.isArray(item.submenu)) {
item.submenu = sortTemplate(item.submenu);
}
}
return sorted;
}
// Search between separators to find a radio menu item and return its group id
2020-07-06 20:24:54 +00:00
function generateGroupId (items: (MenuItemConstructorOptions | MenuItem)[], pos: number) {
2017-10-23 22:35:16 +00:00
if (pos > 0) {
for (let idx = pos - 1; idx >= 0; idx--) {
if (items[idx].type === 'radio') return (items[idx] as MenuItem).groupId;
if (items[idx].type === 'separator') break;
2017-10-23 22:35:16 +00:00
}
} else if (pos < items.length) {
for (let idx = pos; idx <= items.length - 1; idx++) {
if (items[idx].type === 'radio') return (items[idx] as MenuItem).groupId;
if (items[idx].type === 'separator') break;
2017-10-23 03:57:23 +00:00
}
2017-10-23 18:47:47 +00:00
}
groupIdIndex += 1;
return groupIdIndex;
2017-10-23 22:35:16 +00:00
}
2017-10-23 18:47:47 +00:00
2020-07-06 20:24:54 +00:00
function removeExtraSeparators (items: (MenuItemConstructorOptions | MenuItem)[]) {
// fold adjacent separators together
let ret = items.filter((e, idx, arr) => {
if (e.visible === false) return true;
return e.type !== 'separator' || idx === 0 || arr[idx - 1].type !== 'separator';
});
// remove edge separators
ret = ret.filter((e, idx, arr) => {
if (e.visible === false) return true;
return e.type !== 'separator' || (idx !== 0 && idx !== arr.length - 1);
});
return ret;
}
2020-07-06 20:24:54 +00:00
function insertItemByType (this: MenuType, item: MenuItem, pos: number) {
const types = {
2017-10-25 14:17:41 +00:00
normal: () => this.insertItem(pos, item.commandId, item.label),
checkbox: () => this.insertCheckItem(pos, item.commandId, item.label),
separator: () => this.insertSeparator(pos),
submenu: () => this.insertSubMenu(pos, item.commandId, item.label, item.submenu),
radio: () => {
// Grouping radio menu items
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos));
if (this.groupsMap[item.groupId] == null) {
this.groupsMap[item.groupId] = [];
}
this.groupsMap[item.groupId].push(item);
// Setting a radio menu item should flip other items in the group.
checked.set(item, item.checked);
Object.defineProperty(item, 'checked', {
enumerable: true,
get: () => checked.get(item),
set: () => {
this.groupsMap[item.groupId].forEach(other => {
if (other !== item) checked.set(other, false);
});
checked.set(item, true);
}
});
this.insertRadioItem(pos, item.commandId, item.label, item.groupId);
}
};
types[item.type]();
}
2017-10-24 02:35:42 +00:00
module.exports = Menu;