summaryrefslogtreecommitdiffstats
path: root/toolkit/content/widgets/button.js
blob: 7ca2eddbed26db51f2d60be8c2625e72983f9643 (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
/* 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.
{
  class MozButtonBase extends MozElements.BaseText {
    constructor() {
      super();

      /**
       * While it would seem we could do this by handling oncommand, we can't
       * because any external oncommand handlers might get called before ours,
       * and then they would see the incorrect value of checked. Additionally
       * a command attribute would redirect the command events anyway.
       */
      this.addEventListener("click", event => {
        if (event.button != 0) {
          return;
        }
        this._handleClick();
      });

      this.addEventListener("keypress", event => {
        if (event.key != " ") {
          return;
        }
        this._handleClick();
        // Prevent page from scrolling on the space key.
        event.preventDefault();
      });

      this.addEventListener("keypress", event => {
        if (this.hasMenu()) {
          if (this.open) {
            return;
          }
        } else if (!this.inRichListItem) {
          if (
            event.keyCode == KeyEvent.DOM_VK_UP ||
            (event.keyCode == KeyEvent.DOM_VK_LEFT &&
              document.defaultView.getComputedStyle(this.parentNode)
                .direction == "ltr") ||
            (event.keyCode == KeyEvent.DOM_VK_RIGHT &&
              document.defaultView.getComputedStyle(this.parentNode)
                .direction == "rtl")
          ) {
            event.preventDefault();
            window.document.commandDispatcher.rewindFocus();
            return;
          }

          if (
            event.keyCode == KeyEvent.DOM_VK_DOWN ||
            (event.keyCode == KeyEvent.DOM_VK_RIGHT &&
              document.defaultView.getComputedStyle(this.parentNode)
                .direction == "ltr") ||
            (event.keyCode == KeyEvent.DOM_VK_LEFT &&
              document.defaultView.getComputedStyle(this.parentNode)
                .direction == "rtl")
          ) {
            event.preventDefault();
            window.document.commandDispatcher.advanceFocus();
            return;
          }
        }

        if (
          event.keyCode ||
          event.charCode <= 32 ||
          event.altKey ||
          event.ctrlKey ||
          event.metaKey
        ) {
          return;
        } // No printable char pressed, not a potential accesskey

        // Possible accesskey pressed
        var charPressedLower = String.fromCharCode(
          event.charCode
        ).toLowerCase();

        // If the accesskey of the current button is pressed, just activate it
        if (this.accessKey?.toLowerCase() == charPressedLower) {
          this.click();
          return;
        }

        // Search for accesskey in the list of buttons for this doc and each subdoc
        // Get the buttons for the main document and all sub-frames
        for (
          var frameCount = -1;
          frameCount < window.top.frames.length;
          frameCount++
        ) {
          var doc =
            frameCount == -1
              ? window.top.document
              : window.top.frames[frameCount].document;
          if (this.fireAccessKeyButton(doc.documentElement, charPressedLower)) {
            return;
          }
        }

        // Test dialog buttons
        let buttonBox = window.top.document.querySelector("dialog")?.buttonBox;
        if (buttonBox) {
          this.fireAccessKeyButton(buttonBox, charPressedLower);
        }
      });
    }

    set type(val) {
      this.setAttribute("type", val);
    }

    get type() {
      return this.getAttribute("type");
    }

    set disabled(val) {
      if (val) {
        this.setAttribute("disabled", "true");
      } else {
        this.removeAttribute("disabled");
      }
    }

    get disabled() {
      return this.getAttribute("disabled") == "true";
    }

    set group(val) {
      this.setAttribute("group", val);
    }

    get group() {
      return this.getAttribute("group");
    }

    set open(val) {
      if (this.hasMenu()) {
        this.openMenu(val);
      } else if (val) {
        // Fall back to just setting the attribute
        this.setAttribute("open", "true");
      } else {
        this.removeAttribute("open");
      }
    }

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

    set checked(val) {
      if (this.type == "radio" && val) {
        var sibs = this.parentNode.getElementsByAttribute("group", this.group);
        for (var i = 0; i < sibs.length; ++i) {
          sibs[i].removeAttribute("checked");
        }
      }

      if (val) {
        this.setAttribute("checked", "true");
      } else {
        this.removeAttribute("checked");
      }
    }

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

    filterButtons(node) {
      // if the node isn't visible, don't descend into it.
      var cs = node.ownerGlobal.getComputedStyle(node);
      if (cs.visibility != "visible" || cs.display == "none") {
        return NodeFilter.FILTER_REJECT;
      }
      // but it may be a popup element, in which case we look at "state"...
      if (XULPopupElement.isInstance(node) && node.state != "open") {
        return NodeFilter.FILTER_REJECT;
      }
      // OK - the node seems visible, so it is a candidate.
      if (node.localName == "button" && node.accessKey && !node.disabled) {
        return NodeFilter.FILTER_ACCEPT;
      }
      return NodeFilter.FILTER_SKIP;
    }

    fireAccessKeyButton(aSubtree, aAccessKeyLower) {
      var iterator = aSubtree.ownerDocument.createTreeWalker(
        aSubtree,
        NodeFilter.SHOW_ELEMENT,
        this.filterButtons
      );
      while (iterator.nextNode()) {
        var test = iterator.currentNode;
        if (
          test.accessKey?.toLowerCase() == aAccessKeyLower &&
          !test.disabled &&
          !test.collapsed &&
          !test.hidden
        ) {
          test.focus();
          test.click();
          return true;
        }
      }
      return false;
    }

    _handleClick() {
      if (!this.disabled) {
        if (this.type == "checkbox") {
          this.checked = !this.checked;
        } else if (this.type == "radio") {
          this.checked = true;
        }
      }
    }
  }

  MozXULElement.implementCustomInterface(MozButtonBase, [
    Ci.nsIDOMXULButtonElement,
  ]);

  MozElements.ButtonBase = MozButtonBase;

  class MozButton extends MozButtonBase {
    static get inheritedAttributes() {
      return {
        ".box-inherit": "align,dir,pack,orient",
        ".button-icon": "src=image",
        ".button-text": "value=label,accesskey,crop",
        ".button-menu-dropmarker": "open,disabled,label",
      };
    }

    get icon() {
      return this.querySelector(".button-icon");
    }

    static get buttonFragment() {
      let frag = document.importNode(
        MozXULElement.parseXULToFragment(`
        <hbox class="box-inherit button-box" align="center" pack="center" flex="1" anonid="button-box">
          <image class="button-icon"/>
          <label class="button-text"/>
        </hbox>`),
        true
      );
      Object.defineProperty(this, "buttonFragment", { value: frag });
      return frag;
    }

    static get menuFragment() {
      let frag = document.importNode(
        MozXULElement.parseXULToFragment(`
        <hbox class="box-inherit button-box" align="center" pack="center" flex="1">
          <hbox class="box-inherit" align="center" pack="center" flex="1">
            <image class="button-icon"/>
            <label class="button-text"/>
          </hbox>
          <dropmarker class="button-menu-dropmarker"/>
        </hbox>`),
        true
      );
      Object.defineProperty(this, "menuFragment", { value: frag });
      return frag;
    }

    get _hasConnected() {
      return this.querySelector(":scope > .button-box") != null;
    }

    connectedCallback() {
      if (this.delayConnectedCallback() || this._hasConnected) {
        return;
      }

      let fragment;
      if (this.type === "menu") {
        fragment = MozButton.menuFragment;

        this.addEventListener("keypress", event => {
          if (event.keyCode != KeyEvent.DOM_VK_RETURN && event.key != " ") {
            return;
          }

          this.open = true;
          // Prevent page from scrolling on the space key.
          if (event.key == " ") {
            event.preventDefault();
          }
        });
      } else {
        fragment = this.constructor.buttonFragment;
      }

      this.appendChild(fragment.cloneNode(true));
      this.initializeAttributeInheritance();
      this.inRichListItem = !!this.closest("richlistitem");
    }
  }

  customElements.define("button", MozButton);
}