summaryrefslogtreecommitdiffstats
path: root/toolkit/content/widgets/menu.js
blob: 1a55d799b60ff6f0826f7c35f7cfe415bd3535f9 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/* 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";

// This is loaded into all XUL windows. Wrap in a block to prevent
// leaking to window scope.
{
  let imports = {};
  ChromeUtils.defineESModuleGetters(imports, {
    ShortcutUtils: "resource://gre/modules/ShortcutUtils.sys.mjs",
  });

  const MozMenuItemBaseMixin = Base => {
    class MozMenuItemBase extends MozElements.BaseTextMixin(Base) {
      // nsIDOMXULSelectControlItemElement
      set value(val) {
        this.setAttribute("value", val);
      }
      get value() {
        return this.getAttribute("value");
      }

      // nsIDOMXULSelectControlItemElement
      get selected() {
        return this.getAttribute("selected") == "true";
      }

      // nsIDOMXULSelectControlItemElement
      get control() {
        var parent = this.parentNode;
        // Return the parent if it is a menu or menulist.
        if (parent && XULMenuElement.isInstance(parent.parentNode)) {
          return parent.parentNode;
        }
        return null;
      }

      // nsIDOMXULContainerItemElement
      get parentContainer() {
        for (var parent = this.parentNode; parent; parent = parent.parentNode) {
          if (XULMenuElement.isInstance(parent)) {
            return parent;
          }
        }
        return null;
      }
    }
    MozXULElement.implementCustomInterface(MozMenuItemBase, [
      Ci.nsIDOMXULSelectControlItemElement,
      Ci.nsIDOMXULContainerItemElement,
    ]);
    return MozMenuItemBase;
  };

  const MozMenuBaseMixin = Base => {
    class MozMenuBase extends MozMenuItemBaseMixin(Base) {
      set open(val) {
        this.openMenu(val);
      }

      get open() {
        return this.hasAttribute("open");
      }

      get itemCount() {
        var menupopup = this.menupopup;
        return menupopup ? menupopup.children.length : 0;
      }

      get menupopup() {
        const XUL_NS =
          "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

        for (
          var child = this.firstElementChild;
          child;
          child = child.nextElementSibling
        ) {
          if (child.namespaceURI == XUL_NS && child.localName == "menupopup") {
            return child;
          }
        }
        return null;
      }

      appendItem(aLabel, aValue) {
        var menupopup = this.menupopup;
        if (!menupopup) {
          menupopup = this.ownerDocument.createXULElement("menupopup");
          this.appendChild(menupopup);
        }

        var menuitem = this.ownerDocument.createXULElement("menuitem");
        menuitem.setAttribute("label", aLabel);
        menuitem.setAttribute("value", aValue);

        return menupopup.appendChild(menuitem);
      }

      getIndexOfItem(aItem) {
        var menupopup = this.menupopup;
        if (menupopup) {
          var items = menupopup.children;
          var length = items.length;
          for (var index = 0; index < length; ++index) {
            if (items[index] == aItem) {
              return index;
            }
          }
        }
        return -1;
      }

      getItemAtIndex(aIndex) {
        var menupopup = this.menupopup;
        if (!menupopup || aIndex < 0 || aIndex >= menupopup.children.length) {
          return null;
        }

        return menupopup.children[aIndex];
      }
    }
    MozXULElement.implementCustomInterface(MozMenuBase, [
      Ci.nsIDOMXULContainerElement,
    ]);
    return MozMenuBase;
  };

  // The <menucaption> element is used for rendering <html:optgroup> inside of <html:select>,
  // See SelectParentHelper.sys.mjs.
  class MozMenuCaption extends MozMenuBaseMixin(MozXULElement) {
    static get inheritedAttributes() {
      return {
        ".menu-iconic-left": "selected,disabled,checked",
        ".menu-iconic-icon": "src=image,validate,src",
        ".menu-iconic-text": "value=label,crop,highlightable",
        ".menu-iconic-highlightable-text": "text=label,crop,highlightable",
      };
    }

    connectedCallback() {
      this.textContent = "";
      this.appendChild(
        MozXULElement.parseXULToFragment(`
      <hbox class="menu-iconic-left" align="center" pack="center" aria-hidden="true">
        <image class="menu-iconic-icon" aria-hidden="true"></image>
      </hbox>
      <label class="menu-iconic-text" flex="1" crop="end" aria-hidden="true"></label>
      <label class="menu-iconic-highlightable-text" crop="end" aria-hidden="true"></label>
    `)
      );
      this.initializeAttributeInheritance();
    }
  }

  customElements.define("menucaption", MozMenuCaption);

  // In general, wait to render menus and menuitems inside menupopups
  // until they are going to be visible:
  window.addEventListener(
    "popupshowing",
    e => {
      if (e.originalTarget.ownerDocument != document) {
        return;
      }
      e.originalTarget.setAttribute("hasbeenopened", "true");
      for (let el of e.originalTarget.querySelectorAll("menuitem, menu")) {
        el.render();
      }
    },
    { capture: true }
  );

  class MozMenuItem extends MozMenuItemBaseMixin(MozXULElement) {
    static get observedAttributes() {
      return super.observedAttributes.concat("acceltext", "key");
    }

    attributeChangedCallback(name, oldValue, newValue) {
      if (name == "acceltext") {
        if (this._ignoreAccelTextChange) {
          this._ignoreAccelTextChange = false;
        } else {
          this._accelTextIsDerived = false;
          this._computeAccelTextFromKeyIfNeeded();
        }
      }
      if (name == "key") {
        this._computeAccelTextFromKeyIfNeeded();
      }
      super.attributeChangedCallback(name, oldValue, newValue);
    }

    static get inheritedAttributes() {
      return {
        ".menu-iconic-text": "value=label,crop,accesskey,highlightable",
        ".menu-text": "value=label,crop,accesskey,highlightable",
        ".menu-iconic-highlightable-text":
          "text=label,crop,accesskey,highlightable",
        ".menu-iconic-left": "selected,_moz-menuactive,disabled,checked",
        ".menu-iconic-icon":
          "src=image,validate,triggeringprincipal=iconloadingprincipal",
        ".menu-iconic-accel": "value=acceltext",
        ".menu-accel": "value=acceltext",
      };
    }

    static get iconicNoAccelFragment() {
      // Add aria-hidden="true" on all DOM, since XULMenuAccessible handles accessibility here.
      let frag = document.importNode(
        MozXULElement.parseXULToFragment(`
      <hbox class="menu-iconic-left" align="center" pack="center" aria-hidden="true">
        <image class="menu-iconic-icon"/>
      </hbox>
      <label class="menu-iconic-text" flex="1" crop="end" aria-hidden="true"/>
      <label class="menu-iconic-highlightable-text" crop="end" aria-hidden="true"/>
    `),
        true
      );
      Object.defineProperty(this, "iconicNoAccelFragment", { value: frag });
      return frag;
    }

    static get iconicFragment() {
      let frag = document.importNode(
        MozXULElement.parseXULToFragment(`
      <hbox class="menu-iconic-left" align="center" pack="center" aria-hidden="true">
        <image class="menu-iconic-icon"/>
      </hbox>
      <label class="menu-iconic-text" flex="1" crop="end" aria-hidden="true"/>
      <label class="menu-iconic-highlightable-text" crop="end" aria-hidden="true"/>
      <hbox class="menu-accel-container" aria-hidden="true">
        <label class="menu-iconic-accel"/>
      </hbox>
    `),
        true
      );
      Object.defineProperty(this, "iconicFragment", { value: frag });
      return frag;
    }

    static get plainFragment() {
      let frag = document.importNode(
        MozXULElement.parseXULToFragment(`
      <label class="menu-text" crop="end" aria-hidden="true"/>
      <hbox class="menu-accel-container" aria-hidden="true">
        <label class="menu-accel"/>
      </hbox>
    `),
        true
      );
      Object.defineProperty(this, "plainFragment", { value: frag });
      return frag;
    }

    get isIconic() {
      let type = this.getAttribute("type");
      return (
        type == "checkbox" ||
        type == "radio" ||
        this.classList.contains("menuitem-iconic")
      );
    }

    get isMenulistChild() {
      return this.matches("menulist > menupopup > menuitem");
    }

    get isInHiddenMenupopup() {
      return this.matches("menupopup:not([hasbeenopened]) menuitem");
    }

    _computeAccelTextFromKeyIfNeeded() {
      if (!this._accelTextIsDerived && this.getAttribute("acceltext")) {
        return;
      }
      let accelText = (() => {
        if (!document.contains(this)) {
          return null;
        }
        let keyId = this.getAttribute("key");
        if (!keyId) {
          return null;
        }
        let key = document.getElementById(keyId);
        if (!key) {
          let msg =
            `Key ${keyId} of menuitem ${this.getAttribute("label")} ` +
            `could not be found`;
          if (keyId.startsWith("ext-key-id-")) {
            console.info(msg);
          } else {
            console.error(msg);
          }
          return null;
        }
        return imports.ShortcutUtils.prettifyShortcut(key);
      })();

      this._accelTextIsDerived = true;
      // We need to ignore the next attribute change callback for acceltext, in
      // order to not reenter here.
      this._ignoreAccelTextChange = true;
      if (accelText) {
        this.setAttribute("acceltext", accelText);
      } else {
        this.removeAttribute("acceltext");
      }
    }

    render() {
      if (this.renderedOnce) {
        return;
      }
      this.renderedOnce = true;
      this.textContent = "";
      if (this.isMenulistChild) {
        this.append(this.constructor.iconicNoAccelFragment.cloneNode(true));
      } else if (this.isIconic) {
        this.append(this.constructor.iconicFragment.cloneNode(true));
      } else {
        this.append(this.constructor.plainFragment.cloneNode(true));
      }

      this._computeAccelTextFromKeyIfNeeded();
      this.initializeAttributeInheritance();
    }

    connectedCallback() {
      if (this.renderedOnce) {
        this._computeAccelTextFromKeyIfNeeded();
      }
      // Eagerly render if we are being inserted into a menulist (since we likely need to
      // size it), or into an already-opened menupopup (since we are already visible).
      // Checking isConnectedAndReady is an optimization that will let us quickly skip
      // non-menulists that are being connected during parse.
      if (
        this.isMenulistChild ||
        (this.isConnectedAndReady && !this.isInHiddenMenupopup)
      ) {
        this.render();
      }
    }
  }

  customElements.define("menuitem", MozMenuItem);

  const isHiddenWindow =
    document.documentURI == "chrome://browser/content/hiddenWindowMac.xhtml";

  class MozMenu extends MozMenuBaseMixin(
    MozElements.MozElementMixin(XULMenuElement)
  ) {
    static get inheritedAttributes() {
      return {
        ".menubar-text": "value=label,accesskey,crop",
        ".menu-iconic-text": "value=label,accesskey,crop,highlightable",
        ".menu-text": "value=label,accesskey,crop",
        ".menu-iconic-highlightable-text":
          "text=label,crop,accesskey,highlightable",
        ".menubar-left": "src=image",
        ".menu-iconic-icon":
          "src=image,triggeringprincipal=iconloadingprincipal,validate",
        ".menu-iconic-accel": "value=acceltext",
        ".menu-right": "_moz-menuactive,disabled",
        ".menu-accel": "value=acceltext",
      };
    }

    get needsEagerRender() {
      return (
        this.isMenubarChild || this.isMenulistChild || !this.isInHiddenMenupopup
      );
    }

    get isMenubarChild() {
      return this.matches("menubar > menu");
    }

    get isMenulistChild() {
      return this.matches("menulist > menupopup > menu");
    }

    get isInHiddenMenupopup() {
      return this.matches("menupopup:not([hasbeenopened]) menu");
    }

    get isIconic() {
      return this.classList.contains("menu-iconic");
    }

    get fragment() {
      let { isMenubarChild, isIconic } = this;
      let fragment = null;
      // Add aria-hidden="true" on all DOM, since XULMenuAccessible handles accessibility here.
      if (isMenubarChild && isIconic) {
        if (!MozMenu.menubarIconicFrag) {
          MozMenu.menubarIconicFrag = MozXULElement.parseXULToFragment(`
          <image class="menubar-left" aria-hidden="true"/>
          <label class="menubar-text" crop="end" aria-hidden="true"/>
        `);
        }
        fragment = document.importNode(MozMenu.menubarIconicFrag, true);
      }
      if (isMenubarChild && !isIconic) {
        if (!MozMenu.menubarFrag) {
          MozMenu.menubarFrag = MozXULElement.parseXULToFragment(`
          <label class="menubar-text" crop="end" aria-hidden="true"/>
        `);
        }
        fragment = document.importNode(MozMenu.menubarFrag, true);
      }
      if (!isMenubarChild && isIconic) {
        if (!MozMenu.normalIconicFrag) {
          MozMenu.normalIconicFrag = MozXULElement.parseXULToFragment(`
          <hbox class="menu-iconic-left" align="center" pack="center" aria-hidden="true">
            <image class="menu-iconic-icon"/>
          </hbox>
          <label class="menu-iconic-text" flex="1" crop="end" aria-hidden="true"/>
          <label class="menu-iconic-highlightable-text" crop="end" aria-hidden="true"/>
          <hbox class="menu-accel-container" anonid="accel" aria-hidden="true">
            <label class="menu-iconic-accel"/>
          </hbox>
          <hbox align="center" class="menu-right" aria-hidden="true">
            <image/>
          </hbox>
       `);
        }

        fragment = document.importNode(MozMenu.normalIconicFrag, true);
      }
      if (!isMenubarChild && !isIconic) {
        if (!MozMenu.normalFrag) {
          MozMenu.normalFrag = MozXULElement.parseXULToFragment(`
          <label class="menu-text" crop="end" aria-hidden="true"/>
          <hbox class="menu-accel-container" anonid="accel" aria-hidden="true">
            <label class="menu-accel"/>
          </hbox>
          <hbox align="center" class="menu-right" aria-hidden="true">
            <image/>
          </hbox>
       `);
        }

        fragment = document.importNode(MozMenu.normalFrag, true);
      }
      return fragment;
    }

    render() {
      // There are 2 main types of menus:
      //  (1) direct descendant of a menubar
      //  (2) all other menus
      // There is also an "iconic" variation of (1) and (2) based on the class.
      // To make this as simple as possible, we don't support menus being changed from one
      // of these types to another after the initial DOM connection. It'd be possible to make
      // this work by keeping track of the markup we prepend and then removing / re-prepending
      // during a change, but it's not a feature we use anywhere currently.
      if (this.renderedOnce) {
        return;
      }
      this.renderedOnce = true;

      // There will be a <menupopup /> already. Don't clear it out, just put our markup before it.
      this.prepend(this.fragment);
      this.initializeAttributeInheritance();
    }

    connectedCallback() {
      // On OSX we will have a bunch of menus in the hidden window. They get converted
      // into native menus based on the host attributes, so the inner DOM doesn't need
      // to be created.
      if (isHiddenWindow) {
        return;
      }

      if (this.delayConnectedCallback()) {
        return;
      }

      // Wait until we are going to be visible or required for sizing a popup.
      if (!this.needsEagerRender) {
        return;
      }

      this.render();
    }
  }

  customElements.define("menu", MozMenu);
}