3 // nb. This is for IE10 and lower _only_.
4 var supportCustomEvent = window.CustomEvent;
5 if (!supportCustomEvent || typeof supportCustomEvent === 'object') {
6 supportCustomEvent = function CustomEvent(event, x) {
8 var ev = document.createEvent('CustomEvent');
9 ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null);
12 supportCustomEvent.prototype = window.Event.prototype;
16 * @param {Element} el to check for stacking context
17 * @return {boolean} whether this el or its parents creates a stacking context
19 function createsStackingContext(el) {
20 while (el && el !== document.body) {
21 var s = window.getComputedStyle(el);
22 var invalid = function(k, ok) {
23 return !(s[k] === undefined || s[k] === ok);
26 invalid('zIndex', 'auto') ||
27 invalid('transform', 'none') ||
28 invalid('mixBlendMode', 'normal') ||
29 invalid('filter', 'none') ||
30 invalid('perspective', 'none') ||
31 s['isolation'] === 'isolate' ||
32 s.position === 'fixed' ||
33 s.webkitOverflowScrolling === 'touch') {
36 el = el.parentElement;
42 * Finds the nearest <dialog> from the passed element.
44 * @param {Element} el to search from
45 * @return {HTMLDialogElement} dialog found
47 function findNearestDialog(el) {
49 if (el.localName === 'dialog') {
50 return /** @type {HTMLDialogElement} */ (el);
52 el = el.parentElement;
58 * Blur the specified element, as long as it's not the HTML body element.
59 * This works around an IE9/10 bug - blurring the body causes Windows to
60 * blur the whole application.
62 * @param {Element} el to blur
64 function safeBlur(el) {
65 if (el && el.blur && el !== document.body) {
71 * @param {!NodeList} nodeList to search
72 * @param {Node} node to find
73 * @return {boolean} whether node is inside nodeList
75 function inNodeList(nodeList, node) {
76 for (var i = 0; i < nodeList.length; ++i) {
77 if (nodeList[i] === node) {
85 * @param {HTMLFormElement} el to check
86 * @return {boolean} whether this form has method="dialog"
88 function isFormMethodDialog(el) {
89 if (!el || !el.hasAttribute('method')) {
92 return el.getAttribute('method').toLowerCase() === 'dialog';
96 * @param {!HTMLDialogElement} dialog to upgrade
99 function dialogPolyfillInfo(dialog) {
100 this.dialog_ = dialog;
101 this.replacedStyleTop_ = false;
102 this.openAsModal_ = false;
104 // Set a11y role. Browsers that support dialog implicitly know this already.
105 if (!dialog.hasAttribute('role')) {
106 dialog.setAttribute('role', 'dialog');
109 dialog.show = this.show.bind(this);
110 dialog.showModal = this.showModal.bind(this);
111 dialog.close = this.close.bind(this);
113 if (!('returnValue' in dialog)) {
114 dialog.returnValue = '';
117 if ('MutationObserver' in window) {
118 var mo = new MutationObserver(this.maybeHideModal.bind(this));
119 mo.observe(dialog, {attributes: true, attributeFilter: ['open']});
121 // IE10 and below support. Note that DOMNodeRemoved etc fire _before_ removal. They also
122 // seem to fire even if the element was removed as part of a parent removal. Use the removed
123 // events to force downgrade (useful if removed/immediately added).
125 var cb = function() {
126 removed ? this.downgradeModal() : this.maybeHideModal();
130 var delayModel = function(ev) {
131 if (ev.target !== dialog) { return; } // not for a child element
132 var cand = 'DOMNodeRemoved';
133 removed |= (ev.type.substr(0, cand.length) === cand);
134 window.clearTimeout(timeout);
135 timeout = window.setTimeout(cb, 0);
137 ['DOMAttrModified', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument'].forEach(function(name) {
138 dialog.addEventListener(name, delayModel);
141 // Note that the DOM is observed inside DialogManager while any dialog
142 // is being displayed as a modal, to catch modal removal from the DOM.
144 Object.defineProperty(dialog, 'open', {
145 set: this.setOpen.bind(this),
146 get: dialog.hasAttribute.bind(dialog, 'open')
149 this.backdrop_ = document.createElement('div');
150 this.backdrop_.className = 'backdrop';
151 this.backdrop_.addEventListener('click', this.backdropClick_.bind(this));
154 dialogPolyfillInfo.prototype = {
161 * Maybe remove this dialog from the modal top layer. This is called when
162 * a modal dialog may no longer be tenable, e.g., when the dialog is no
163 * longer open or is no longer part of the DOM.
165 maybeHideModal: function() {
166 if (this.dialog_.hasAttribute('open') && document.body.contains(this.dialog_)) { return; }
167 this.downgradeModal();
171 * Remove this dialog from the modal top layer, leaving it as a non-modal.
173 downgradeModal: function() {
174 if (!this.openAsModal_) { return; }
175 this.openAsModal_ = false;
176 this.dialog_.style.zIndex = '';
178 // This won't match the native <dialog> exactly because if the user set top on a centered
179 // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's
180 // possible to polyfill this perfectly.
181 if (this.replacedStyleTop_) {
182 this.dialog_.style.top = '';
183 this.replacedStyleTop_ = false;
186 // Clear the backdrop and remove from the manager.
187 this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_);
188 dialogPolyfill.dm.removeDialog(this);
192 * @param {boolean} value whether to open or close this dialog
194 setOpen: function(value) {
196 this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', '');
198 this.dialog_.removeAttribute('open');
199 this.maybeHideModal(); // nb. redundant with MutationObserver
204 * Handles clicks on the fake .backdrop element, redirecting them as if
205 * they were on the dialog itself.
207 * @param {!Event} e to redirect
209 backdropClick_: function(e) {
210 if (!this.dialog_.hasAttribute('tabindex')) {
211 // Clicking on the backdrop should move the implicit cursor, even if dialog cannot be
212 // focused. Create a fake thing to focus on. If the backdrop was _before_ the dialog, this
213 // would not be needed - clicks would move the implicit cursor there.
214 var fake = document.createElement('div');
215 this.dialog_.insertBefore(fake, this.dialog_.firstChild);
218 this.dialog_.removeChild(fake);
220 this.dialog_.focus();
223 var redirectedEvent = document.createEvent('MouseEvents');
224 redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window,
225 e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey,
226 e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget);
227 this.dialog_.dispatchEvent(redirectedEvent);
232 * Focuses on the first focusable element within the dialog. This will always blur the current
233 * focus, even if nothing within the dialog is found.
236 // Find element with `autofocus` attribute, or fall back to the first form/tabindex control.
237 var target = this.dialog_.querySelector('[autofocus]:not([disabled])');
238 if (!target && this.dialog_.tabIndex >= 0) {
239 target = this.dialog_;
242 // Note that this is 'any focusable area'. This list is probably not exhaustive, but the
243 // alternative involves stepping through and trying to focus everything.
244 var opts = ['button', 'input', 'keygen', 'select', 'textarea'];
245 var query = opts.map(function(el) {
246 return el + ':not([disabled])';
248 // TODO(samthor): tabindex values that are not numeric are not focusable.
249 query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled
250 target = this.dialog_.querySelector(query.join(', '));
252 safeBlur(document.activeElement);
253 target && target.focus();
257 * Sets the zIndex for the backdrop and dialog.
259 * @param {number} dialogZ
260 * @param {number} backdropZ
262 updateZIndex: function(dialogZ, backdropZ) {
263 if (dialogZ < backdropZ) {
264 throw new Error('dialogZ should never be < backdropZ');
266 this.dialog_.style.zIndex = dialogZ;
267 this.backdrop_.style.zIndex = backdropZ;
271 * Shows the dialog. If the dialog is already open, this does nothing.
274 if (!this.dialog_.open) {
281 * Show this dialog modally.
283 showModal: function() {
284 if (this.dialog_.hasAttribute('open')) {
285 throw new Error('Failed to execute \'showModal\' on dialog: The element is already open, and therefore cannot be opened modally.');
287 if (!document.body.contains(this.dialog_)) {
288 throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.');
290 if (!dialogPolyfill.dm.pushDialog(this)) {
291 throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.');
294 if (createsStackingContext(this.dialog_.parentElement)) {
295 console.warn('A dialog is being shown inside a stacking context. ' +
296 'This may cause it to be unusable. For more information, see this link: ' +
297 'https://github.com/GoogleChrome/dialog-polyfill/#stacking-context');
301 this.openAsModal_ = true;
303 // Optionally center vertically, relative to the current viewport.
304 if (dialogPolyfill.needsCentering(this.dialog_)) {
305 dialogPolyfill.reposition(this.dialog_);
306 this.replacedStyleTop_ = true;
308 this.replacedStyleTop_ = false;
312 this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling);
314 // Focus on whatever inside the dialog.
319 * Closes this HTMLDialogElement. This is optional vs clearing the open
320 * attribute, however this fires a 'close' event.
322 * @param {string=} opt_returnValue to use as the returnValue
324 close: function(opt_returnValue) {
325 if (!this.dialog_.hasAttribute('open')) {
326 throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.');
330 // Leave returnValue untouched in case it was set directly on the element
331 if (opt_returnValue !== undefined) {
332 this.dialog_.returnValue = opt_returnValue;
335 // Triggering "close" event for any attached listeners on the <dialog>.
336 var closeEvent = new supportCustomEvent('close', {
340 this.dialog_.dispatchEvent(closeEvent);
345 var dialogPolyfill = {};
347 dialogPolyfill.reposition = function(element) {
348 var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
349 var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2;
350 element.style.top = Math.max(scrollTop, topValue) + 'px';
353 dialogPolyfill.isInlinePositionSetByStylesheet = function(element) {
354 for (var i = 0; i < document.styleSheets.length; ++i) {
355 var styleSheet = document.styleSheets[i];
357 // Some browsers throw on cssRules.
359 cssRules = styleSheet.cssRules;
361 if (!cssRules) { continue; }
362 for (var j = 0; j < cssRules.length; ++j) {
363 var rule = cssRules[j];
364 var selectedNodes = null;
365 // Ignore errors on invalid selector texts.
367 selectedNodes = document.querySelectorAll(rule.selectorText);
369 if (!selectedNodes || !inNodeList(selectedNodes, element)) {
372 var cssTop = rule.style.getPropertyValue('top');
373 var cssBottom = rule.style.getPropertyValue('bottom');
374 if ((cssTop && cssTop !== 'auto') || (cssBottom && cssBottom !== 'auto')) {
382 dialogPolyfill.needsCentering = function(dialog) {
383 var computedStyle = window.getComputedStyle(dialog);
384 if (computedStyle.position !== 'absolute') {
388 // We must determine whether the top/bottom specified value is non-auto. In
389 // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but
390 // Firefox returns the used value. So we do this crazy thing instead: check
391 // the inline style and then go through CSS rules.
392 if ((dialog.style.top !== 'auto' && dialog.style.top !== '') ||
393 (dialog.style.bottom !== 'auto' && dialog.style.bottom !== '')) {
396 return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog);
400 * @param {!Element} element to force upgrade
402 dialogPolyfill.forceRegisterDialog = function(element) {
403 if (window.HTMLDialogElement || element.showModal) {
404 console.warn('This browser already supports <dialog>, the polyfill ' +
405 'may not work correctly', element);
407 if (element.localName !== 'dialog') {
408 throw new Error('Failed to register dialog: The element is not a dialog.');
410 new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element));
414 * @param {!Element} element to upgrade, if necessary
416 dialogPolyfill.registerDialog = function(element) {
417 if (!element.showModal) {
418 dialogPolyfill.forceRegisterDialog(element);
425 dialogPolyfill.DialogManager = function() {
426 /** @type {!Array<!dialogPolyfillInfo>} */
427 this.pendingDialogStack = [];
429 var checkDOM = this.checkDOM_.bind(this);
431 // The overlay is used to simulate how a modal dialog blocks the document.
432 // The blocking dialog is positioned on top of the overlay, and the rest of
433 // the dialogs on the pending dialog stack are positioned below it. In the
434 // actual implementation, the modal dialog stacking is controlled by the
435 // top layer, where z-index has no effect.
436 this.overlay = document.createElement('div');
437 this.overlay.className = '_dialog_overlay';
438 this.overlay.addEventListener('click', function(e) {
439 this.forwardTab_ = undefined;
441 checkDOM([]); // sanity-check DOM
444 this.handleKey_ = this.handleKey_.bind(this);
445 this.handleFocus_ = this.handleFocus_.bind(this);
447 this.zIndexLow_ = 100000;
448 this.zIndexHigh_ = 100000 + 150;
450 this.forwardTab_ = undefined;
452 if ('MutationObserver' in window) {
453 this.mo_ = new MutationObserver(function(records) {
455 records.forEach(function(rec) {
456 for (var i = 0, c; c = rec.removedNodes[i]; ++i) {
457 if (!(c instanceof Element)) {
459 } else if (c.localName === 'dialog') {
462 removed = removed.concat(c.querySelectorAll('dialog'));
465 removed.length && checkDOM(removed);
471 * Called on the first modal dialog being shown. Adds the overlay and related
474 dialogPolyfill.DialogManager.prototype.blockDocument = function() {
475 document.documentElement.addEventListener('focus', this.handleFocus_, true);
476 document.addEventListener('keydown', this.handleKey_);
477 this.mo_ && this.mo_.observe(document, {childList: true, subtree: true});
481 * Called on the first modal dialog being removed, i.e., when no more modal
482 * dialogs are visible.
484 dialogPolyfill.DialogManager.prototype.unblockDocument = function() {
485 document.documentElement.removeEventListener('focus', this.handleFocus_, true);
486 document.removeEventListener('keydown', this.handleKey_);
487 this.mo_ && this.mo_.disconnect();
491 * Updates the stacking of all known dialogs.
493 dialogPolyfill.DialogManager.prototype.updateStacking = function() {
494 var zIndex = this.zIndexHigh_;
496 for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
497 dpi.updateZIndex(--zIndex, --zIndex);
499 this.overlay.style.zIndex = --zIndex;
503 // Make the overlay a sibling of the dialog itself.
504 var last = this.pendingDialogStack[0];
506 var p = last.dialog.parentNode || document.body;
507 p.appendChild(this.overlay);
508 } else if (this.overlay.parentNode) {
509 this.overlay.parentNode.removeChild(this.overlay);
514 * @param {Element} candidate to check if contained or is the top-most modal dialog
515 * @return {boolean} whether candidate is contained in top dialog
517 dialogPolyfill.DialogManager.prototype.containedByTopDialog_ = function(candidate) {
518 while (candidate = findNearestDialog(candidate)) {
519 for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) {
520 if (dpi.dialog === candidate) {
521 return i === 0; // only valid if top-most
524 candidate = candidate.parentElement;
529 dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) {
530 if (this.containedByTopDialog_(event.target)) { return; }
532 event.preventDefault();
533 event.stopPropagation();
534 safeBlur(/** @type {Element} */ (event.target));
536 if (this.forwardTab_ === undefined) { return; } // move focus only from a tab key
538 var dpi = this.pendingDialogStack[0];
539 var dialog = dpi.dialog;
540 var position = dialog.compareDocumentPosition(event.target);
541 if (position & Node.DOCUMENT_POSITION_PRECEDING) {
542 if (this.forwardTab_) { // forward
544 } else { // backwards
545 document.documentElement.focus();
548 // TODO: Focus after the dialog, is ignored.
554 dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) {
555 this.forwardTab_ = undefined;
556 if (event.keyCode === 27) {
557 event.preventDefault();
558 event.stopPropagation();
559 var cancelEvent = new supportCustomEvent('cancel', {
563 var dpi = this.pendingDialogStack[0];
564 if (dpi && dpi.dialog.dispatchEvent(cancelEvent)) {
567 } else if (event.keyCode === 9) {
568 this.forwardTab_ = !event.shiftKey;
573 * Finds and downgrades any known modal dialogs that are no longer displayed. Dialogs that are
574 * removed and immediately readded don't stay modal, they become normal.
576 * @param {!Array<!HTMLDialogElement>} removed that have definitely been removed
578 dialogPolyfill.DialogManager.prototype.checkDOM_ = function(removed) {
579 // This operates on a clone because it may cause it to change. Each change also calls
580 // updateStacking, which only actually needs to happen once. But who removes many modal dialogs
582 var clone = this.pendingDialogStack.slice();
583 clone.forEach(function(dpi) {
584 if (removed.indexOf(dpi.dialog) !== -1) {
585 dpi.downgradeModal();
587 dpi.maybeHideModal();
593 * @param {!dialogPolyfillInfo} dpi
594 * @return {boolean} whether the dialog was allowed
596 dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) {
597 var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1;
598 if (this.pendingDialogStack.length >= allowed) {
601 if (this.pendingDialogStack.unshift(dpi) === 1) {
602 this.blockDocument();
604 this.updateStacking();
609 * @param {!dialogPolyfillInfo} dpi
611 dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) {
612 var index = this.pendingDialogStack.indexOf(dpi);
613 if (index === -1) { return; }
615 this.pendingDialogStack.splice(index, 1);
616 if (this.pendingDialogStack.length === 0) {
617 this.unblockDocument();
619 this.updateStacking();
622 dialogPolyfill.dm = new dialogPolyfill.DialogManager();
623 dialogPolyfill.formSubmitter = null;
624 dialogPolyfill.useValue = null;
627 * Installs global handlers, such as click listers and native method overrides. These are needed
628 * even if a no dialog is registered, as they deal with <form method="dialog">.
630 if (window.HTMLDialogElement === undefined) {
633 * If HTMLFormElement translates method="DIALOG" into 'get', then replace the descriptor with
634 * one that returns the correct value.
636 var testForm = document.createElement('form');
637 testForm.setAttribute('method', 'dialog');
638 if (testForm.method !== 'dialog') {
639 var methodDescriptor = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'method');
640 if (methodDescriptor) {
641 // nb. Some older iOS and older PhantomJS fail to return the descriptor. Don't do anything
642 // and don't bother to update the element.
643 var realGet = methodDescriptor.get;
644 methodDescriptor.get = function() {
645 if (isFormMethodDialog(this)) {
648 return realGet.call(this);
650 var realSet = methodDescriptor.set;
651 methodDescriptor.set = function(v) {
652 if (typeof v === 'string' && v.toLowerCase() === 'dialog') {
653 return this.setAttribute('method', v);
655 return realSet.call(this, v);
657 Object.defineProperty(HTMLFormElement.prototype, 'method', methodDescriptor);
662 * Global 'click' handler, to capture the <input type="submit"> or <button> element which has
663 * submitted a <form method="dialog">. Needed as Safari and others don't report this inside
664 * document.activeElement.
666 document.addEventListener('click', function(ev) {
667 dialogPolyfill.formSubmitter = null;
668 dialogPolyfill.useValue = null;
669 if (ev.defaultPrevented) { return; } // e.g. a submit which prevents default submission
671 var target = /** @type {Element} */ (ev.target);
672 if (!target || !isFormMethodDialog(target.form)) { return; }
674 var valid = (target.type === 'submit' && ['button', 'input'].indexOf(target.localName) > -1);
676 if (!(target.localName === 'input' && target.type === 'image')) { return; }
677 // this is a <input type="image">, which can submit forms
678 dialogPolyfill.useValue = ev.offsetX + ',' + ev.offsetY;
681 var dialog = findNearestDialog(target);
682 if (!dialog) { return; }
684 dialogPolyfill.formSubmitter = target;
688 * Replace the native HTMLFormElement.submit() method, as it won't fire the
689 * submit event and give us a chance to respond.
691 var nativeFormSubmit = HTMLFormElement.prototype.submit;
692 var replacementFormSubmit = function () {
693 if (!isFormMethodDialog(this)) {
694 return nativeFormSubmit.call(this);
696 var dialog = findNearestDialog(this);
697 dialog && dialog.close();
699 HTMLFormElement.prototype.submit = replacementFormSubmit;
702 * Global form 'dialog' method handler. Closes a dialog correctly on submit
703 * and possibly sets its return value.
705 document.addEventListener('submit', function(ev) {
706 var form = /** @type {HTMLFormElement} */ (ev.target);
707 if (!isFormMethodDialog(form)) { return; }
710 var dialog = findNearestDialog(form);
711 if (!dialog) { return; }
713 // Forms can only be submitted via .submit() or a click (?), but anyway: sanity-check that
714 // the submitter is correct before using its value as .returnValue.
715 var s = dialogPolyfill.formSubmitter;
716 if (s && s.form === form) {
717 dialog.close(dialogPolyfill.useValue || s.value);
721 dialogPolyfill.formSubmitter = null;
725 dialogPolyfill['forceRegisterDialog'] = dialogPolyfill.forceRegisterDialog;
726 dialogPolyfill['registerDialog'] = dialogPolyfill.registerDialog;
728 if (typeof define === 'function' && 'amd' in define) {
730 define(function() { return dialogPolyfill; });
731 } else if (typeof module === 'object' && typeof module['exports'] === 'object') {
733 module['exports'] = dialogPolyfill;
736 window['dialogPolyfill'] = dialogPolyfill;