@navikt/ds-react 4.12.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/_docs.json +101 -127
  2. package/cjs/date/datepicker/DatePicker.js +1 -1
  3. package/cjs/date/hooks/useEscape.js +6 -1
  4. package/cjs/modal/Modal.js +85 -46
  5. package/cjs/modal/{ModalContent.js → ModalBody.js} +3 -3
  6. package/cjs/modal/ModalContext.js +8 -0
  7. package/cjs/modal/ModalFooter.js +46 -0
  8. package/cjs/modal/ModalHeader.js +56 -0
  9. package/cjs/modal/ModalUtils.js +40 -0
  10. package/cjs/modal/dialog-polyfill.js +833 -0
  11. package/cjs/popover/Popover.js +5 -2
  12. package/cjs/table/DataCell.js +1 -3
  13. package/cjs/table/ExpandableRow.js +2 -1
  14. package/cjs/table/HeaderCell.js +1 -4
  15. package/cjs/table/Table.js +1 -1
  16. package/esm/date/datepicker/DatePicker.d.ts +2 -2
  17. package/esm/date/datepicker/DatePicker.js +1 -1
  18. package/esm/date/datepicker/DatePicker.js.map +1 -1
  19. package/esm/date/hooks/useEscape.d.ts +2 -1
  20. package/esm/date/hooks/useEscape.js +6 -1
  21. package/esm/date/hooks/useEscape.js.map +1 -1
  22. package/esm/modal/Modal.d.ts +76 -51
  23. package/esm/modal/Modal.js +87 -48
  24. package/esm/modal/Modal.js.map +1 -1
  25. package/esm/modal/ModalBody.d.ts +6 -0
  26. package/esm/modal/{ModalContent.js → ModalBody.js} +4 -4
  27. package/esm/modal/ModalBody.js.map +1 -0
  28. package/esm/modal/ModalContext.d.ts +6 -0
  29. package/esm/modal/ModalContext.js +3 -0
  30. package/esm/modal/ModalContext.js.map +1 -0
  31. package/esm/modal/ModalFooter.d.ts +6 -0
  32. package/esm/modal/ModalFooter.js +19 -0
  33. package/esm/modal/ModalFooter.js.map +1 -0
  34. package/esm/modal/ModalHeader.d.ts +11 -0
  35. package/esm/modal/ModalHeader.js +29 -0
  36. package/esm/modal/ModalHeader.js.map +1 -0
  37. package/esm/modal/ModalUtils.d.ts +4 -0
  38. package/esm/modal/ModalUtils.js +33 -0
  39. package/esm/modal/ModalUtils.js.map +1 -0
  40. package/esm/modal/dialog-polyfill.d.ts +5 -0
  41. package/esm/modal/dialog-polyfill.js +832 -0
  42. package/esm/modal/dialog-polyfill.js.map +1 -0
  43. package/esm/modal/index.d.ts +3 -1
  44. package/esm/popover/Popover.js +6 -3
  45. package/esm/popover/Popover.js.map +1 -1
  46. package/esm/provider/Provider.d.ts +1 -6
  47. package/esm/provider/Provider.js.map +1 -1
  48. package/esm/table/DataCell.js +2 -4
  49. package/esm/table/DataCell.js.map +1 -1
  50. package/esm/table/ExpandableRow.js +2 -1
  51. package/esm/table/ExpandableRow.js.map +1 -1
  52. package/esm/table/HeaderCell.js +1 -4
  53. package/esm/table/HeaderCell.js.map +1 -1
  54. package/esm/table/Table.d.ts +2 -3
  55. package/esm/table/Table.js +1 -1
  56. package/esm/table/Table.js.map +1 -1
  57. package/package.json +3 -5
  58. package/src/date/datepicker/DatePicker.tsx +3 -3
  59. package/src/date/hooks/useEscape.tsx +8 -3
  60. package/src/modal/Modal.tsx +171 -121
  61. package/src/modal/ModalBody.tsx +14 -0
  62. package/src/modal/ModalContext.ts +6 -0
  63. package/src/modal/ModalFooter.tsx +14 -0
  64. package/src/modal/ModalHeader.tsx +42 -0
  65. package/src/modal/ModalUtils.ts +37 -0
  66. package/src/modal/dialog-polyfill.ts +980 -0
  67. package/src/modal/index.ts +3 -1
  68. package/src/modal/modal.stories.tsx +142 -59
  69. package/src/popover/Popover.tsx +6 -2
  70. package/src/provider/Provider.tsx +1 -6
  71. package/src/table/DataCell.tsx +1 -5
  72. package/src/table/ExpandableRow.tsx +2 -1
  73. package/src/table/HeaderCell.tsx +1 -5
  74. package/src/table/Table.tsx +3 -4
  75. package/src/table/stories/table-expandable.stories.tsx +37 -1
  76. package/src/table/stories/table.stories.tsx +4 -1
  77. package/esm/modal/ModalContent.d.ts +0 -10
  78. package/esm/modal/ModalContent.js.map +0 -1
  79. package/src/modal/ModalContent.tsx +0 -26
@@ -0,0 +1,980 @@
1
+ // @ts-nocheck
2
+
3
+ // Copyright (c) 2013 The Chromium Authors. All rights reserved.
4
+ //
5
+ // Redistribution and use in source and binary forms, with or without
6
+ // modification, are permitted provided that the following conditions are
7
+ // met:
8
+ //
9
+ // * Redistributions of source code must retain the above copyright
10
+ // notice, this list of conditions and the following disclaimer.
11
+ // * Redistributions in binary form must reproduce the above
12
+ // copyright notice, this list of conditions and the following disclaimer
13
+ // in the documentation and/or other materials provided with the
14
+ // distribution.
15
+ // * Neither the name of Google Inc. nor the names of its
16
+ // contributors may be used to endorse or promote products derived from
17
+ // this software without specific prior written permission.
18
+ //
19
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ /**
32
+ * Dispatches the passed event to both an "on<type>" handler as well as via the
33
+ * normal dispatch operation. Does not bubble.
34
+ *
35
+ * @param {!EventTarget} target
36
+ * @param {!Event} event
37
+ * @return {boolean}
38
+ */
39
+ function safeDispatchEvent(target, event) {
40
+ var check = "on" + event.type.toLowerCase();
41
+ if (typeof target[check] === "function") {
42
+ target[check](event);
43
+ }
44
+ return target.dispatchEvent(event);
45
+ }
46
+
47
+ /**
48
+ * @param {Element} el to check for stacking context
49
+ * @return {boolean} whether this el or its parents creates a stacking context
50
+ */
51
+ function createsStackingContext(el) {
52
+ while (el && el !== document.body) {
53
+ var s = window.getComputedStyle(el);
54
+ var invalid = function (k, ok) {
55
+ return !(s[k] === undefined || s[k] === ok);
56
+ };
57
+
58
+ if (
59
+ s.opacity < 1 ||
60
+ invalid("zIndex", "auto") ||
61
+ invalid("transform", "none") ||
62
+ invalid("mixBlendMode", "normal") ||
63
+ invalid("filter", "none") ||
64
+ invalid("perspective", "none") ||
65
+ s["isolation"] === "isolate" ||
66
+ s.position === "fixed" ||
67
+ s.webkitOverflowScrolling === "touch"
68
+ ) {
69
+ return true;
70
+ }
71
+ el = el.parentElement;
72
+ }
73
+ return false;
74
+ }
75
+
76
+ /**
77
+ * Finds the nearest <dialog> from the passed element.
78
+ *
79
+ * @param {Element} el to search from
80
+ * @return {HTMLDialogElement} dialog found
81
+ */
82
+ function findNearestDialog(el) {
83
+ while (el) {
84
+ if (el.localName === "dialog") {
85
+ return /** @type {HTMLDialogElement} */ el;
86
+ }
87
+ if (el.parentElement) {
88
+ el = el.parentElement;
89
+ } else if (el.parentNode) {
90
+ el = el.parentNode.host;
91
+ } else {
92
+ el = null;
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /**
99
+ * Blur the specified element, as long as it's not the HTML body element.
100
+ * This works around an IE9/10 bug - blurring the body causes Windows to
101
+ * blur the whole application.
102
+ *
103
+ * @param {Element} el to blur
104
+ */
105
+ function safeBlur(el) {
106
+ // Find the actual focused element when the active element is inside a shadow root
107
+ while (el && el.shadowRoot && el.shadowRoot.activeElement) {
108
+ el = el.shadowRoot.activeElement;
109
+ }
110
+
111
+ if (el && el.blur && el !== document.body) {
112
+ el.blur();
113
+ }
114
+ }
115
+
116
+ /**
117
+ * @param {!NodeList} nodeList to search
118
+ * @param {Node} node to find
119
+ * @return {boolean} whether node is inside nodeList
120
+ */
121
+ function inNodeList(nodeList, node) {
122
+ for (var i = 0; i < nodeList.length; ++i) {
123
+ if (nodeList[i] === node) {
124
+ return true;
125
+ }
126
+ }
127
+ return false;
128
+ }
129
+
130
+ /**
131
+ * @param {HTMLFormElement} el to check
132
+ * @return {boolean} whether this form has method="dialog"
133
+ */
134
+ function isFormMethodDialog(el) {
135
+ if (!el || !el.hasAttribute("method")) {
136
+ return false;
137
+ }
138
+ return el.getAttribute("method").toLowerCase() === "dialog";
139
+ }
140
+
141
+ /**
142
+ * @param {!DocumentFragment|!Element} hostElement
143
+ * @return {?Element}
144
+ */
145
+ function findFocusableElementWithin(hostElement) {
146
+ // Note that this is 'any focusable area'. This list is probably not exhaustive, but the
147
+ // alternative involves stepping through and trying to focus everything.
148
+ var opts = ["button", "input", "keygen", "select", "textarea"];
149
+ var query = opts.map(function (el) {
150
+ return el + ":not([disabled])";
151
+ });
152
+ // TODO(samthor): tabindex values that are not numeric are not focusable.
153
+ query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled
154
+ var target = hostElement.querySelector(query.join(", "));
155
+
156
+ if (!target && "attachShadow" in Element.prototype) {
157
+ // If we haven't found a focusable target, see if the host element contains an element
158
+ // which has a shadowRoot.
159
+ // Recursively search for the first focusable item in shadow roots.
160
+ var elems = hostElement.querySelectorAll("*");
161
+ for (var i = 0; i < elems.length; i++) {
162
+ if (elems[i].tagName && elems[i].shadowRoot) {
163
+ target = findFocusableElementWithin(elems[i].shadowRoot);
164
+ if (target) {
165
+ break;
166
+ }
167
+ }
168
+ }
169
+ }
170
+ return target;
171
+ }
172
+
173
+ /**
174
+ * Determines if an element is attached to the DOM.
175
+ * @param {Element} element to check
176
+ * @return {boolean} whether the element is in DOM
177
+ */
178
+ function isConnected(element) {
179
+ return element.isConnected || document.body.contains(element);
180
+ }
181
+
182
+ /**
183
+ * @param {!Event} event
184
+ * @return {?Element}
185
+ */
186
+ function findFormSubmitter(event) {
187
+ if (event.submitter) {
188
+ return event.submitter;
189
+ }
190
+
191
+ var form = event.target;
192
+ if (!(form instanceof HTMLFormElement)) {
193
+ return null;
194
+ }
195
+
196
+ var submitter = dialogPolyfill.formSubmitter;
197
+ if (!submitter) {
198
+ var target = event.target;
199
+ var root = ("getRootNode" in target && target.getRootNode()) || document;
200
+ submitter = root.activeElement;
201
+ }
202
+
203
+ if (!submitter || submitter.form !== form) {
204
+ return null;
205
+ }
206
+ return submitter;
207
+ }
208
+
209
+ /**
210
+ * @param {!Event} event
211
+ */
212
+ function maybeHandleSubmit(event) {
213
+ if (event.defaultPrevented) {
214
+ return;
215
+ }
216
+ var form = /** @type {!HTMLFormElement} */ event.target;
217
+
218
+ // We'd have a value if we clicked on an imagemap.
219
+ var value = dialogPolyfill.imagemapUseValue;
220
+ var submitter = findFormSubmitter(event);
221
+ if (value === null && submitter) {
222
+ value = submitter.value;
223
+ }
224
+
225
+ // There should always be a dialog as this handler is added specifically on them, but check just
226
+ // in case.
227
+ var dialog = findNearestDialog(form);
228
+ if (!dialog) {
229
+ return;
230
+ }
231
+
232
+ // Prefer formmethod on the button.
233
+ var formmethod =
234
+ (submitter && submitter.getAttribute("formmethod")) ||
235
+ form.getAttribute("method");
236
+ if (formmethod !== "dialog") {
237
+ return;
238
+ }
239
+ event.preventDefault();
240
+
241
+ if (value != null) {
242
+ // nb. we explicitly check against null/undefined
243
+ dialog.close(value);
244
+ } else {
245
+ dialog.close();
246
+ }
247
+ }
248
+
249
+ /**
250
+ * @param {!HTMLDialogElement} dialog to upgrade
251
+ * @constructor
252
+ */
253
+ function dialogPolyfillInfo(dialog) {
254
+ this.dialog_ = dialog;
255
+ this.replacedStyleTop_ = false;
256
+ this.openAsModal_ = false;
257
+
258
+ // Set a11y role. Browsers that support dialog implicitly know this already.
259
+ if (!dialog.hasAttribute("role")) {
260
+ dialog.setAttribute("role", "dialog");
261
+ }
262
+
263
+ dialog.show = this.show.bind(this);
264
+ dialog.showModal = this.showModal.bind(this);
265
+ dialog.close = this.close.bind(this);
266
+
267
+ dialog.addEventListener("submit", maybeHandleSubmit, false);
268
+
269
+ if (!("returnValue" in dialog)) {
270
+ dialog.returnValue = "";
271
+ }
272
+
273
+ if ("MutationObserver" in window) {
274
+ var mo = new MutationObserver(this.maybeHideModal.bind(this));
275
+ mo.observe(dialog, { attributes: true, attributeFilter: ["open"] });
276
+ } else {
277
+ // IE10 and below support. Note that DOMNodeRemoved etc fire _before_ removal. They also
278
+ // seem to fire even if the element was removed as part of a parent removal. Use the removed
279
+ // events to force downgrade (useful if removed/immediately added).
280
+ var removed = false;
281
+ var cb = function () {
282
+ removed ? this.downgradeModal() : this.maybeHideModal();
283
+ removed = false;
284
+ }.bind(this);
285
+ var timeout;
286
+ var delayModel = function (ev) {
287
+ if (ev.target !== dialog) {
288
+ return;
289
+ } // not for a child element
290
+ var cand = "DOMNodeRemoved";
291
+ removed |= ev.type.substr(0, cand.length) === cand;
292
+ window.clearTimeout(timeout);
293
+ timeout = window.setTimeout(cb, 0);
294
+ };
295
+ ["DOMAttrModified", "DOMNodeRemoved", "DOMNodeRemovedFromDocument"].forEach(
296
+ function (name) {
297
+ dialog.addEventListener(name, delayModel);
298
+ }
299
+ );
300
+ }
301
+ // Note that the DOM is observed inside DialogManager while any dialog
302
+ // is being displayed as a modal, to catch modal removal from the DOM.
303
+
304
+ Object.defineProperty(dialog, "open", {
305
+ set: this.setOpen.bind(this),
306
+ get: dialog.hasAttribute.bind(dialog, "open"),
307
+ });
308
+
309
+ this.backdrop_ = document.createElement("div");
310
+ this.backdrop_.className = "backdrop";
311
+ this.backdrop_.addEventListener(
312
+ "mouseup",
313
+ this.backdropMouseEvent_.bind(this)
314
+ );
315
+ this.backdrop_.addEventListener(
316
+ "mousedown",
317
+ this.backdropMouseEvent_.bind(this)
318
+ );
319
+ this.backdrop_.addEventListener("click", this.backdropMouseEvent_.bind(this));
320
+ }
321
+
322
+ dialogPolyfillInfo.prototype = /** @type {HTMLDialogElement.prototype} */ {
323
+ get dialog() {
324
+ return this.dialog_;
325
+ },
326
+
327
+ /**
328
+ * Maybe remove this dialog from the modal top layer. This is called when
329
+ * a modal dialog may no longer be tenable, e.g., when the dialog is no
330
+ * longer open or is no longer part of the DOM.
331
+ */
332
+ maybeHideModal: function () {
333
+ if (this.dialog_.hasAttribute("open") && isConnected(this.dialog_)) {
334
+ return;
335
+ }
336
+ this.downgradeModal();
337
+ },
338
+
339
+ /**
340
+ * Remove this dialog from the modal top layer, leaving it as a non-modal.
341
+ */
342
+ downgradeModal: function () {
343
+ if (!this.openAsModal_) {
344
+ return;
345
+ }
346
+ this.openAsModal_ = false;
347
+ this.dialog_.style.zIndex = "";
348
+
349
+ // This won't match the native <dialog> exactly because if the user set top on a centered
350
+ // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's
351
+ // possible to polyfill this perfectly.
352
+ if (this.replacedStyleTop_) {
353
+ this.dialog_.style.top = "";
354
+ this.replacedStyleTop_ = false;
355
+ }
356
+
357
+ // Clear the backdrop and remove from the manager.
358
+ this.backdrop_.parentNode &&
359
+ this.backdrop_.parentNode.removeChild(this.backdrop_);
360
+ dialogPolyfill.dm.removeDialog(this);
361
+ },
362
+
363
+ /**
364
+ * @param {boolean} value whether to open or close this dialog
365
+ */
366
+ setOpen: function (value) {
367
+ if (value) {
368
+ this.dialog_.hasAttribute("open") ||
369
+ this.dialog_.setAttribute("open", "");
370
+ } else {
371
+ this.dialog_.removeAttribute("open");
372
+ this.maybeHideModal(); // nb. redundant with MutationObserver
373
+ }
374
+ },
375
+
376
+ /**
377
+ * Handles mouse events ('mouseup', 'mousedown', 'click') on the fake .backdrop element, redirecting them as if
378
+ * they were on the dialog itself.
379
+ *
380
+ * @param {!Event} e to redirect
381
+ */
382
+ backdropMouseEvent_: function (e) {
383
+ if (!this.dialog_.hasAttribute("tabindex")) {
384
+ // Clicking on the backdrop should move the implicit cursor, even if dialog cannot be
385
+ // focused. Create a fake thing to focus on. If the backdrop was _before_ the dialog, this
386
+ // would not be needed - clicks would move the implicit cursor there.
387
+ var fake = document.createElement("div");
388
+ this.dialog_.insertBefore(fake, this.dialog_.firstChild);
389
+ fake.tabIndex = -1;
390
+ fake.focus();
391
+ this.dialog_.removeChild(fake);
392
+ } else {
393
+ this.dialog_.focus();
394
+ }
395
+
396
+ var redirectedEvent = document.createEvent("MouseEvents");
397
+ redirectedEvent.initMouseEvent(
398
+ e.type,
399
+ e.bubbles,
400
+ e.cancelable,
401
+ window,
402
+ e.detail,
403
+ e.screenX,
404
+ e.screenY,
405
+ e.clientX,
406
+ e.clientY,
407
+ e.ctrlKey,
408
+ e.altKey,
409
+ e.shiftKey,
410
+ e.metaKey,
411
+ e.button,
412
+ e.relatedTarget
413
+ );
414
+ this.dialog_.dispatchEvent(redirectedEvent);
415
+ e.stopPropagation();
416
+ },
417
+
418
+ /**
419
+ * Focuses on the first focusable element within the dialog. This will always blur the current
420
+ * focus, even if nothing within the dialog is found.
421
+ */
422
+ focus_: function () {
423
+ // Find element with `autofocus` attribute, or fall back to the first form/tabindex control.
424
+ var target = this.dialog_.querySelector("[autofocus]:not([disabled])");
425
+ if (!target && this.dialog_.tabIndex >= 0) {
426
+ target = this.dialog_;
427
+ }
428
+ if (!target) {
429
+ target = findFocusableElementWithin(this.dialog_);
430
+ }
431
+ safeBlur(document.activeElement);
432
+ target && target.focus();
433
+ },
434
+
435
+ /**
436
+ * Sets the zIndex for the backdrop and dialog.
437
+ *
438
+ * @param {number} dialogZ
439
+ * @param {number} backdropZ
440
+ */
441
+ updateZIndex: function (dialogZ, backdropZ) {
442
+ if (dialogZ < backdropZ) {
443
+ throw new Error("dialogZ should never be < backdropZ");
444
+ }
445
+ this.dialog_.style.zIndex = dialogZ;
446
+ this.backdrop_.style.zIndex = backdropZ;
447
+ },
448
+
449
+ /**
450
+ * Shows the dialog. If the dialog is already open, this does nothing.
451
+ */
452
+ show: function () {
453
+ if (!this.dialog_.open) {
454
+ this.setOpen(true);
455
+ this.focus_();
456
+ }
457
+ },
458
+
459
+ /**
460
+ * Show this dialog modally.
461
+ */
462
+ showModal: function () {
463
+ if (this.dialog_.hasAttribute("open")) {
464
+ throw new Error(
465
+ "Failed to execute 'showModal' on dialog: The element is already open, and therefore cannot be opened modally."
466
+ );
467
+ }
468
+ if (!isConnected(this.dialog_)) {
469
+ throw new Error(
470
+ "Failed to execute 'showModal' on dialog: The element is not in a Document."
471
+ );
472
+ }
473
+ if (!dialogPolyfill.dm.pushDialog(this)) {
474
+ throw new Error(
475
+ "Failed to execute 'showModal' on dialog: There are too many open modal dialogs."
476
+ );
477
+ }
478
+
479
+ if (createsStackingContext(this.dialog_.parentElement)) {
480
+ console.warn(
481
+ "A dialog is being shown inside a stacking context. " +
482
+ "This may cause it to be unusable. For more information, see this link: " +
483
+ "https://github.com/GoogleChrome/dialog-polyfill/#stacking-context"
484
+ );
485
+ }
486
+
487
+ this.setOpen(true);
488
+ this.openAsModal_ = true;
489
+
490
+ // Optionally center vertically, relative to the current viewport.
491
+ if (dialogPolyfill.needsCentering(this.dialog_)) {
492
+ dialogPolyfill.reposition(this.dialog_);
493
+ this.replacedStyleTop_ = true;
494
+ } else {
495
+ this.replacedStyleTop_ = false;
496
+ }
497
+
498
+ // Insert backdrop.
499
+ this.dialog_.parentNode.insertBefore(
500
+ this.backdrop_,
501
+ this.dialog_.nextSibling
502
+ );
503
+
504
+ // Focus on whatever inside the dialog.
505
+ this.focus_();
506
+ },
507
+
508
+ /**
509
+ * Closes this HTMLDialogElement. This is optional vs clearing the open
510
+ * attribute, however this fires a 'close' event.
511
+ *
512
+ * @param {string=} opt_returnValue to use as the returnValue
513
+ */
514
+ close: function (opt_returnValue) {
515
+ if (!this.dialog_.hasAttribute("open")) {
516
+ throw new Error(
517
+ "Failed to execute 'close' on dialog: The element does not have an 'open' attribute, and therefore cannot be closed."
518
+ );
519
+ }
520
+ this.setOpen(false);
521
+
522
+ // Leave returnValue untouched in case it was set directly on the element
523
+ if (opt_returnValue !== undefined) {
524
+ this.dialog_.returnValue = opt_returnValue;
525
+ }
526
+
527
+ // Triggering "close" event for any attached listeners on the <dialog>.
528
+ var closeEvent = new window.CustomEvent("close", {
529
+ bubbles: false,
530
+ cancelable: false,
531
+ });
532
+ safeDispatchEvent(this.dialog_, closeEvent);
533
+ },
534
+ };
535
+
536
+ var dialogPolyfill = {};
537
+
538
+ dialogPolyfill.reposition = function (element) {
539
+ var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
540
+ var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2;
541
+ element.style.top = Math.max(scrollTop, topValue) + "px";
542
+ };
543
+
544
+ dialogPolyfill.isInlinePositionSetByStylesheet = function (element) {
545
+ for (var i = 0; i < document.styleSheets.length; ++i) {
546
+ var styleSheet = document.styleSheets[i];
547
+ var cssRules = null;
548
+ // Some browsers throw on cssRules.
549
+ try {
550
+ cssRules = styleSheet.cssRules;
551
+ } catch (e) {
552
+ /* empty */
553
+ }
554
+ if (!cssRules) {
555
+ continue;
556
+ }
557
+ for (var j = 0; j < cssRules.length; ++j) {
558
+ var rule = cssRules[j];
559
+ var selectedNodes = null;
560
+ // Ignore errors on invalid selector texts.
561
+ try {
562
+ selectedNodes = document.querySelectorAll(rule.selectorText);
563
+ } catch (e) {
564
+ /* empty */
565
+ }
566
+ if (!selectedNodes || !inNodeList(selectedNodes, element)) {
567
+ continue;
568
+ }
569
+ var cssTop = rule.style.getPropertyValue("top");
570
+ var cssBottom = rule.style.getPropertyValue("bottom");
571
+ if (
572
+ (cssTop && cssTop !== "auto") ||
573
+ (cssBottom && cssBottom !== "auto")
574
+ ) {
575
+ return true;
576
+ }
577
+ }
578
+ }
579
+ return false;
580
+ };
581
+
582
+ dialogPolyfill.needsCentering = function (dialog) {
583
+ var computedStyle = window.getComputedStyle(dialog);
584
+ if (computedStyle.position !== "absolute") {
585
+ return false;
586
+ }
587
+
588
+ // We must determine whether the top/bottom specified value is non-auto. In
589
+ // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but
590
+ // Firefox returns the used value. So we do this crazy thing instead: check
591
+ // the inline style and then go through CSS rules.
592
+ if (
593
+ (dialog.style.top !== "auto" && dialog.style.top !== "") ||
594
+ (dialog.style.bottom !== "auto" && dialog.style.bottom !== "")
595
+ ) {
596
+ return false;
597
+ }
598
+ return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog);
599
+ };
600
+
601
+ /**
602
+ * @param {!Element} element to force upgrade
603
+ */
604
+ dialogPolyfill.forceRegisterDialog = function (element) {
605
+ if (window.HTMLDialogElement || element.showModal) {
606
+ console.warn(
607
+ "This browser already supports <dialog>, the polyfill " +
608
+ "may not work correctly",
609
+ element
610
+ );
611
+ }
612
+ if (element.localName !== "dialog") {
613
+ throw new Error("Failed to register dialog: The element is not a dialog.");
614
+ }
615
+ new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ element);
616
+ };
617
+
618
+ /**
619
+ * @param {!Element} element to upgrade, if necessary
620
+ */
621
+ dialogPolyfill.registerDialog = function (element) {
622
+ if (!element.showModal) {
623
+ dialogPolyfill.forceRegisterDialog(element);
624
+ }
625
+ };
626
+
627
+ /**
628
+ * @constructor
629
+ */
630
+ dialogPolyfill.DialogManager = function () {
631
+ /** @type {!Array<!dialogPolyfillInfo>} */
632
+ this.pendingDialogStack = [];
633
+
634
+ var checkDOM = this.checkDOM_.bind(this);
635
+
636
+ // The overlay is used to simulate how a modal dialog blocks the document.
637
+ // The blocking dialog is positioned on top of the overlay, and the rest of
638
+ // the dialogs on the pending dialog stack are positioned below it. In the
639
+ // actual implementation, the modal dialog stacking is controlled by the
640
+ // top layer, where z-index has no effect.
641
+ this.overlay = document.createElement("div");
642
+ this.overlay.className = "_dialog_overlay";
643
+ this.overlay.addEventListener(
644
+ "click",
645
+ function (e) {
646
+ this.forwardTab_ = undefined;
647
+ e.stopPropagation();
648
+ checkDOM([]); // sanity-check DOM
649
+ }.bind(this)
650
+ );
651
+
652
+ this.handleKey_ = this.handleKey_.bind(this);
653
+ this.handleFocus_ = this.handleFocus_.bind(this);
654
+
655
+ this.zIndexLow_ = 100000;
656
+ this.zIndexHigh_ = 100000 + 150;
657
+
658
+ this.forwardTab_ = undefined;
659
+
660
+ if ("MutationObserver" in window) {
661
+ this.mo_ = new MutationObserver(function (records) {
662
+ var removed = [];
663
+ records.forEach(function (rec) {
664
+ for (var i = 0, c; (c = rec.removedNodes[i]); ++i) {
665
+ if (!(c instanceof Element)) {
666
+ continue;
667
+ } else if (c.localName === "dialog") {
668
+ removed.push(c);
669
+ }
670
+ removed = removed.concat(c.querySelectorAll("dialog"));
671
+ }
672
+ });
673
+ removed.length && checkDOM(removed);
674
+ });
675
+ }
676
+ };
677
+
678
+ /**
679
+ * Called on the first modal dialog being shown. Adds the overlay and related
680
+ * handlers.
681
+ */
682
+ dialogPolyfill.DialogManager.prototype.blockDocument = function () {
683
+ document.documentElement.addEventListener("focus", this.handleFocus_, true);
684
+ document.addEventListener("keydown", this.handleKey_);
685
+ this.mo_ && this.mo_.observe(document, { childList: true, subtree: true });
686
+ };
687
+
688
+ /**
689
+ * Called on the first modal dialog being removed, i.e., when no more modal
690
+ * dialogs are visible.
691
+ */
692
+ dialogPolyfill.DialogManager.prototype.unblockDocument = function () {
693
+ document.documentElement.removeEventListener(
694
+ "focus",
695
+ this.handleFocus_,
696
+ true
697
+ );
698
+ document.removeEventListener("keydown", this.handleKey_);
699
+ this.mo_ && this.mo_.disconnect();
700
+ };
701
+
702
+ /**
703
+ * Updates the stacking of all known dialogs.
704
+ */
705
+ dialogPolyfill.DialogManager.prototype.updateStacking = function () {
706
+ var zIndex = this.zIndexHigh_;
707
+
708
+ for (var i = 0, dpi; (dpi = this.pendingDialogStack[i]); ++i) {
709
+ dpi.updateZIndex(--zIndex, --zIndex);
710
+ if (i === 0) {
711
+ this.overlay.style.zIndex = --zIndex;
712
+ }
713
+ }
714
+
715
+ // Make the overlay a sibling of the dialog itself.
716
+ var last = this.pendingDialogStack[0];
717
+ if (last) {
718
+ var p = last.dialog.parentNode || document.body;
719
+ p.appendChild(this.overlay);
720
+ } else if (this.overlay.parentNode) {
721
+ this.overlay.parentNode.removeChild(this.overlay);
722
+ }
723
+ };
724
+
725
+ /**
726
+ * @param {Element} candidate to check if contained or is the top-most modal dialog
727
+ * @return {boolean} whether candidate is contained in top dialog
728
+ */
729
+ dialogPolyfill.DialogManager.prototype.containedByTopDialog_ = function (
730
+ candidate
731
+ ) {
732
+ while ((candidate = findNearestDialog(candidate))) {
733
+ for (var i = 0, dpi; (dpi = this.pendingDialogStack[i]); ++i) {
734
+ if (dpi.dialog === candidate) {
735
+ return i === 0; // only valid if top-most
736
+ }
737
+ }
738
+ candidate = candidate.parentElement;
739
+ }
740
+ return false;
741
+ };
742
+
743
+ dialogPolyfill.DialogManager.prototype.handleFocus_ = function (event) {
744
+ var target = event.composedPath ? event.composedPath()[0] : event.target;
745
+
746
+ if (this.containedByTopDialog_(target)) {
747
+ return;
748
+ }
749
+
750
+ if (document.activeElement === document.documentElement) {
751
+ return;
752
+ }
753
+
754
+ event.preventDefault();
755
+ event.stopPropagation();
756
+ safeBlur(/** @type {Element} */ target);
757
+
758
+ if (this.forwardTab_ === undefined) {
759
+ return;
760
+ } // move focus only from a tab key
761
+
762
+ var dpi = this.pendingDialogStack[0];
763
+ var dialog = dpi.dialog;
764
+ var position = dialog.compareDocumentPosition(target);
765
+ if (position & Node.DOCUMENT_POSITION_PRECEDING) {
766
+ if (this.forwardTab_) {
767
+ // forward
768
+ dpi.focus_();
769
+ } else if (target !== document.documentElement) {
770
+ // backwards if we're not already focused on <html>
771
+ document.documentElement.focus();
772
+ }
773
+ } else {
774
+ // TODO: Focus after the dialog, is ignored.
775
+ }
776
+
777
+ return false;
778
+ };
779
+
780
+ dialogPolyfill.DialogManager.prototype.handleKey_ = function (event) {
781
+ this.forwardTab_ = undefined;
782
+ if (event.keyCode === 27) {
783
+ event.preventDefault();
784
+ event.stopPropagation();
785
+ var cancelEvent = new window.CustomEvent("cancel", {
786
+ bubbles: false,
787
+ cancelable: true,
788
+ });
789
+ var dpi = this.pendingDialogStack[0];
790
+ if (dpi && safeDispatchEvent(dpi.dialog, cancelEvent)) {
791
+ dpi.dialog.close();
792
+ }
793
+ } else if (event.keyCode === 9) {
794
+ this.forwardTab_ = !event.shiftKey;
795
+ }
796
+ };
797
+
798
+ /**
799
+ * Finds and downgrades any known modal dialogs that are no longer displayed. Dialogs that are
800
+ * removed and immediately readded don't stay modal, they become normal.
801
+ *
802
+ * @param {!Array<!HTMLDialogElement>} removed that have definitely been removed
803
+ */
804
+ dialogPolyfill.DialogManager.prototype.checkDOM_ = function (removed) {
805
+ // This operates on a clone because it may cause it to change. Each change also calls
806
+ // updateStacking, which only actually needs to happen once. But who removes many modal dialogs
807
+ // at a time?!
808
+ var clone = this.pendingDialogStack.slice();
809
+ clone.forEach(function (dpi) {
810
+ if (removed.indexOf(dpi.dialog) !== -1) {
811
+ dpi.downgradeModal();
812
+ } else {
813
+ dpi.maybeHideModal();
814
+ }
815
+ });
816
+ };
817
+
818
+ /**
819
+ * @param {!dialogPolyfillInfo} dpi
820
+ * @return {boolean} whether the dialog was allowed
821
+ */
822
+ dialogPolyfill.DialogManager.prototype.pushDialog = function (dpi) {
823
+ var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1;
824
+ if (this.pendingDialogStack.length >= allowed) {
825
+ return false;
826
+ }
827
+ if (this.pendingDialogStack.unshift(dpi) === 1) {
828
+ this.blockDocument();
829
+ }
830
+ this.updateStacking();
831
+ return true;
832
+ };
833
+
834
+ /**
835
+ * @param {!dialogPolyfillInfo} dpi
836
+ */
837
+ dialogPolyfill.DialogManager.prototype.removeDialog = function (dpi) {
838
+ var index = this.pendingDialogStack.indexOf(dpi);
839
+ if (index === -1) {
840
+ return;
841
+ }
842
+
843
+ this.pendingDialogStack.splice(index, 1);
844
+ if (this.pendingDialogStack.length === 0) {
845
+ this.unblockDocument();
846
+ }
847
+ this.updateStacking();
848
+ };
849
+
850
+ if (typeof window !== "undefined" && window.HTMLDialogElement === undefined) {
851
+ dialogPolyfill.dm = new dialogPolyfill.DialogManager();
852
+ dialogPolyfill.formSubmitter = null;
853
+ dialogPolyfill.imagemapUseValue = null;
854
+ }
855
+
856
+ /**
857
+ * Installs global handlers, such as click listers and native method overrides. These are needed
858
+ * even if a no dialog is registered, as they deal with <form method="dialog">.
859
+ */
860
+ if (typeof window !== "undefined" && window.HTMLDialogElement === undefined) {
861
+ /**
862
+ * If HTMLFormElement translates method="DIALOG" into 'get', then replace the descriptor with
863
+ * one that returns the correct value.
864
+ */
865
+ var testForm = document.createElement("form");
866
+ testForm.setAttribute("method", "dialog");
867
+ if (testForm.method !== "dialog") {
868
+ var methodDescriptor = Object.getOwnPropertyDescriptor(
869
+ HTMLFormElement.prototype,
870
+ "method"
871
+ );
872
+ if (methodDescriptor) {
873
+ // nb. Some older iOS and older PhantomJS fail to return the descriptor. Don't do anything
874
+ // and don't bother to update the element.
875
+ var realGet = methodDescriptor.get;
876
+ methodDescriptor.get = function () {
877
+ if (isFormMethodDialog(this)) {
878
+ return "dialog";
879
+ }
880
+ return realGet.call(this);
881
+ };
882
+ var realSet = methodDescriptor.set;
883
+ /** @this {HTMLElement} */
884
+ methodDescriptor.set = function (v) {
885
+ if (typeof v === "string" && v.toLowerCase() === "dialog") {
886
+ return this.setAttribute("method", v);
887
+ }
888
+ return realSet.call(this, v);
889
+ };
890
+ Object.defineProperty(
891
+ HTMLFormElement.prototype,
892
+ "method",
893
+ methodDescriptor
894
+ );
895
+ }
896
+ }
897
+
898
+ /**
899
+ * Global 'click' handler, to capture the <input type="submit"> or <button> element which has
900
+ * submitted a <form method="dialog">. Needed as Safari and others don't report this inside
901
+ * document.activeElement.
902
+ */
903
+ document.addEventListener(
904
+ "click",
905
+ function (ev) {
906
+ dialogPolyfill.formSubmitter = null;
907
+ dialogPolyfill.imagemapUseValue = null;
908
+ if (ev.defaultPrevented) {
909
+ return;
910
+ } // e.g. a submit which prevents default submission
911
+
912
+ var target = /** @type {Element} */ ev.target;
913
+ if ("composedPath" in ev) {
914
+ var path = ev.composedPath();
915
+ target = path.shift() || target;
916
+ }
917
+ if (!target || !isFormMethodDialog(target.form)) {
918
+ return;
919
+ }
920
+
921
+ var valid =
922
+ target.type === "submit" &&
923
+ ["button", "input"].indexOf(target.localName) > -1;
924
+ if (!valid) {
925
+ if (!(target.localName === "input" && target.type === "image")) {
926
+ return;
927
+ }
928
+ // this is a <input type="image">, which can submit forms
929
+ dialogPolyfill.imagemapUseValue = ev.offsetX + "," + ev.offsetY;
930
+ }
931
+
932
+ var dialog = findNearestDialog(target);
933
+ if (!dialog) {
934
+ return;
935
+ }
936
+
937
+ dialogPolyfill.formSubmitter = target;
938
+ },
939
+ false
940
+ );
941
+
942
+ /**
943
+ * Global 'submit' handler. This handles submits of `method="dialog"` which are invalid, i.e.,
944
+ * outside a dialog. They get prevented.
945
+ */
946
+ document.addEventListener("submit", function (ev) {
947
+ var form = ev.target;
948
+ var dialog = findNearestDialog(form);
949
+ if (dialog) {
950
+ return; // ignore, handle there
951
+ }
952
+
953
+ var submitter = findFormSubmitter(ev);
954
+ var formmethod =
955
+ (submitter && submitter.getAttribute("formmethod")) ||
956
+ form.getAttribute("method");
957
+ if (formmethod === "dialog") {
958
+ ev.preventDefault();
959
+ }
960
+ });
961
+
962
+ /**
963
+ * Replace the native HTMLFormElement.submit() method, as it won't fire the
964
+ * submit event and give us a chance to respond.
965
+ */
966
+ var nativeFormSubmit = HTMLFormElement.prototype.submit;
967
+ var replacementFormSubmit = function () {
968
+ if (!isFormMethodDialog(this)) {
969
+ return nativeFormSubmit.call(this);
970
+ }
971
+ var dialog = findNearestDialog(this);
972
+ dialog && dialog.close();
973
+ };
974
+ HTMLFormElement.prototype.submit = replacementFormSubmit;
975
+ }
976
+
977
+ export default dialogPolyfill as {
978
+ registerDialog(dialog: HTMLDialogElement): void;
979
+ forceRegisterDialog(dialog: HTMLDialogElement): void;
980
+ };