menu.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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, 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. // find which window to use
  68. const wins = BaseWindow.getAllWindows();
  69. if (!wins || wins.indexOf(window as any) === -1) {
  70. window = BaseWindow.getFocusedWindow() as any;
  71. if (!window && wins && wins.length > 0) {
  72. window = wins[0] as any;
  73. }
  74. if (!window) {
  75. throw new Error('Cannot open Menu without a BaseWindow present');
  76. }
  77. }
  78. this.popupAt(window as unknown as BaseWindow, x, y, positioningItem, callback);
  79. return { browserWindow: window, x, y, position: positioningItem };
  80. };
  81. Menu.prototype.closePopup = function (window) {
  82. if (window instanceof BaseWindow) {
  83. this.closePopupAt(window.id);
  84. } else {
  85. // Passing -1 (invalid) would make closePopupAt close the all menu runners
  86. // belong to this menu.
  87. this.closePopupAt(-1);
  88. }
  89. };
  90. Menu.prototype.getMenuItemById = function (id) {
  91. const items = this.items;
  92. let found = items.find(item => item.id === id) || null;
  93. for (let i = 0; !found && i < items.length; i++) {
  94. const { submenu } = items[i];
  95. if (submenu) {
  96. found = submenu.getMenuItemById(id);
  97. }
  98. }
  99. return found;
  100. };
  101. Menu.prototype.append = function (item) {
  102. return this.insert(this.getItemCount(), item);
  103. };
  104. Menu.prototype.insert = function (pos, item) {
  105. if ((item ? item.constructor : undefined) !== MenuItem) {
  106. throw new TypeError('Invalid item');
  107. }
  108. if (pos < 0) {
  109. throw new RangeError(`Position ${pos} cannot be less than 0`);
  110. } else if (pos > this.getItemCount()) {
  111. throw new RangeError(`Position ${pos} cannot be greater than the total MenuItem count`);
  112. }
  113. // insert item depending on its type
  114. insertItemByType.call(this, item, pos);
  115. // set item properties
  116. if (item.sublabel) this.setSublabel(pos, item.sublabel);
  117. if (item.toolTip) this.setToolTip(pos, item.toolTip);
  118. if (item.icon) this.setIcon(pos, item.icon);
  119. if (item.role) this.setRole(pos, item.role);
  120. // Make menu accessible to items.
  121. item.overrideReadOnlyProperty('menu', this);
  122. // Remember the items.
  123. this.items.splice(pos, 0, item);
  124. this.commandsMap[item.commandId] = item;
  125. };
  126. Menu.prototype._callMenuWillShow = function () {
  127. if (this.delegate) this.delegate.menuWillShow(this);
  128. this.items.forEach(item => {
  129. if (item.submenu) item.submenu._callMenuWillShow();
  130. });
  131. };
  132. /* Static Methods */
  133. Menu.getApplicationMenu = () => applicationMenu;
  134. Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder;
  135. // set application menu with a preexisting menu
  136. Menu.setApplicationMenu = function (menu: MenuType) {
  137. if (menu && menu.constructor !== Menu) {
  138. throw new TypeError('Invalid menu');
  139. }
  140. applicationMenu = menu;
  141. setApplicationMenuWasSet();
  142. if (process.platform === 'darwin') {
  143. if (!menu) return;
  144. menu._callMenuWillShow();
  145. bindings.setApplicationMenu(menu);
  146. } else {
  147. const windows = BaseWindow.getAllWindows();
  148. windows.map(w => w.setMenu(menu));
  149. }
  150. };
  151. Menu.buildFromTemplate = function (template) {
  152. if (!Array.isArray(template)) {
  153. throw new TypeError('Invalid template for Menu: Menu template must be an array');
  154. }
  155. if (!areValidTemplateItems(template)) {
  156. throw new TypeError('Invalid template for MenuItem: must have at least one of label, role or type');
  157. }
  158. const sorted = sortTemplate(template);
  159. const filtered = removeExtraSeparators(sorted);
  160. const menu = new Menu();
  161. filtered.forEach(item => {
  162. if (item instanceof MenuItem) {
  163. menu.append(item);
  164. } else {
  165. menu.append(new MenuItem(item));
  166. }
  167. });
  168. return menu;
  169. };
  170. /* Helper Functions */
  171. // validate the template against having the wrong attribute
  172. function areValidTemplateItems (template: (MenuItemConstructorOptions | MenuItem)[]) {
  173. return template.every(item =>
  174. item != null &&
  175. typeof item === 'object' &&
  176. (Object.prototype.hasOwnProperty.call(item, 'label') ||
  177. Object.prototype.hasOwnProperty.call(item, 'role') ||
  178. item.type === 'separator'));
  179. }
  180. function sortTemplate (template: (MenuItemConstructorOptions | MenuItem)[]) {
  181. const sorted = sortMenuItems(template);
  182. for (const item of sorted) {
  183. if (Array.isArray(item.submenu)) {
  184. item.submenu = sortTemplate(item.submenu);
  185. }
  186. }
  187. return sorted;
  188. }
  189. // Search between separators to find a radio menu item and return its group id
  190. function generateGroupId (items: (MenuItemConstructorOptions | MenuItem)[], pos: number) {
  191. if (pos > 0) {
  192. for (let idx = pos - 1; idx >= 0; idx--) {
  193. if (items[idx].type === 'radio') return (items[idx] as MenuItem).groupId;
  194. if (items[idx].type === 'separator') break;
  195. }
  196. } else if (pos < items.length) {
  197. for (let idx = pos; idx <= items.length - 1; idx++) {
  198. if (items[idx].type === 'radio') return (items[idx] as MenuItem).groupId;
  199. if (items[idx].type === 'separator') break;
  200. }
  201. }
  202. groupIdIndex += 1;
  203. return groupIdIndex;
  204. }
  205. function removeExtraSeparators (items: (MenuItemConstructorOptions | MenuItem)[]) {
  206. // fold adjacent separators together
  207. let ret = items.filter((e, idx, arr) => {
  208. if (e.visible === false) return true;
  209. return e.type !== 'separator' || idx === 0 || arr[idx - 1].type !== 'separator';
  210. });
  211. // remove edge separators
  212. ret = ret.filter((e, idx, arr) => {
  213. if (e.visible === false) return true;
  214. return e.type !== 'separator' || (idx !== 0 && idx !== arr.length - 1);
  215. });
  216. return ret;
  217. }
  218. function insertItemByType (this: MenuType, item: MenuItem, pos: number) {
  219. const types = {
  220. normal: () => this.insertItem(pos, item.commandId, item.label),
  221. checkbox: () => this.insertCheckItem(pos, item.commandId, item.label),
  222. separator: () => this.insertSeparator(pos),
  223. submenu: () => this.insertSubMenu(pos, item.commandId, item.label, item.submenu),
  224. radio: () => {
  225. // Grouping radio menu items
  226. item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos));
  227. if (this.groupsMap[item.groupId] == null) {
  228. this.groupsMap[item.groupId] = [];
  229. }
  230. this.groupsMap[item.groupId].push(item);
  231. // Setting a radio menu item should flip other items in the group.
  232. checked.set(item, item.checked);
  233. Object.defineProperty(item, 'checked', {
  234. enumerable: true,
  235. get: () => checked.get(item),
  236. set: () => {
  237. this.groupsMap[item.groupId].forEach(other => {
  238. if (other !== item) checked.set(other, false);
  239. });
  240. checked.set(item, true);
  241. }
  242. });
  243. this.insertRadioItem(pos, item.commandId, item.label, item.groupId);
  244. }
  245. };
  246. types[item.type]();
  247. }
  248. module.exports = Menu;