blob: bd60a702691e9bf1eccc2a7daff985926df7ab98 [file] [log] [blame]
Copybara botbe50d492023-11-30 00:16:42 +01001(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (global = global || self, global.dialogPolyfill = factory());
5}(this, function () { 'use strict';
6
7 // nb. This is for IE10 and lower _only_.
8 var supportCustomEvent = window.CustomEvent;
9 if (!supportCustomEvent || typeof supportCustomEvent === 'object') {
10 supportCustomEvent = function CustomEvent(event, x) {
11 x = x || {};
12 var ev = document.createEvent('CustomEvent');
13 ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null);
14 return ev;
15 };
16 supportCustomEvent.prototype = window.Event.prototype;
17 }
18
19 /**
Renovate botf591dcf2023-12-30 14:13:54 +000020 * Dispatches the passed event to both an "on<type>" handler as well as via the
21 * normal dispatch operation. Does not bubble.
22 *
23 * @param {!EventTarget} target
24 * @param {!Event} event
25 * @return {boolean}
26 */
27 function safeDispatchEvent(target, event) {
28 var check = 'on' + event.type.toLowerCase();
29 if (typeof target[check] === 'function') {
30 target[check](event);
31 }
32 return target.dispatchEvent(event);
33 }
34
35 /**
Copybara botbe50d492023-11-30 00:16:42 +010036 * @param {Element} el to check for stacking context
37 * @return {boolean} whether this el or its parents creates a stacking context
38 */
39 function createsStackingContext(el) {
40 while (el && el !== document.body) {
41 var s = window.getComputedStyle(el);
42 var invalid = function(k, ok) {
43 return !(s[k] === undefined || s[k] === ok);
44 };
Renovate botf591dcf2023-12-30 14:13:54 +000045
Copybara botbe50d492023-11-30 00:16:42 +010046 if (s.opacity < 1 ||
47 invalid('zIndex', 'auto') ||
48 invalid('transform', 'none') ||
49 invalid('mixBlendMode', 'normal') ||
50 invalid('filter', 'none') ||
51 invalid('perspective', 'none') ||
52 s['isolation'] === 'isolate' ||
53 s.position === 'fixed' ||
54 s.webkitOverflowScrolling === 'touch') {
55 return true;
56 }
57 el = el.parentElement;
58 }
59 return false;
60 }
61
62 /**
63 * Finds the nearest <dialog> from the passed element.
64 *
65 * @param {Element} el to search from
66 * @return {HTMLDialogElement} dialog found
67 */
68 function findNearestDialog(el) {
69 while (el) {
70 if (el.localName === 'dialog') {
71 return /** @type {HTMLDialogElement} */ (el);
72 }
73 el = el.parentElement;
74 }
75 return null;
76 }
77
78 /**
79 * Blur the specified element, as long as it's not the HTML body element.
80 * This works around an IE9/10 bug - blurring the body causes Windows to
81 * blur the whole application.
82 *
83 * @param {Element} el to blur
84 */
85 function safeBlur(el) {
Renovate botf591dcf2023-12-30 14:13:54 +000086 // Find the actual focused element when the active element is inside a shadow root
87 while (el && el.shadowRoot && el.shadowRoot.activeElement) {
88 el = el.shadowRoot.activeElement;
89 }
90
Copybara botbe50d492023-11-30 00:16:42 +010091 if (el && el.blur && el !== document.body) {
92 el.blur();
93 }
94 }
95
96 /**
97 * @param {!NodeList} nodeList to search
98 * @param {Node} node to find
99 * @return {boolean} whether node is inside nodeList
100 */
101 function inNodeList(nodeList, node) {
102 for (var i = 0; i < nodeList.length; ++i) {
103 if (nodeList[i] === node) {
104 return true;
105 }
106 }
107 return false;
108 }
109
110 /**
111 * @param {HTMLFormElement} el to check
112 * @return {boolean} whether this form has method="dialog"
113 */
114 function isFormMethodDialog(el) {
115 if (!el || !el.hasAttribute('method')) {
116 return false;
117 }
118 return el.getAttribute('method').toLowerCase() === 'dialog';
119 }
120
121 /**
Renovate botf591dcf2023-12-30 14:13:54 +0000122 * @param {!DocumentFragment|!Element} hostElement
123 * @return {?Element}
124 */
125 function findFocusableElementWithin(hostElement) {
126 // Note that this is 'any focusable area'. This list is probably not exhaustive, but the
127 // alternative involves stepping through and trying to focus everything.
128 var opts = ['button', 'input', 'keygen', 'select', 'textarea'];
129 var query = opts.map(function(el) {
130 return el + ':not([disabled])';
131 });
132 // TODO(samthor): tabindex values that are not numeric are not focusable.
133 query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled
134 var target = hostElement.querySelector(query.join(', '));
135
136 if (!target && 'attachShadow' in Element.prototype) {
137 // If we haven't found a focusable target, see if the host element contains an element
138 // which has a shadowRoot.
139 // Recursively search for the first focusable item in shadow roots.
140 var elems = hostElement.querySelectorAll('*');
141 for (var i = 0; i < elems.length; i++) {
142 if (elems[i].tagName && elems[i].shadowRoot) {
143 target = findFocusableElementWithin(elems[i].shadowRoot);
144 if (target) {
145 break;
146 }
147 }
148 }
149 }
150 return target;
151 }
152
153 /**
154 * Determines if an element is attached to the DOM.
155 * @param {Element} element to check
156 * @return {Boolean} whether the element is in DOM
157 */
158 function isConnected(element) {
159 return element.isConnected || document.body.contains(element);
160 }
161
162 /**
163 * @param {!Event} event
164 */
165 function findFormSubmitter(event) {
166 if (event.submitter) {
167 return event.submitter;
168 }
169
170 var form = event.target;
171 if (!(form instanceof HTMLFormElement)) {
172 return null;
173 }
174
175 var submitter = dialogPolyfill.formSubmitter;
176 if (!submitter) {
177 var target = event.target;
178 var root = ('getRootNode' in target && target.getRootNode() || document);
179 submitter = root.activeElement;
180 }
181
182 if (submitter.form !== form) {
183 return null;
184 }
185 return submitter;
186 }
187
188 /**
189 * @param {!Event} event
190 */
191 function maybeHandleSubmit(event) {
192 if (event.defaultPrevented) {
193 return;
194 }
195 var form = /** @type {!HTMLFormElement} */ (event.target);
196
197 // We'd have a value if we clicked on an imagemap.
198 var value = dialogPolyfill.useValue;
199 var submitter = findFormSubmitter(event);
200 if (value === null && submitter) {
201 value = submitter.value;
202 }
203
204 // There should always be a dialog as this handler is added specifically on them, but check just
205 // in case.
206 var dialog = findNearestDialog(form);
207 if (!dialog) {
208 return;
209 }
210
211 // Prefer formmethod on the button.
212 var formmethod = submitter && submitter.getAttribute('formmethod') || form.getAttribute('method');
213 if (formmethod !== 'dialog') {
214 return;
215 }
216 event.preventDefault();
217
218 if (submitter) {
219 dialog.close(value);
220 } else {
221 dialog.close();
222 }
223 }
224
225 /**
Copybara botbe50d492023-11-30 00:16:42 +0100226 * @param {!HTMLDialogElement} dialog to upgrade
227 * @constructor
228 */
229 function dialogPolyfillInfo(dialog) {
230 this.dialog_ = dialog;
231 this.replacedStyleTop_ = false;
232 this.openAsModal_ = false;
233
234 // Set a11y role. Browsers that support dialog implicitly know this already.
235 if (!dialog.hasAttribute('role')) {
236 dialog.setAttribute('role', 'dialog');
237 }
238
239 dialog.show = this.show.bind(this);
240 dialog.showModal = this.showModal.bind(this);
241 dialog.close = this.close.bind(this);
242
Renovate botf591dcf2023-12-30 14:13:54 +0000243 dialog.addEventListener('submit', maybeHandleSubmit, false);
244
Copybara botbe50d492023-11-30 00:16:42 +0100245 if (!('returnValue' in dialog)) {
246 dialog.returnValue = '';
247 }
248
249 if ('MutationObserver' in window) {
250 var mo = new MutationObserver(this.maybeHideModal.bind(this));
251 mo.observe(dialog, {attributes: true, attributeFilter: ['open']});
252 } else {
253 // IE10 and below support. Note that DOMNodeRemoved etc fire _before_ removal. They also
254 // seem to fire even if the element was removed as part of a parent removal. Use the removed
255 // events to force downgrade (useful if removed/immediately added).
256 var removed = false;
257 var cb = function() {
258 removed ? this.downgradeModal() : this.maybeHideModal();
259 removed = false;
260 }.bind(this);
261 var timeout;
262 var delayModel = function(ev) {
263 if (ev.target !== dialog) { return; } // not for a child element
264 var cand = 'DOMNodeRemoved';
265 removed |= (ev.type.substr(0, cand.length) === cand);
266 window.clearTimeout(timeout);
267 timeout = window.setTimeout(cb, 0);
268 };
269 ['DOMAttrModified', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument'].forEach(function(name) {
270 dialog.addEventListener(name, delayModel);
271 });
272 }
273 // Note that the DOM is observed inside DialogManager while any dialog
274 // is being displayed as a modal, to catch modal removal from the DOM.
275
276 Object.defineProperty(dialog, 'open', {
277 set: this.setOpen.bind(this),
278 get: dialog.hasAttribute.bind(dialog, 'open')
279 });
280
281 this.backdrop_ = document.createElement('div');
282 this.backdrop_.className = 'backdrop';
Renovate botf591dcf2023-12-30 14:13:54 +0000283 this.backdrop_.addEventListener('mouseup' , this.backdropMouseEvent_.bind(this));
284 this.backdrop_.addEventListener('mousedown', this.backdropMouseEvent_.bind(this));
285 this.backdrop_.addEventListener('click' , this.backdropMouseEvent_.bind(this));
Copybara botbe50d492023-11-30 00:16:42 +0100286 }
287
Renovate botf591dcf2023-12-30 14:13:54 +0000288 dialogPolyfillInfo.prototype = /** @type {HTMLDialogElement.prototype} */ ({
Copybara botbe50d492023-11-30 00:16:42 +0100289
290 get dialog() {
291 return this.dialog_;
292 },
293
294 /**
295 * Maybe remove this dialog from the modal top layer. This is called when
296 * a modal dialog may no longer be tenable, e.g., when the dialog is no
297 * longer open or is no longer part of the DOM.
298 */
299 maybeHideModal: function() {
Renovate botf591dcf2023-12-30 14:13:54 +0000300 if (this.dialog_.hasAttribute('open') && isConnected(this.dialog_)) { return; }
Copybara botbe50d492023-11-30 00:16:42 +0100301 this.downgradeModal();
302 },
303
304 /**
305 * Remove this dialog from the modal top layer, leaving it as a non-modal.
306 */
307 downgradeModal: function() {
308 if (!this.openAsModal_) { return; }
309 this.openAsModal_ = false;
310 this.dialog_.style.zIndex = '';
311
312 // This won't match the native <dialog> exactly because if the user set top on a centered
313 // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's
314 // possible to polyfill this perfectly.
315 if (this.replacedStyleTop_) {
316 this.dialog_.style.top = '';
317 this.replacedStyleTop_ = false;
318 }
319
320 // Clear the backdrop and remove from the manager.
321 this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_);
322 dialogPolyfill.dm.removeDialog(this);
323 },
324
325 /**
326 * @param {boolean} value whether to open or close this dialog
327 */
328 setOpen: function(value) {
329 if (value) {
330 this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', '');
331 } else {
332 this.dialog_.removeAttribute('open');
333 this.maybeHideModal(); // nb. redundant with MutationObserver
334 }
335 },
336
337 /**
Renovate botf591dcf2023-12-30 14:13:54 +0000338 * Handles mouse events ('mouseup', 'mousedown', 'click') on the fake .backdrop element, redirecting them as if
Copybara botbe50d492023-11-30 00:16:42 +0100339 * they were on the dialog itself.
340 *
341 * @param {!Event} e to redirect
342 */
Renovate botf591dcf2023-12-30 14:13:54 +0000343 backdropMouseEvent_: function(e) {
Copybara botbe50d492023-11-30 00:16:42 +0100344 if (!this.dialog_.hasAttribute('tabindex')) {
345 // Clicking on the backdrop should move the implicit cursor, even if dialog cannot be
346 // focused. Create a fake thing to focus on. If the backdrop was _before_ the dialog, this
347 // would not be needed - clicks would move the implicit cursor there.
348 var fake = document.createElement('div');
349 this.dialog_.insertBefore(fake, this.dialog_.firstChild);
350 fake.tabIndex = -1;
351 fake.focus();
352 this.dialog_.removeChild(fake);
353 } else {
354 this.dialog_.focus();
355 }
356
357 var redirectedEvent = document.createEvent('MouseEvents');
358 redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window,
359 e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey,
360 e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
361 this.dialog_.dispatchEvent(redirectedEvent);
362 e.stopPropagation();
363 },
364
365 /**
366 * Focuses on the first focusable element within the dialog. This will always blur the current
367 * focus, even if nothing within the dialog is found.
368 */
369 focus_: function() {
370 // Find element with `autofocus` attribute, or fall back to the first form/tabindex control.
371 var target = this.dialog_.querySelector('[autofocus]:not([disabled])');
372 if (!target && this.dialog_.tabIndex >= 0) {
373 target = this.dialog_;
374 }
375 if (!target) {
Renovate botf591dcf2023-12-30 14:13:54 +0000376 target = findFocusableElementWithin(this.dialog_);
Copybara botbe50d492023-11-30 00:16:42 +0100377 }
378 safeBlur(document.activeElement);
379 target && target.focus();
380 },
381
382 /**
383 * Sets the zIndex for the backdrop and dialog.
384 *
385 * @param {number} dialogZ
386 * @param {number} backdropZ
387 */
388 updateZIndex: function(dialogZ, backdropZ) {
389 if (dialogZ < backdropZ) {
390 throw new Error('dialogZ should never be < backdropZ');
391 }
392 this.dialog_.style.zIndex = dialogZ;
393 this.backdrop_.style.zIndex = backdropZ;
394 },
395
396 /**
397 * Shows the dialog. If the dialog is already open, this does nothing.
398 */
399 show: function() {
400 if (!this.dialog_.open) {
401 this.setOpen(true);
402 this.focus_();
403 }
404 },
405
406 /**
407 * Show this dialog modally.
408 */
409 showModal: function() {
410 if (this.dialog_.hasAttribute('open')) {
411 throw new Error('Failed to execute \'showModal\' on dialog: The element is already open, and therefore cannot be opened modally.');
412 }
Renovate botf591dcf2023-12-30 14:13:54 +0000413 if (!isConnected(this.dialog_)) {
Copybara botbe50d492023-11-30 00:16:42 +0100414 throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.');
415 }
416 if (!dialogPolyfill.dm.pushDialog(this)) {
417 throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.');
418 }
419
420 if (createsStackingContext(this.dialog_.parentElement)) {
421 console.warn('A dialog is being shown inside a stacking context. ' +
422 'This may cause it to be unusable. For more information, see this link: ' +
423 'https://github.com/GoogleChrome/dialog-polyfill/#stacking-context');
424 }
425
426 this.setOpen(true);
427 this.openAsModal_ = true;
428
429 // Optionally center vertically, relative to the current viewport.
430 if (dialogPolyfill.needsCentering(this.dialog_)) {
431 dialogPolyfill.reposition(this.dialog_);
432 this.replacedStyleTop_ = true;
433 } else {
434 this.replacedStyleTop_ = false;
435 }
436
437 // Insert backdrop.
438 this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling);
439
440 // Focus on whatever inside the dialog.
441 this.focus_();
442 },
443
444 /**
445 * Closes this HTMLDialogElement. This is optional vs clearing the open
446 * attribute, however this fires a 'close' event.
447 *
448 * @param {string=} opt_returnValue to use as the returnValue
449 */
450 close: function(opt_returnValue) {
451 if (!this.dialog_.hasAttribute('open')) {
452 throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.');
453 }
454 this.setOpen(false);
455
456 // Leave returnValue untouched in case it was set directly on the element
457 if (opt_returnValue !== undefined) {
458 this.dialog_.returnValue = opt_returnValue;
459 }
460
461 // Triggering "close" event for any attached listeners on the <dialog>.
462 var closeEvent = new supportCustomEvent('close', {
463 bubbles: false,
464 cancelable: false
465 });
Renovate botf591dcf2023-12-30 14:13:54 +0000466 safeDispatchEvent(this.dialog_, closeEvent);
Copybara botbe50d492023-11-30 00:16:42 +0100467 }
468
Renovate botf591dcf2023-12-30 14:13:54 +0000469 });
Copybara botbe50d492023-11-30 00:16:42 +0100470
471 var dialogPolyfill = {};
472
473 dialogPolyfill.reposition = function(element) {
474 var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
475 var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2;
476 element.style.top = Math.max(scrollTop, topValue) + 'px';
477 };
478
479 dialogPolyfill.isInlinePositionSetByStylesheet = function(element) {
480 for (var i = 0; i < document.styleSheets.length; ++i) {
481 var styleSheet = document.styleSheets[i];
482 var cssRules = null;
483 // Some browsers throw on cssRules.
484 try {
485 cssRules = styleSheet.cssRules;
486 } catch (e) {}
487 if (!cssRules) { continue; }
488 for (var j = 0; j < cssRules.length; ++j) {
489 var rule = cssRules[j];
490 var selectedNodes = null;
491 // Ignore errors on invalid selector texts.
492 try {
493 selectedNodes = document.querySelectorAll(rule.selectorText);
494 } catch(e) {}
495 if (!selectedNodes || !inNodeList(selectedNodes, element)) {
496 continue;
497 }
498 var cssTop = rule.style.getPropertyValue('top');
499 var cssBottom = rule.style.getPropertyValue('bottom');
500 if ((cssTop && cssTop !== 'auto') || (cssBottom && cssBottom !== 'auto')) {
501 return true;
502 }
503 }
504 }
505 return false;
506 };
507
508 dialogPolyfill.needsCentering = function(dialog) {
509 var computedStyle = window.getComputedStyle(dialog);
510 if (computedStyle.position !== 'absolute') {
511 return false;
512 }
513
514 // We must determine whether the top/bottom specified value is non-auto. In
515 // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but
516 // Firefox returns the used value. So we do this crazy thing instead: check
517 // the inline style and then go through CSS rules.
518 if ((dialog.style.top !== 'auto' && dialog.style.top !== '') ||
519 (dialog.style.bottom !== 'auto' && dialog.style.bottom !== '')) {
520 return false;
521 }
522 return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog);
523 };
524
525 /**
526 * @param {!Element} element to force upgrade
527 */
528 dialogPolyfill.forceRegisterDialog = function(element) {
529 if (window.HTMLDialogElement || element.showModal) {
530 console.warn('This browser already supports <dialog>, the polyfill ' +
531 'may not work correctly', element);
532 }
533 if (element.localName !== 'dialog') {
534 throw new Error('Failed to register dialog: The element is not a dialog.');
535 }
536 new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element));
537 };
538
539 /**
540 * @param {!Element} element to upgrade, if necessary
541 */
542 dialogPolyfill.registerDialog = function(element) {
543 if (!element.showModal) {
544 dialogPolyfill.forceRegisterDialog(element);
545 }
546 };
547
548 /**
549 * @constructor
550 */
551 dialogPolyfill.DialogManager = function() {
552 /** @type {!Array<!dialogPolyfillInfo>} */
553 this.pendingDialogStack = [];
554
555 var checkDOM = this.checkDOM_.bind(this);
556
557 // The overlay is used to simulate how a modal dialog blocks the document.
558 // The blocking dialog is positioned on top of the overlay, and the rest of
559 // the dialogs on the pending dialog stack are positioned below it. In the
560 // actual implementation, the modal dialog stacking is controlled by the
561 // top layer, where z-index has no effect.
562 this.overlay = document.createElement('div');
563 this.overlay.className = '_dialog_overlay';
564 this.overlay.addEventListener('click', function(e) {
565 this.forwardTab_ = undefined;
566 e.stopPropagation();
567 checkDOM([]); // sanity-check DOM
568 }.bind(this));
569
570 this.handleKey_ = this.handleKey_.bind(this);
571 this.handleFocus_ = this.handleFocus_.bind(this);
572
573 this.zIndexLow_ = 100000;
574 this.zIndexHigh_ = 100000 + 150;
575
576 this.forwardTab_ = undefined;
577
578 if ('MutationObserver' in window) {
579 this.mo_ = new MutationObserver(function(records) {
580 var removed = [];
581 records.forEach(function(rec) {
582 for (var i = 0, c; c = rec.removedNodes[i]; ++i) {
583 if (!(c instanceof Element)) {
584 continue;
585 } else if (c.localName === 'dialog') {
586 removed.push(c);
587 }
588 removed = removed.concat(c.querySelectorAll('dialog'));
589 }
590 });
591 removed.length && checkDOM(removed);
592 });
593 }
594 };
595
596 /**
597 * Called on the first modal dialog being shown. Adds the overlay and related
598 * handlers.
599 */
600 dialogPolyfill.DialogManager.prototype.blockDocument = function() {
601 document.documentElement.addEventListener('focus', this.handleFocus_, true);
602 document.addEventListener('keydown', this.handleKey_);
603 this.mo_ && this.mo_.observe(document, {childList: true, subtree: true});
604 };
605
606 /**
607 * Called on the first modal dialog being removed, i.e., when no more modal
608 * dialogs are visible.
609 */
610 dialogPolyfill.DialogManager.prototype.unblockDocument = function() {
611 document.documentElement.removeEventListener('focus', this.handleFocus_, true);
612 document.removeEventListener('keydown', this.handleKey_);
613 this.mo_ && this.mo_.disconnect();
614 };
615
616 /**
617 * Updates the stacking of all known dialogs.
618 */
619 dialogPolyfill.DialogManager.prototype.updateStacking = function() {
620 var zIndex = this.zIndexHigh_;
621
622 for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
623 dpi.updateZIndex(--zIndex, --zIndex);
624 if (i === 0) {
625 this.overlay.style.zIndex = --zIndex;
626 }
627 }
628
629 // Make the overlay a sibling of the dialog itself.
630 var last = this.pendingDialogStack[0];
631 if (last) {
632 var p = last.dialog.parentNode || document.body;
633 p.appendChild(this.overlay);
634 } else if (this.overlay.parentNode) {
635 this.overlay.parentNode.removeChild(this.overlay);
636 }
637 };
638
639 /**
640 * @param {Element} candidate to check if contained or is the top-most modal dialog
641 * @return {boolean} whether candidate is contained in top dialog
642 */
643 dialogPolyfill.DialogManager.prototype.containedByTopDialog_ = function(candidate) {
644 while (candidate = findNearestDialog(candidate)) {
645 for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
646 if (dpi.dialog === candidate) {
647 return i === 0; // only valid if top-most
648 }
649 }
650 candidate = candidate.parentElement;
651 }
652 return false;
653 };
654
655 dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) {
Renovate botf591dcf2023-12-30 14:13:54 +0000656 var target = event.composedPath ? event.composedPath()[0] : event.target;
657
658 if (this.containedByTopDialog_(target)) { return; }
Copybara botbe50d492023-11-30 00:16:42 +0100659
660 if (document.activeElement === document.documentElement) { return; }
661
662 event.preventDefault();
663 event.stopPropagation();
Renovate botf591dcf2023-12-30 14:13:54 +0000664 safeBlur(/** @type {Element} */ (target));
Copybara botbe50d492023-11-30 00:16:42 +0100665
666 if (this.forwardTab_ === undefined) { return; } // move focus only from a tab key
667
668 var dpi = this.pendingDialogStack[0];
669 var dialog = dpi.dialog;
Renovate botf591dcf2023-12-30 14:13:54 +0000670 var position = dialog.compareDocumentPosition(target);
Copybara botbe50d492023-11-30 00:16:42 +0100671 if (position & Node.DOCUMENT_POSITION_PRECEDING) {
672 if (this.forwardTab_) {
673 // forward
674 dpi.focus_();
Renovate botf591dcf2023-12-30 14:13:54 +0000675 } else if (target !== document.documentElement) {
Copybara botbe50d492023-11-30 00:16:42 +0100676 // backwards if we're not already focused on <html>
677 document.documentElement.focus();
678 }
679 }
680
681 return false;
682 };
683
684 dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) {
685 this.forwardTab_ = undefined;
686 if (event.keyCode === 27) {
687 event.preventDefault();
688 event.stopPropagation();
689 var cancelEvent = new supportCustomEvent('cancel', {
690 bubbles: false,
691 cancelable: true
692 });
693 var dpi = this.pendingDialogStack[0];
Renovate botf591dcf2023-12-30 14:13:54 +0000694 if (dpi && safeDispatchEvent(dpi.dialog, cancelEvent)) {
Copybara botbe50d492023-11-30 00:16:42 +0100695 dpi.dialog.close();
696 }
697 } else if (event.keyCode === 9) {
698 this.forwardTab_ = !event.shiftKey;
699 }
700 };
701
702 /**
703 * Finds and downgrades any known modal dialogs that are no longer displayed. Dialogs that are
704 * removed and immediately readded don't stay modal, they become normal.
705 *
706 * @param {!Array<!HTMLDialogElement>} removed that have definitely been removed
707 */
708 dialogPolyfill.DialogManager.prototype.checkDOM_ = function(removed) {
709 // This operates on a clone because it may cause it to change. Each change also calls
710 // updateStacking, which only actually needs to happen once. But who removes many modal dialogs
711 // at a time?!
712 var clone = this.pendingDialogStack.slice();
713 clone.forEach(function(dpi) {
714 if (removed.indexOf(dpi.dialog) !== -1) {
715 dpi.downgradeModal();
716 } else {
717 dpi.maybeHideModal();
718 }
719 });
720 };
721
722 /**
723 * @param {!dialogPolyfillInfo} dpi
724 * @return {boolean} whether the dialog was allowed
725 */
726 dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) {
727 var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1;
728 if (this.pendingDialogStack.length >= allowed) {
729 return false;
730 }
731 if (this.pendingDialogStack.unshift(dpi) === 1) {
732 this.blockDocument();
733 }
734 this.updateStacking();
735 return true;
736 };
737
738 /**
739 * @param {!dialogPolyfillInfo} dpi
740 */
741 dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) {
742 var index = this.pendingDialogStack.indexOf(dpi);
743 if (index === -1) { return; }
744
745 this.pendingDialogStack.splice(index, 1);
746 if (this.pendingDialogStack.length === 0) {
747 this.unblockDocument();
748 }
749 this.updateStacking();
750 };
751
752 dialogPolyfill.dm = new dialogPolyfill.DialogManager();
753 dialogPolyfill.formSubmitter = null;
754 dialogPolyfill.useValue = null;
755
756 /**
757 * Installs global handlers, such as click listers and native method overrides. These are needed
758 * even if a no dialog is registered, as they deal with <form method="dialog">.
759 */
760 if (window.HTMLDialogElement === undefined) {
761
762 /**
763 * If HTMLFormElement translates method="DIALOG" into 'get', then replace the descriptor with
764 * one that returns the correct value.
765 */
766 var testForm = document.createElement('form');
767 testForm.setAttribute('method', 'dialog');
768 if (testForm.method !== 'dialog') {
769 var methodDescriptor = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'method');
770 if (methodDescriptor) {
771 // nb. Some older iOS and older PhantomJS fail to return the descriptor. Don't do anything
772 // and don't bother to update the element.
773 var realGet = methodDescriptor.get;
774 methodDescriptor.get = function() {
775 if (isFormMethodDialog(this)) {
776 return 'dialog';
777 }
778 return realGet.call(this);
779 };
780 var realSet = methodDescriptor.set;
Renovate botf591dcf2023-12-30 14:13:54 +0000781 /** @this {HTMLElement} */
Copybara botbe50d492023-11-30 00:16:42 +0100782 methodDescriptor.set = function(v) {
783 if (typeof v === 'string' && v.toLowerCase() === 'dialog') {
784 return this.setAttribute('method', v);
785 }
786 return realSet.call(this, v);
787 };
788 Object.defineProperty(HTMLFormElement.prototype, 'method', methodDescriptor);
789 }
790 }
791
792 /**
793 * Global 'click' handler, to capture the <input type="submit"> or <button> element which has
794 * submitted a <form method="dialog">. Needed as Safari and others don't report this inside
795 * document.activeElement.
796 */
797 document.addEventListener('click', function(ev) {
798 dialogPolyfill.formSubmitter = null;
799 dialogPolyfill.useValue = null;
800 if (ev.defaultPrevented) { return; } // e.g. a submit which prevents default submission
801
802 var target = /** @type {Element} */ (ev.target);
Renovate botf591dcf2023-12-30 14:13:54 +0000803 if ('composedPath' in ev) {
804 var path = ev.composedPath();
805 target = path.shift() || target;
806 }
Copybara botbe50d492023-11-30 00:16:42 +0100807 if (!target || !isFormMethodDialog(target.form)) { return; }
808
809 var valid = (target.type === 'submit' && ['button', 'input'].indexOf(target.localName) > -1);
810 if (!valid) {
811 if (!(target.localName === 'input' && target.type === 'image')) { return; }
812 // this is a <input type="image">, which can submit forms
813 dialogPolyfill.useValue = ev.offsetX + ',' + ev.offsetY;
814 }
815
816 var dialog = findNearestDialog(target);
817 if (!dialog) { return; }
818
819 dialogPolyfill.formSubmitter = target;
820
821 }, false);
822
823 /**
Renovate botf591dcf2023-12-30 14:13:54 +0000824 * Global 'submit' handler. This handles submits of `method="dialog"` which are invalid, i.e.,
825 * outside a dialog. They get prevented.
826 */
827 document.addEventListener('submit', function(ev) {
828 var form = ev.target;
829 var dialog = findNearestDialog(form);
830 if (dialog) {
831 return; // ignore, handle there
832 }
833
834 var submitter = findFormSubmitter(ev);
835 var formmethod = submitter && submitter.getAttribute('formmethod') || form.getAttribute('method');
836 if (formmethod === 'dialog') {
837 ev.preventDefault();
838 }
839 });
840
841 /**
Copybara botbe50d492023-11-30 00:16:42 +0100842 * Replace the native HTMLFormElement.submit() method, as it won't fire the
843 * submit event and give us a chance to respond.
844 */
845 var nativeFormSubmit = HTMLFormElement.prototype.submit;
846 var replacementFormSubmit = function () {
847 if (!isFormMethodDialog(this)) {
848 return nativeFormSubmit.call(this);
849 }
850 var dialog = findNearestDialog(this);
851 dialog && dialog.close();
852 };
853 HTMLFormElement.prototype.submit = replacementFormSubmit;
Copybara botbe50d492023-11-30 00:16:42 +0100854 }
855
856 return dialogPolyfill;
857
858}));