menu.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import { BaseWindow, MenuItem, webContents, Menu as MenuType, BrowserWindow, MenuItemConstructorOptions } from 'electron/main';
  2. import { sortMenuItems } from '@electron/internal/browser/api/menu-utils';
  3. import { setApplicationMenuWasSet } from '@electron/internal/browser/default-menu';
  4. const bindings = process._linkedBinding('electron_browser_menu');
  5. const { Menu } = bindings as { Menu: typeof MenuType };
  6. const checked = new WeakMap<MenuItem, boolean>();
  7. let applicationMenu: MenuType | null = null;
  8. let groupIdIndex = 0;
  9. /* Instance Methods */
  10. Menu.prototype._init = function () {
  11. this.commandsMap = {};
  12. this.groupsMap = {};
  13. this.items = [];
  14. };
  15. Menu.prototype._isCommandIdChecked = function (id) {
  16. const item = this.commandsMap[id];
  17. if (!item) return false;
  18. return item.getCheckStatus();
  19. };
  20. Menu.prototype._isCommandIdEnabled = function (id) {
  21. return this.commandsMap[id] ? this.commandsMap[id].enabled : false;
  22. };
  23. Menu.prototype._shouldCommandIdWorkWhenHidden = function (id) {
  24. return this.commandsMap[id] ? !!this.commandsMap[id].acceleratorWorksWhenHidden : false;
  25. };
  26. Menu.prototype._isCommandIdVisible = function (id) {
  27. return this.commandsMap[id] ? this.commandsMap[id].visible : false;
  28. };
  29. Menu.prototype._getAcceleratorForCommandId = function (id, useDefaultAccelerator) {
  30. const command = this.commandsMap[id];
  31. if (!command) return;
  32. if (command.accelerator != null) return command.accelerator;
  33. if (useDefaultAccelerator) return command.getDefaultRoleAccelerator();
  34. };
  35. Menu.prototype._shouldRegisterAcceleratorForCommandId = function (id) {
  36. return this.commandsMap[id] ? this.commandsMap[id].registerAccelerator : false;
  37. };
  38. if (process.platform === 'darwin') {
  39. Menu.prototype._getSharingItemForCommandId = function (id) {
  40. return this.commandsMap[id] ? this.commandsMap[id].sharingItem : null;
  41. };
  42. }
  43. Menu.prototype._executeCommand = function (event, id) {
  44. const command = this.commandsMap[id];
  45. if (!command) return;
  46. const focusedWindow = BaseWindow.getFocusedWindow();
  47. command.click(event, focusedWindow instanceof BrowserWindow ? focusedWindow : undefined, webContents.getFocusedWebContents());
  48. };
  49. Menu.prototype._menuWillShow = function () {
  50. // Ensure radio groups have at least one menu item selected
  51. for (const id of Object.keys(this.groupsMap)) {
  52. const found = this.groupsMap[id].find(item => item.checked) || null;
  53. if (!found) checked.set(this.groupsMap[id][0], true);
  54. }
  55. };
  56. Menu.prototype.popup = function (options = {}) {
  57. if (options == null || typeof options !== 'object') {
  58. throw new TypeError('Options must be an object');
  59. }
  60. let { window, x, y, positioningItem, sourceType, callback } = options;
  61. // no callback passed
  62. if (!callback || typeof callback !== 'function') callback = () => {};
  63. // set defaults
  64. if (typeof x !== 'number') x = -1;
  65. if (typeof y !== 'number') y = -1;
  66. if (typeof positioningItem !== 'number') positioningItem = -1;
  67. if (typeof sourceType !== 'string' || !sourceType) sourceType = 'mouse';
  68. // find which window to use
  69. const wins = BaseWindow.getAllWindows();
  70. if (!wins || !wins.includes(window as any)) {
  71. window = BaseWindow.getFocusedWindow() as any;
  72. if (!window && wins && wins.length > 0) {
  73. window = wins[0] as any;
  74. }
  75. if (!window) {
  76. throw new Error('Cannot open Menu without a BaseWindow present');
  77. }
  78. }
  79. this.popupAt(window as unknown as BaseWindow, x, y, positioningItem, sourceType, callback);
  80. return { browserWindow: window, x, y, position: positioningItem };
  81. };
  82. Menu.prototype.closePopup = function (window) {
  83. if (window instanceof BaseWindow) {
  84. this.closePopupAt(window.id);
  85. } else {
  86. // Passing -1 (invalid) would make closePopupAt close the all menu runners
  87. // belong to this menu.
  88. this.closePopupAt(-1);
  89. }
  90. };
  91. Menu.prototype.getMenuItemById = function (id) {
  92. const items = this.items;
  93. let found = items.find(item => item.id === id) || null;
  94. for (let i = 0; !found && i < items.length; i++) {
  95. const { submenu } = items[i];
  96. if (submenu) {
  97. found = submenu.getMenuItemById(id);
  98. }
  99. }
  100. return found;
  101. };
  102. Menu.prototype.append = function (item) {
  103. return this.insert(this.getItemCount(), item);
  104. };
  105. Menu.prototype.insert = function (pos, item) {
  106. if ((item ? item.constructor : undefined) !== MenuItem) {
  107. throw new TypeError('Invalid item');
  108. }
  109. if (pos < 0) {
  110. throw new RangeError(`Position ${pos} cannot be less than 0`);
  111. } else if (pos > this.getItemCount()) {
  112. throw new RangeError(`Position ${pos} cannot be greater than the total MenuItem count`);
  113. }
  114. // insert item depending on its type
  115. insertItemByType.call(this, item, pos);
  116. // set item properties
  117. if (item.sublabel) this.setSublabel(pos, item.sublabel);
  118. if (item.toolTip) this.setToolTip(pos, item.toolTip);
  119. if (item.icon) this.setIcon(pos, item.icon);
  120. if (item.role) this.setRole(pos, item.role);
  121. // Make menu accessible to items.
  122. item.overrideReadOnlyProperty('menu', this);
  123. // Remember the items.
  124. this.items.splice(pos, 0, item);
  125. this.commandsMap[item.commandId] = item;
  126. };
  127. Menu.prototype._callMenuWillShow = function () {
  128. if (this.delegate) this.delegate.menuWillShow(this);
  129. for (const item of this.items) {
  130. if (item.submenu) item.submenu._callMenuWillShow();
  131. }
  132. };
  133. /* Static Methods */
  134. Menu.getApplicationMenu = () => applicationMenu;
  135. Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder;
  136. // set application menu with a preexisting menu
  137. Menu.setApplicationMenu = function (menu: MenuType) {
  138. if (menu && menu.constructor !== Menu) {
  139. throw new TypeError('Invalid menu');
  140. }
  141. applicationMenu = menu;
  142. setApplicationMenuWasSet();
  143. if (process.platform === 'darwin') {
  144. if (!menu) return;
  145. menu._callMenuWillShow();
  146. bindings.setApplicationMenu(menu);
  147. } else {
  148. const windows = BaseWindow.getAllWindows();
  149. windows.map(w => w.setMenu(menu));
  150. }
  151. };
  152. Menu.buildFromTemplate = function (template) {
  153. if (!Array.isArray(template)) {
  154. throw new TypeError('Invalid template for Menu: Menu template must be an array');
  155. }
  156. if (!areValidTemplateItems(template)) {
  157. throw new TypeError('Invalid template for MenuItem: must have at least one of label, role or type');
  158. }
  159. const sorted = sortTemplate(template);
  160. const filtered = removeExtraSeparators(sorted);
  161. const menu = new Menu();
  162. for (const item of filtered) {
  163. if (item instanceof MenuItem) {
  164. menu.append(item);
  165. } else {
  166. menu.append(new MenuItem(item));
  167. }
  168. }
  169. return menu;
  170. };
  171. /* Helper Functions */
  172. // validate the template against having the wrong attribute
  173. function areValidTemplateItems (template: (MenuItemConstructorOptions | MenuItem)[]) {
  174. return template.every(item =>
  175. item != null &&
  176. typeof item === 'object' &&
  177. (Object.hasOwn(item, 'label') || Object.hasOwn(item, 'role') || item.type === 'separator'));
  178. }
  179. function sortTemplate (template: (MenuItemConstructorOptions | MenuItem)[]) {
  180. const sorted = sortMenuItems(template);
  181. for (const item of sorted) {
  182. if (Array.isArray(item.submenu)) {
  183. item.submenu = sortTemplate(item.submenu);
  184. }
  185. }
  186. return sorted;
  187. }
  188. // Search between separators to find a radio menu item and return its group id
  189. function generateGroupId (items: (MenuItemConstructorOptions | MenuItem)[], pos: number) {
  190. if (pos > 0) {
  191. for (let idx = pos - 1; idx >= 0; idx--) {
  192. if (items[idx].type === 'radio') return (items[idx] as MenuItem).groupId;
  193. if (items[idx].type === 'separator') break;
  194. }
  195. } else if (pos < items.length) {
  196. for (let idx = pos; idx <= items.length - 1; idx++) {
  197. if (items[idx].type === 'radio') return (items[idx] as MenuItem).groupId;
  198. if (items[idx].type === 'separator') break;
  199. }
  200. }
  201. groupIdIndex += 1;
  202. return groupIdIndex;
  203. }
  204. function removeExtraSeparators (items: (MenuItemConstructorOptions | MenuItem)[]) {
  205. // fold adjacent separators together
  206. let ret = items.filter((e, idx, arr) => {
  207. if (e.visible === false) return true;
  208. return e.type !== 'separator' || idx === 0 || arr[idx - 1].type !== 'separator';
  209. });
  210. // remove edge separators
  211. ret = ret.filter((e, idx, arr) => {
  212. if (e.visible === false) return true;
  213. return e.type !== 'separator' || (idx !== 0 && idx !== arr.length - 1);
  214. });
  215. return ret;
  216. }
  217. function insertItemByType (this: MenuType, item: MenuItem, pos: number) {
  218. const types = {
  219. normal: () => this.insertItem(pos, item.commandId, item.label),
  220. checkbox: () => this.insertCheckItem(pos, item.commandId, item.label),
  221. separator: () => this.insertSeparator(pos),
  222. submenu: () => this.insertSubMenu(pos, item.commandId, item.label, item.submenu),
  223. radio: () => {
  224. // Grouping radio menu items
  225. item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos));
  226. if (this.groupsMap[item.groupId] == null) {
  227. this.groupsMap[item.groupId] = [];
  228. }
  229. this.groupsMap[item.groupId].push(item);
  230. // Setting a radio menu item should flip other items in the group.
  231. checked.set(item, item.checked);
  232. Object.defineProperty(item, 'checked', {
  233. enumerable: true,
  234. get: () => checked.get(item),
  235. set: () => {
  236. for (const other of this.groupsMap[item.groupId]) {
  237. if (other !== item) checked.set(other, false);
  238. }
  239. checked.set(item, true);
  240. }
  241. });
  242. this.insertRadioItem(pos, item.commandId, item.label, item.groupId);
  243. }
  244. };
  245. types[item.type]();
  246. }
  247. module.exports = Menu;