summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/components/menu/utils.js
blob: e6fca9682208bc8ca5ef8b362fabbfd6a1394c1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const Menu = require("resource://devtools/client/framework/menu.js");
const MenuItem = require("resource://devtools/client/framework/menu-item.js");

/**
 * Helper function for opening context menu.
 *
 * @param {Array} items
 *        List of menu items.
 * @param {Object} options:
 * @property {Element} button
 *           Button element used to open the menu.
 * @property {Number} screenX
 *           Screen x coordinate of the menu on the screen.
 * @property {Number} screenY
 *           Screen y coordinate of the menu on the screen.
 */
function showMenu(items, options) {
  if (items.length === 0) {
    return;
  }

  // Build the menu object from provided menu items.
  const menu = new Menu();
  items.forEach(item => {
    if (item == "-") {
      item = { type: "separator" };
    }

    const menuItem = new MenuItem(item);
    const subItems = item.submenu;

    if (subItems) {
      const subMenu = new Menu();
      subItems.forEach(subItem => {
        subMenu.append(new MenuItem(subItem));
      });
      menuItem.submenu = subMenu;
    }

    menu.append(menuItem);
  });

  // Calculate position on the screen according to
  // the parent button if available.
  if (options.button) {
    menu.popupAtTarget(options.button);
  } else {
    const screenX = options.screenX;
    const screenY = options.screenY;
    menu.popup(screenX, screenY, window.document);
  }
}

module.exports = {
  showMenu,
};