summaryrefslogtreecommitdiffstats
path: root/toolkit/content/widgets/dialog.js
blob: 52eb2168f8ba7083a1f499c570369f486432d8cf (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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/* 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.
{
  const { AppConstants } = ChromeUtils.importESModule(
    "resource://gre/modules/AppConstants.sys.mjs"
  );

  class MozDialog extends MozXULElement {
    constructor() {
      super();
    }

    static get observedAttributes() {
      return super.observedAttributes.concat("subdialog");
    }

    attributeChangedCallback(name, oldValue, newValue) {
      if (name == "subdialog") {
        console.assert(
          newValue,
          `Turning off subdialog style is not supported`
        );
        if (this.isConnectedAndReady && !oldValue && newValue) {
          this.shadowRoot.appendChild(
            MozXULElement.parseXULToFragment(this.inContentStyle)
          );
        }
        return;
      }
      super.attributeChangedCallback(name, oldValue, newValue);
    }

    static get inheritedAttributes() {
      return {
        ".dialog-button-box":
          "pack=buttonpack,align=buttonalign,dir=buttondir,orient=buttonorient",
        "[dlgtype='accept']": "disabled=buttondisabledaccept",
      };
    }

    get inContentStyle() {
      return `
      <html:link rel="stylesheet" href="chrome://global/skin/in-content/common.css" />
    `;
    }

    get _markup() {
      let buttons = AppConstants.XP_UNIX
        ? `
      <hbox class="dialog-button-box">
        <button dlgtype="disclosure" hidden="true"/>
        <button dlgtype="extra2" hidden="true"/>
        <button dlgtype="extra1" hidden="true"/>
        <spacer class="button-spacer" part="button-spacer" flex="1"/>
        <button dlgtype="cancel"/>
        <button dlgtype="accept"/>
      </hbox>`
        : `
      <hbox class="dialog-button-box" pack="end">
        <button dlgtype="extra2" hidden="true"/>
        <spacer class="button-spacer" part="button-spacer" flex="1" hidden="true"/>
        <button dlgtype="accept"/>
        <button dlgtype="extra1" hidden="true"/>
        <button dlgtype="cancel"/>
        <button dlgtype="disclosure" hidden="true"/>
      </hbox>`;

      return `
      <html:link rel="stylesheet" href="chrome://global/skin/button.css"/>
      <html:link rel="stylesheet" href="chrome://global/skin/dialog.css"/>
      ${this.hasAttribute("subdialog") ? this.inContentStyle : ""}
      <vbox class="box-inherit" part="content-box">
        <html:slot></html:slot>
      </vbox>
      ${buttons}`;
    }

    connectedCallback() {
      if (this.delayConnectedCallback()) {
        return;
      }
      if (this.hasConnected) {
        return;
      }
      this.hasConnected = true;
      this.attachShadow({ mode: "open" });

      document.documentElement.setAttribute("role", "dialog");
      document.l10n?.connectRoot(this.shadowRoot);

      this.shadowRoot.textContent = "";
      this.shadowRoot.appendChild(
        MozXULElement.parseXULToFragment(this._markup)
      );
      this.initializeAttributeInheritance();

      this._configureButtons(this.buttons);

      window.moveToAlertPosition = this.moveToAlertPosition;
      window.centerWindowOnScreen = this.centerWindowOnScreen;

      document.addEventListener(
        "keypress",
        event => {
          if (event.keyCode == KeyEvent.DOM_VK_RETURN) {
            this._hitEnter(event);
          } else if (
            event.keyCode == KeyEvent.DOM_VK_ESCAPE &&
            !event.defaultPrevented
          ) {
            this.cancelDialog();
          }
        },
        { mozSystemGroup: true }
      );

      if (AppConstants.platform == "macosx") {
        document.addEventListener(
          "keypress",
          event => {
            if (event.key == "." && event.metaKey) {
              this.cancelDialog();
            }
          },
          true
        );
      } else {
        this.addEventListener("focus", this, true);
        this.shadowRoot.addEventListener("focus", this, true);
      }

      // listen for when window is closed via native close buttons
      window.addEventListener("close", event => {
        if (!this.cancelDialog()) {
          event.preventDefault();
        }
      });

      // Call postLoadInit for things that we need to initialize after onload.
      if (document.readyState == "complete") {
        this._postLoadInit();
      } else {
        window.addEventListener("load", event => this._postLoadInit());
      }
    }

    set buttons(val) {
      this._configureButtons(val);
    }

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

    set defaultButton(val) {
      this._setDefaultButton(val);
    }

    get defaultButton() {
      if (this.hasAttribute("defaultButton")) {
        return this.getAttribute("defaultButton");
      }
      return "accept"; // default to the accept button
    }

    get _strBundle() {
      if (!this.__stringBundle) {
        this.__stringBundle = Services.strings.createBundle(
          "chrome://global/locale/dialog.properties"
        );
      }
      return this.__stringBundle;
    }

    acceptDialog() {
      return this._doButtonCommand("accept");
    }

    cancelDialog() {
      return this._doButtonCommand("cancel");
    }

    getButton(aDlgType) {
      return this._buttons[aDlgType];
    }

    get buttonBox() {
      return this.shadowRoot.querySelector(".dialog-button-box");
    }

    // NOTE(emilio): This has to match AppWindow::IntrinsicallySizeShell, to
    // prevent flickering, see bug 1799394.
    _sizeToPreferredSize() {
      const docEl = document.documentElement;
      const prefWidth = (() => {
        if (docEl.hasAttribute("width")) {
          return parseInt(docEl.getAttribute("width"));
        }
        let prefWidthProp = docEl.getAttribute("prefwidth");
        if (prefWidthProp) {
          let minWidth = parseFloat(
            getComputedStyle(docEl).getPropertyValue(prefWidthProp)
          );
          if (isFinite(minWidth)) {
            return minWidth;
          }
        }
        return 0;
      })();
      window.sizeToContentConstrained({ prefWidth });
    }

    moveToAlertPosition() {
      // hack. we need this so the window has something like its final size
      if (window.outerWidth == 1) {
        dump(
          "Trying to position a sizeless window; caller should have called sizeToContent() or sizeTo(). See bug 75649.\n"
        );
        this._sizeToPreferredSize();
      }

      if (opener) {
        var xOffset = (opener.outerWidth - window.outerWidth) / 2;
        var yOffset = opener.outerHeight / 5;

        var newX = opener.screenX + xOffset;
        var newY = opener.screenY + yOffset;
      } else {
        newX = (screen.availWidth - window.outerWidth) / 2;
        newY = (screen.availHeight - window.outerHeight) / 2;
      }

      // ensure the window is fully onscreen (if smaller than the screen)
      if (newX < screen.availLeft) {
        newX = screen.availLeft + 20;
      }
      if (newX + window.outerWidth > screen.availLeft + screen.availWidth) {
        newX = screen.availLeft + screen.availWidth - window.outerWidth - 20;
      }

      if (newY < screen.availTop) {
        newY = screen.availTop + 20;
      }
      if (newY + window.outerHeight > screen.availTop + screen.availHeight) {
        newY = screen.availTop + screen.availHeight - window.outerHeight - 60;
      }

      window.moveTo(newX, newY);
    }

    centerWindowOnScreen() {
      var xOffset = screen.availWidth / 2 - window.outerWidth / 2;
      var yOffset = screen.availHeight / 2 - window.outerHeight / 2;

      xOffset = xOffset > 0 ? xOffset : 0;
      yOffset = yOffset > 0 ? yOffset : 0;
      window.moveTo(xOffset, yOffset);
    }

    // Give focus to the first focusable element in the dialog
    _setInitialFocusIfNeeded() {
      let focusedElt = document.commandDispatcher.focusedElement;
      if (focusedElt) {
        return;
      }

      const defaultButton = this.getButton(this.defaultButton);
      Services.focus.moveFocus(
        window,
        null,
        Services.focus.MOVEFOCUS_FORWARD,
        Services.focus.FLAG_NOPARENTFRAME
      );

      focusedElt = document.commandDispatcher.focusedElement;
      if (!focusedElt) {
        return; // No focusable element?
      }

      let firstFocusedElt = focusedElt;
      while (
        focusedElt.localName == "tab" ||
        focusedElt.getAttribute("noinitialfocus") == "true"
      ) {
        Services.focus.moveFocus(
          window,
          focusedElt,
          Services.focus.MOVEFOCUS_FORWARD,
          Services.focus.FLAG_NOPARENTFRAME
        );
        focusedElt = document.commandDispatcher.focusedElement;
        if (focusedElt == firstFocusedElt) {
          if (focusedElt.getAttribute("noinitialfocus") == "true") {
            focusedElt.blur();
          }
          // Didn't find anything else to focus, we're done.
          return;
        }
      }

      if (firstFocusedElt.localName == "tab") {
        if (focusedElt.hasAttribute("dlgtype")) {
          // We don't want to focus on anonymous OK, Cancel, etc. buttons,
          // so return focus to the tab itself
          firstFocusedElt.focus();
        }
      } else if (
        AppConstants.platform != "macosx" &&
        focusedElt.hasAttribute("dlgtype") &&
        focusedElt != defaultButton
      ) {
        defaultButton.focus();
        if (document.commandDispatcher.focusedElement != defaultButton) {
          // If the default button is not focusable, then return focus to the
          // initial element if possible, or blur otherwise.
          if (firstFocusedElt.getAttribute("noinitialfocus") == "true") {
            focusedElt.blur();
          } else {
            firstFocusedElt.focus();
          }
        }
      }
    }

    async _postLoadInit() {
      this._setInitialFocusIfNeeded();
      let finalStep = () => {
        this._sizeToPreferredSize();
        this._snapCursorToDefaultButtonIfNeeded();
      };
      // As a hack to ensure Windows sizes the window correctly,
      // _sizeToPreferredSize() needs to happen after
      // AppWindow::OnChromeLoaded. That one is called right after the load
      // event dispatch but within the same task. Using direct dispatch let's
      // all this code run before the next task (which might be a task to
      // paint the window).
      // But, MacOS doesn't like resizing after window/dialog becoming visible.
      // Linux seems to be able to handle both cases.
      if (Services.appinfo.OS == "Darwin") {
        finalStep();
      } else {
        Services.tm.dispatchDirectTaskToCurrentThread(finalStep);
      }
    }

    // This snaps the cursor to the default button rect on windows, when
    // SPI_GETSNAPTODEFBUTTON is set.
    async _snapCursorToDefaultButtonIfNeeded() {
      const defaultButton = this.getButton(this.defaultButton);
      if (!defaultButton) {
        return;
      }
      try {
        // FIXME(emilio, bug 1797624): This setTimeout() ensures enough time
        // has passed so that the dialog vertical margin has been set by the
        // front-end. For subdialogs, cursor positioning should probably be
        // done by the opener instead, once the dialog is positioned.
        await new Promise(r => setTimeout(r, 0));
        await window.promiseDocumentFlushed(() => {});
        window.notifyDefaultButtonLoaded(defaultButton);
      } catch (e) {}
    }

    _configureButtons(aButtons) {
      // by default, get all the anonymous button elements
      var buttons = {};
      this._buttons = buttons;

      for (let type of ["accept", "cancel", "extra1", "extra2", "disclosure"]) {
        buttons[type] = this.shadowRoot.querySelector(`[dlgtype="${type}"]`);
      }

      // look for any overriding explicit button elements
      var exBtns = this.getElementsByAttribute("dlgtype", "*");
      var dlgtype;
      for (let i = 0; i < exBtns.length; ++i) {
        dlgtype = exBtns[i].getAttribute("dlgtype");
        buttons[dlgtype].hidden = true; // hide the anonymous button
        buttons[dlgtype] = exBtns[i];
      }

      // add the label and oncommand handler to each button
      for (dlgtype in buttons) {
        var button = buttons[dlgtype];
        button.addEventListener(
          "command",
          this._handleButtonCommand.bind(this),
          true
        );

        // don't override custom labels with pre-defined labels on explicit buttons
        if (!button.hasAttribute("label")) {
          // dialog attributes override the default labels in dialog.properties
          if (this.hasAttribute("buttonlabel" + dlgtype)) {
            button.setAttribute(
              "label",
              this.getAttribute("buttonlabel" + dlgtype)
            );
            if (this.hasAttribute("buttonaccesskey" + dlgtype)) {
              button.setAttribute(
                "accesskey",
                this.getAttribute("buttonaccesskey" + dlgtype)
              );
            }
          } else if (this.hasAttribute("buttonid" + dlgtype)) {
            document.l10n.setAttributes(
              button,
              this.getAttribute("buttonid" + dlgtype)
            );
          } else if (dlgtype != "extra1" && dlgtype != "extra2") {
            button.setAttribute(
              "label",
              this._strBundle.GetStringFromName("button-" + dlgtype)
            );
            var accessKey = this._strBundle.GetStringFromName(
              "accesskey-" + dlgtype
            );
            if (accessKey) {
              button.setAttribute("accesskey", accessKey);
            }
          }
        }
      }

      // ensure that hitting enter triggers the default button command
      // eslint-disable-next-line no-self-assign
      this.defaultButton = this.defaultButton;

      // if there is a special button configuration, use it
      if (aButtons) {
        // expect a comma delimited list of dlgtype values
        var list = aButtons.split(",");

        // mark shown dlgtypes as true
        var shown = {
          accept: false,
          cancel: false,
          disclosure: false,
          extra1: false,
          extra2: false,
        };
        for (let i = 0; i < list.length; ++i) {
          shown[list[i].replace(/ /g, "")] = true;
        }

        // hide/show the buttons we want
        for (dlgtype in buttons) {
          buttons[dlgtype].hidden = !shown[dlgtype];
        }

        // show the spacer on Windows only when the extra2 button is present
        if (AppConstants.platform == "win") {
          let spacer = this.shadowRoot.querySelector(".button-spacer");
          spacer.removeAttribute("hidden");
          spacer.setAttribute("flex", shown.extra2 ? "1" : "0");
        }
      }
    }

    _setDefaultButton(aNewDefault) {
      // remove the default attribute from the previous default button, if any
      var oldDefaultButton = this.getButton(this.defaultButton);
      if (oldDefaultButton) {
        oldDefaultButton.removeAttribute("default");
      }

      var newDefaultButton = this.getButton(aNewDefault);
      if (newDefaultButton) {
        this.setAttribute("defaultButton", aNewDefault);
        newDefaultButton.setAttribute("default", "true");
      } else {
        this.setAttribute("defaultButton", "none");
        if (aNewDefault != "none") {
          dump(
            "invalid new default button: " + aNewDefault + ", assuming: none\n"
          );
        }
      }
    }

    _handleButtonCommand(aEvent) {
      return this._doButtonCommand(aEvent.target.getAttribute("dlgtype"));
    }

    _doButtonCommand(aDlgType) {
      var button = this.getButton(aDlgType);
      if (!button.disabled) {
        var noCancel = this._fireButtonEvent(aDlgType);
        if (noCancel) {
          if (aDlgType == "accept" || aDlgType == "cancel") {
            var closingEvent = new CustomEvent("dialogclosing", {
              bubbles: true,
              detail: { button: aDlgType },
            });
            this.dispatchEvent(closingEvent);
            window.close();
          }
        }
        return noCancel;
      }
      return true;
    }

    _fireButtonEvent(aDlgType) {
      var event = document.createEvent("Events");
      event.initEvent("dialog" + aDlgType, true, true);

      // handle dom event handlers
      return this.dispatchEvent(event);
    }

    _hitEnter(evt) {
      if (evt.defaultPrevented) {
        return;
      }

      var btn = this.getButton(this.defaultButton);
      if (btn) {
        this._doButtonCommand(this.defaultButton);
      }
    }

    on_focus(event) {
      let btn = this.getButton(this.defaultButton);
      if (btn) {
        btn.setAttribute(
          "default",
          event.originalTarget == btn ||
            !(
              event.originalTarget.localName == "button" ||
              event.originalTarget.localName == "toolbarbutton"
            )
        );
      }
    }
  }

  customElements.define("dialog", MozDialog);
}