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