utils.js (1651B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 const Menu = require("resource://devtools/client/framework/menu.js"); 8 const MenuItem = require("resource://devtools/client/framework/menu-item.js"); 9 10 /** 11 * Helper function for opening context menu. 12 * 13 * @param {Array} items 14 * List of menu items. 15 * @param {object} options: 16 * @property {Element} button 17 * Button element used to open the menu. 18 * @property {number} screenX 19 * Screen x coordinate of the menu on the screen. 20 * @property {number} screenY 21 * Screen y coordinate of the menu on the screen. 22 */ 23 function showMenu(items, options) { 24 if (items.length === 0) { 25 return; 26 } 27 28 // Build the menu object from provided menu items. 29 const menu = new Menu(); 30 items.forEach(item => { 31 if (item == "-") { 32 item = { type: "separator" }; 33 } 34 35 const menuItem = new MenuItem(item); 36 const subItems = item.submenu; 37 38 if (subItems) { 39 const subMenu = new Menu(); 40 subItems.forEach(subItem => { 41 subMenu.append(new MenuItem(subItem)); 42 }); 43 menuItem.submenu = subMenu; 44 } 45 46 menu.append(menuItem); 47 }); 48 49 // Calculate position on the screen according to 50 // the parent button if available. 51 if (options.button) { 52 menu.popupAtTarget(options.button); 53 } else { 54 const screenX = options.screenX; 55 const screenY = options.screenY; 56 menu.popup(screenX, screenY, window.document); 57 } 58 } 59 60 module.exports = { 61 showMenu, 62 };