Copybara bot | be50d49 | 2023-11-30 00:16:42 +0100 | [diff] [blame] | 1 | |
| 2 | // nb. This is for IE10 and lower _only_. |
| 3 | var supportCustomEvent = window.CustomEvent; |
| 4 | if (!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 | /** |
| 15 | * @param {Element} el to check for stacking context |
| 16 | * @return {boolean} whether this el or its parents creates a stacking context |
| 17 | */ |
| 18 | function createsStackingContext(el) { |
| 19 | while (el && el !== document.body) { |
| 20 | var s = window.getComputedStyle(el); |
| 21 | var invalid = function(k, ok) { |
| 22 | return !(s[k] === undefined || s[k] === ok); |
| 23 | }; |
| 24 | |
| 25 | if (s.opacity < 1 || |
| 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') { |
| 34 | return true; |
| 35 | } |
| 36 | el = el.parentElement; |
| 37 | } |
| 38 | return false; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Finds the nearest <dialog> from the passed element. |
| 43 | * |
| 44 | * @param {Element} el to search from |
| 45 | * @return {HTMLDialogElement} dialog found |
| 46 | */ |
| 47 | function findNearestDialog(el) { |
| 48 | while (el) { |
| 49 | if (el.localName === 'dialog') { |
| 50 | return /** @type {HTMLDialogElement} */ (el); |
| 51 | } |
| 52 | el = el.parentElement; |
| 53 | } |
| 54 | return null; |
| 55 | } |
| 56 | |
| 57 | /** |
| 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. |
| 61 | * |
| 62 | * @param {Element} el to blur |
| 63 | */ |
| 64 | function safeBlur(el) { |
| 65 | if (el && el.blur && el !== document.body) { |
| 66 | el.blur(); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * @param {!NodeList} nodeList to search |
| 72 | * @param {Node} node to find |
| 73 | * @return {boolean} whether node is inside nodeList |
| 74 | */ |
| 75 | function inNodeList(nodeList, node) { |
| 76 | for (var i = 0; i < nodeList.length; ++i) { |
| 77 | if (nodeList[i] === node) { |
| 78 | return true; |
| 79 | } |
| 80 | } |
| 81 | return false; |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * @param {HTMLFormElement} el to check |
| 86 | * @return {boolean} whether this form has method="dialog" |
| 87 | */ |
| 88 | function isFormMethodDialog(el) { |
| 89 | if (!el || !el.hasAttribute('method')) { |
| 90 | return false; |
| 91 | } |
| 92 | return el.getAttribute('method').toLowerCase() === 'dialog'; |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * @param {!HTMLDialogElement} dialog to upgrade |
| 97 | * @constructor |
| 98 | */ |
| 99 | function dialogPolyfillInfo(dialog) { |
| 100 | this.dialog_ = dialog; |
| 101 | this.replacedStyleTop_ = false; |
| 102 | this.openAsModal_ = false; |
| 103 | |
| 104 | // Set a11y role. Browsers that support dialog implicitly know this already. |
| 105 | if (!dialog.hasAttribute('role')) { |
| 106 | dialog.setAttribute('role', 'dialog'); |
| 107 | } |
| 108 | |
| 109 | dialog.show = this.show.bind(this); |
| 110 | dialog.showModal = this.showModal.bind(this); |
| 111 | dialog.close = this.close.bind(this); |
| 112 | |
| 113 | if (!('returnValue' in dialog)) { |
| 114 | dialog.returnValue = ''; |
| 115 | } |
| 116 | |
| 117 | if ('MutationObserver' in window) { |
| 118 | var mo = new MutationObserver(this.maybeHideModal.bind(this)); |
| 119 | mo.observe(dialog, {attributes: true, attributeFilter: ['open']}); |
| 120 | } else { |
| 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). |
| 124 | var removed = false; |
| 125 | var cb = function() { |
| 126 | removed ? this.downgradeModal() : this.maybeHideModal(); |
| 127 | removed = false; |
| 128 | }.bind(this); |
| 129 | var timeout; |
| 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); |
| 136 | }; |
| 137 | ['DOMAttrModified', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument'].forEach(function(name) { |
| 138 | dialog.addEventListener(name, delayModel); |
| 139 | }); |
| 140 | } |
| 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. |
| 143 | |
| 144 | Object.defineProperty(dialog, 'open', { |
| 145 | set: this.setOpen.bind(this), |
| 146 | get: dialog.hasAttribute.bind(dialog, 'open') |
| 147 | }); |
| 148 | |
| 149 | this.backdrop_ = document.createElement('div'); |
| 150 | this.backdrop_.className = 'backdrop'; |
| 151 | this.backdrop_.addEventListener('click', this.backdropClick_.bind(this)); |
| 152 | } |
| 153 | |
| 154 | dialogPolyfillInfo.prototype = { |
| 155 | |
| 156 | get dialog() { |
| 157 | return this.dialog_; |
| 158 | }, |
| 159 | |
| 160 | /** |
| 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. |
| 164 | */ |
| 165 | maybeHideModal: function() { |
| 166 | if (this.dialog_.hasAttribute('open') && document.body.contains(this.dialog_)) { return; } |
| 167 | this.downgradeModal(); |
| 168 | }, |
| 169 | |
| 170 | /** |
| 171 | * Remove this dialog from the modal top layer, leaving it as a non-modal. |
| 172 | */ |
| 173 | downgradeModal: function() { |
| 174 | if (!this.openAsModal_) { return; } |
| 175 | this.openAsModal_ = false; |
| 176 | this.dialog_.style.zIndex = ''; |
| 177 | |
| 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; |
| 184 | } |
| 185 | |
| 186 | // Clear the backdrop and remove from the manager. |
| 187 | this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_); |
| 188 | dialogPolyfill.dm.removeDialog(this); |
| 189 | }, |
| 190 | |
| 191 | /** |
| 192 | * @param {boolean} value whether to open or close this dialog |
| 193 | */ |
| 194 | setOpen: function(value) { |
| 195 | if (value) { |
| 196 | this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', ''); |
| 197 | } else { |
| 198 | this.dialog_.removeAttribute('open'); |
| 199 | this.maybeHideModal(); // nb. redundant with MutationObserver |
| 200 | } |
| 201 | }, |
| 202 | |
| 203 | /** |
| 204 | * Handles clicks on the fake .backdrop element, redirecting them as if |
| 205 | * they were on the dialog itself. |
| 206 | * |
| 207 | * @param {!Event} e to redirect |
| 208 | */ |
| 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); |
| 216 | fake.tabIndex = -1; |
| 217 | fake.focus(); |
| 218 | this.dialog_.removeChild(fake); |
| 219 | } else { |
| 220 | this.dialog_.focus(); |
| 221 | } |
| 222 | |
| 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); |
| 228 | e.stopPropagation(); |
| 229 | }, |
| 230 | |
| 231 | /** |
| 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. |
| 234 | */ |
| 235 | focus_: function() { |
| 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_; |
| 240 | } |
| 241 | if (!target) { |
| 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])'; |
| 247 | }); |
| 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(', ')); |
| 251 | } |
| 252 | safeBlur(document.activeElement); |
| 253 | target && target.focus(); |
| 254 | }, |
| 255 | |
| 256 | /** |
| 257 | * Sets the zIndex for the backdrop and dialog. |
| 258 | * |
| 259 | * @param {number} dialogZ |
| 260 | * @param {number} backdropZ |
| 261 | */ |
| 262 | updateZIndex: function(dialogZ, backdropZ) { |
| 263 | if (dialogZ < backdropZ) { |
| 264 | throw new Error('dialogZ should never be < backdropZ'); |
| 265 | } |
| 266 | this.dialog_.style.zIndex = dialogZ; |
| 267 | this.backdrop_.style.zIndex = backdropZ; |
| 268 | }, |
| 269 | |
| 270 | /** |
| 271 | * Shows the dialog. If the dialog is already open, this does nothing. |
| 272 | */ |
| 273 | show: function() { |
| 274 | if (!this.dialog_.open) { |
| 275 | this.setOpen(true); |
| 276 | this.focus_(); |
| 277 | } |
| 278 | }, |
| 279 | |
| 280 | /** |
| 281 | * Show this dialog modally. |
| 282 | */ |
| 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.'); |
| 286 | } |
| 287 | if (!document.body.contains(this.dialog_)) { |
| 288 | throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.'); |
| 289 | } |
| 290 | if (!dialogPolyfill.dm.pushDialog(this)) { |
| 291 | throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.'); |
| 292 | } |
| 293 | |
| 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'); |
| 298 | } |
| 299 | |
| 300 | this.setOpen(true); |
| 301 | this.openAsModal_ = true; |
| 302 | |
| 303 | // Optionally center vertically, relative to the current viewport. |
| 304 | if (dialogPolyfill.needsCentering(this.dialog_)) { |
| 305 | dialogPolyfill.reposition(this.dialog_); |
| 306 | this.replacedStyleTop_ = true; |
| 307 | } else { |
| 308 | this.replacedStyleTop_ = false; |
| 309 | } |
| 310 | |
| 311 | // Insert backdrop. |
| 312 | this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling); |
| 313 | |
| 314 | // Focus on whatever inside the dialog. |
| 315 | this.focus_(); |
| 316 | }, |
| 317 | |
| 318 | /** |
| 319 | * Closes this HTMLDialogElement. This is optional vs clearing the open |
| 320 | * attribute, however this fires a 'close' event. |
| 321 | * |
| 322 | * @param {string=} opt_returnValue to use as the returnValue |
| 323 | */ |
| 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.'); |
| 327 | } |
| 328 | this.setOpen(false); |
| 329 | |
| 330 | // Leave returnValue untouched in case it was set directly on the element |
| 331 | if (opt_returnValue !== undefined) { |
| 332 | this.dialog_.returnValue = opt_returnValue; |
| 333 | } |
| 334 | |
| 335 | // Triggering "close" event for any attached listeners on the <dialog>. |
| 336 | var closeEvent = new supportCustomEvent('close', { |
| 337 | bubbles: false, |
| 338 | cancelable: false |
| 339 | }); |
| 340 | this.dialog_.dispatchEvent(closeEvent); |
| 341 | } |
| 342 | |
| 343 | }; |
| 344 | |
| 345 | var dialogPolyfill = {}; |
| 346 | |
| 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'; |
| 351 | }; |
| 352 | |
| 353 | dialogPolyfill.isInlinePositionSetByStylesheet = function(element) { |
| 354 | for (var i = 0; i < document.styleSheets.length; ++i) { |
| 355 | var styleSheet = document.styleSheets[i]; |
| 356 | var cssRules = null; |
| 357 | // Some browsers throw on cssRules. |
| 358 | try { |
| 359 | cssRules = styleSheet.cssRules; |
| 360 | } catch (e) {} |
| 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. |
| 366 | try { |
| 367 | selectedNodes = document.querySelectorAll(rule.selectorText); |
| 368 | } catch(e) {} |
| 369 | if (!selectedNodes || !inNodeList(selectedNodes, element)) { |
| 370 | continue; |
| 371 | } |
| 372 | var cssTop = rule.style.getPropertyValue('top'); |
| 373 | var cssBottom = rule.style.getPropertyValue('bottom'); |
| 374 | if ((cssTop && cssTop !== 'auto') || (cssBottom && cssBottom !== 'auto')) { |
| 375 | return true; |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | return false; |
| 380 | }; |
| 381 | |
| 382 | dialogPolyfill.needsCentering = function(dialog) { |
| 383 | var computedStyle = window.getComputedStyle(dialog); |
| 384 | if (computedStyle.position !== 'absolute') { |
| 385 | return false; |
| 386 | } |
| 387 | |
| 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 !== '')) { |
| 394 | return false; |
| 395 | } |
| 396 | return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog); |
| 397 | }; |
| 398 | |
| 399 | /** |
| 400 | * @param {!Element} element to force upgrade |
| 401 | */ |
| 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); |
| 406 | } |
| 407 | if (element.localName !== 'dialog') { |
| 408 | throw new Error('Failed to register dialog: The element is not a dialog.'); |
| 409 | } |
| 410 | new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element)); |
| 411 | }; |
| 412 | |
| 413 | /** |
| 414 | * @param {!Element} element to upgrade, if necessary |
| 415 | */ |
| 416 | dialogPolyfill.registerDialog = function(element) { |
| 417 | if (!element.showModal) { |
| 418 | dialogPolyfill.forceRegisterDialog(element); |
| 419 | } |
| 420 | }; |
| 421 | |
| 422 | /** |
| 423 | * @constructor |
| 424 | */ |
| 425 | dialogPolyfill.DialogManager = function() { |
| 426 | /** @type {!Array<!dialogPolyfillInfo>} */ |
| 427 | this.pendingDialogStack = []; |
| 428 | |
| 429 | var checkDOM = this.checkDOM_.bind(this); |
| 430 | |
| 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; |
| 440 | e.stopPropagation(); |
| 441 | checkDOM([]); // sanity-check DOM |
| 442 | }.bind(this)); |
| 443 | |
| 444 | this.handleKey_ = this.handleKey_.bind(this); |
| 445 | this.handleFocus_ = this.handleFocus_.bind(this); |
| 446 | |
| 447 | this.zIndexLow_ = 100000; |
| 448 | this.zIndexHigh_ = 100000 + 150; |
| 449 | |
| 450 | this.forwardTab_ = undefined; |
| 451 | |
| 452 | if ('MutationObserver' in window) { |
| 453 | this.mo_ = new MutationObserver(function(records) { |
| 454 | var removed = []; |
| 455 | records.forEach(function(rec) { |
| 456 | for (var i = 0, c; c = rec.removedNodes[i]; ++i) { |
| 457 | if (!(c instanceof Element)) { |
| 458 | continue; |
| 459 | } else if (c.localName === 'dialog') { |
| 460 | removed.push(c); |
| 461 | } |
| 462 | removed = removed.concat(c.querySelectorAll('dialog')); |
| 463 | } |
| 464 | }); |
| 465 | removed.length && checkDOM(removed); |
| 466 | }); |
| 467 | } |
| 468 | }; |
| 469 | |
| 470 | /** |
| 471 | * Called on the first modal dialog being shown. Adds the overlay and related |
| 472 | * handlers. |
| 473 | */ |
| 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}); |
| 478 | }; |
| 479 | |
| 480 | /** |
| 481 | * Called on the first modal dialog being removed, i.e., when no more modal |
| 482 | * dialogs are visible. |
| 483 | */ |
| 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(); |
| 488 | }; |
| 489 | |
| 490 | /** |
| 491 | * Updates the stacking of all known dialogs. |
| 492 | */ |
| 493 | dialogPolyfill.DialogManager.prototype.updateStacking = function() { |
| 494 | var zIndex = this.zIndexHigh_; |
| 495 | |
| 496 | for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) { |
| 497 | dpi.updateZIndex(--zIndex, --zIndex); |
| 498 | if (i === 0) { |
| 499 | this.overlay.style.zIndex = --zIndex; |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | // Make the overlay a sibling of the dialog itself. |
| 504 | var last = this.pendingDialogStack[0]; |
| 505 | if (last) { |
| 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); |
| 510 | } |
| 511 | }; |
| 512 | |
| 513 | /** |
| 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 |
| 516 | */ |
| 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 |
| 522 | } |
| 523 | } |
| 524 | candidate = candidate.parentElement; |
| 525 | } |
| 526 | return false; |
| 527 | }; |
| 528 | |
| 529 | dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) { |
| 530 | if (this.containedByTopDialog_(event.target)) { return; } |
| 531 | |
| 532 | if (document.activeElement === document.documentElement) { return; } |
| 533 | |
| 534 | event.preventDefault(); |
| 535 | event.stopPropagation(); |
| 536 | safeBlur(/** @type {Element} */ (event.target)); |
| 537 | |
| 538 | if (this.forwardTab_ === undefined) { return; } // move focus only from a tab key |
| 539 | |
| 540 | var dpi = this.pendingDialogStack[0]; |
| 541 | var dialog = dpi.dialog; |
| 542 | var position = dialog.compareDocumentPosition(event.target); |
| 543 | if (position & Node.DOCUMENT_POSITION_PRECEDING) { |
| 544 | if (this.forwardTab_) { |
| 545 | // forward |
| 546 | dpi.focus_(); |
| 547 | } else if (event.target !== document.documentElement) { |
| 548 | // backwards if we're not already focused on <html> |
| 549 | document.documentElement.focus(); |
| 550 | } |
| 551 | } else { |
| 552 | // TODO: Focus after the dialog, is ignored. |
| 553 | } |
| 554 | |
| 555 | return false; |
| 556 | }; |
| 557 | |
| 558 | dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) { |
| 559 | this.forwardTab_ = undefined; |
| 560 | if (event.keyCode === 27) { |
| 561 | event.preventDefault(); |
| 562 | event.stopPropagation(); |
| 563 | var cancelEvent = new supportCustomEvent('cancel', { |
| 564 | bubbles: false, |
| 565 | cancelable: true |
| 566 | }); |
| 567 | var dpi = this.pendingDialogStack[0]; |
| 568 | if (dpi && dpi.dialog.dispatchEvent(cancelEvent)) { |
| 569 | dpi.dialog.close(); |
| 570 | } |
| 571 | } else if (event.keyCode === 9) { |
| 572 | this.forwardTab_ = !event.shiftKey; |
| 573 | } |
| 574 | }; |
| 575 | |
| 576 | /** |
| 577 | * Finds and downgrades any known modal dialogs that are no longer displayed. Dialogs that are |
| 578 | * removed and immediately readded don't stay modal, they become normal. |
| 579 | * |
| 580 | * @param {!Array<!HTMLDialogElement>} removed that have definitely been removed |
| 581 | */ |
| 582 | dialogPolyfill.DialogManager.prototype.checkDOM_ = function(removed) { |
| 583 | // This operates on a clone because it may cause it to change. Each change also calls |
| 584 | // updateStacking, which only actually needs to happen once. But who removes many modal dialogs |
| 585 | // at a time?! |
| 586 | var clone = this.pendingDialogStack.slice(); |
| 587 | clone.forEach(function(dpi) { |
| 588 | if (removed.indexOf(dpi.dialog) !== -1) { |
| 589 | dpi.downgradeModal(); |
| 590 | } else { |
| 591 | dpi.maybeHideModal(); |
| 592 | } |
| 593 | }); |
| 594 | }; |
| 595 | |
| 596 | /** |
| 597 | * @param {!dialogPolyfillInfo} dpi |
| 598 | * @return {boolean} whether the dialog was allowed |
| 599 | */ |
| 600 | dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) { |
| 601 | var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1; |
| 602 | if (this.pendingDialogStack.length >= allowed) { |
| 603 | return false; |
| 604 | } |
| 605 | if (this.pendingDialogStack.unshift(dpi) === 1) { |
| 606 | this.blockDocument(); |
| 607 | } |
| 608 | this.updateStacking(); |
| 609 | return true; |
| 610 | }; |
| 611 | |
| 612 | /** |
| 613 | * @param {!dialogPolyfillInfo} dpi |
| 614 | */ |
| 615 | dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) { |
| 616 | var index = this.pendingDialogStack.indexOf(dpi); |
| 617 | if (index === -1) { return; } |
| 618 | |
| 619 | this.pendingDialogStack.splice(index, 1); |
| 620 | if (this.pendingDialogStack.length === 0) { |
| 621 | this.unblockDocument(); |
| 622 | } |
| 623 | this.updateStacking(); |
| 624 | }; |
| 625 | |
| 626 | dialogPolyfill.dm = new dialogPolyfill.DialogManager(); |
| 627 | dialogPolyfill.formSubmitter = null; |
| 628 | dialogPolyfill.useValue = null; |
| 629 | |
| 630 | /** |
| 631 | * Installs global handlers, such as click listers and native method overrides. These are needed |
| 632 | * even if a no dialog is registered, as they deal with <form method="dialog">. |
| 633 | */ |
| 634 | if (window.HTMLDialogElement === undefined) { |
| 635 | |
| 636 | /** |
| 637 | * If HTMLFormElement translates method="DIALOG" into 'get', then replace the descriptor with |
| 638 | * one that returns the correct value. |
| 639 | */ |
| 640 | var testForm = document.createElement('form'); |
| 641 | testForm.setAttribute('method', 'dialog'); |
| 642 | if (testForm.method !== 'dialog') { |
| 643 | var methodDescriptor = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'method'); |
| 644 | if (methodDescriptor) { |
| 645 | // nb. Some older iOS and older PhantomJS fail to return the descriptor. Don't do anything |
| 646 | // and don't bother to update the element. |
| 647 | var realGet = methodDescriptor.get; |
| 648 | methodDescriptor.get = function() { |
| 649 | if (isFormMethodDialog(this)) { |
| 650 | return 'dialog'; |
| 651 | } |
| 652 | return realGet.call(this); |
| 653 | }; |
| 654 | var realSet = methodDescriptor.set; |
| 655 | methodDescriptor.set = function(v) { |
| 656 | if (typeof v === 'string' && v.toLowerCase() === 'dialog') { |
| 657 | return this.setAttribute('method', v); |
| 658 | } |
| 659 | return realSet.call(this, v); |
| 660 | }; |
| 661 | Object.defineProperty(HTMLFormElement.prototype, 'method', methodDescriptor); |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | /** |
| 666 | * Global 'click' handler, to capture the <input type="submit"> or <button> element which has |
| 667 | * submitted a <form method="dialog">. Needed as Safari and others don't report this inside |
| 668 | * document.activeElement. |
| 669 | */ |
| 670 | document.addEventListener('click', function(ev) { |
| 671 | dialogPolyfill.formSubmitter = null; |
| 672 | dialogPolyfill.useValue = null; |
| 673 | if (ev.defaultPrevented) { return; } // e.g. a submit which prevents default submission |
| 674 | |
| 675 | var target = /** @type {Element} */ (ev.target); |
| 676 | if (!target || !isFormMethodDialog(target.form)) { return; } |
| 677 | |
| 678 | var valid = (target.type === 'submit' && ['button', 'input'].indexOf(target.localName) > -1); |
| 679 | if (!valid) { |
| 680 | if (!(target.localName === 'input' && target.type === 'image')) { return; } |
| 681 | // this is a <input type="image">, which can submit forms |
| 682 | dialogPolyfill.useValue = ev.offsetX + ',' + ev.offsetY; |
| 683 | } |
| 684 | |
| 685 | var dialog = findNearestDialog(target); |
| 686 | if (!dialog) { return; } |
| 687 | |
| 688 | dialogPolyfill.formSubmitter = target; |
| 689 | |
| 690 | }, false); |
| 691 | |
| 692 | /** |
| 693 | * Replace the native HTMLFormElement.submit() method, as it won't fire the |
| 694 | * submit event and give us a chance to respond. |
| 695 | */ |
| 696 | var nativeFormSubmit = HTMLFormElement.prototype.submit; |
| 697 | var replacementFormSubmit = function () { |
| 698 | if (!isFormMethodDialog(this)) { |
| 699 | return nativeFormSubmit.call(this); |
| 700 | } |
| 701 | var dialog = findNearestDialog(this); |
| 702 | dialog && dialog.close(); |
| 703 | }; |
| 704 | HTMLFormElement.prototype.submit = replacementFormSubmit; |
| 705 | |
| 706 | /** |
| 707 | * Global form 'dialog' method handler. Closes a dialog correctly on submit |
| 708 | * and possibly sets its return value. |
| 709 | */ |
| 710 | document.addEventListener('submit', function(ev) { |
| 711 | var form = /** @type {HTMLFormElement} */ (ev.target); |
| 712 | if (!isFormMethodDialog(form)) { return; } |
| 713 | ev.preventDefault(); |
| 714 | |
| 715 | var dialog = findNearestDialog(form); |
| 716 | if (!dialog) { return; } |
| 717 | |
| 718 | // Forms can only be submitted via .submit() or a click (?), but anyway: sanity-check that |
| 719 | // the submitter is correct before using its value as .returnValue. |
| 720 | var s = dialogPolyfill.formSubmitter; |
| 721 | if (s && s.form === form) { |
| 722 | dialog.close(dialogPolyfill.useValue || s.value); |
| 723 | } else { |
| 724 | dialog.close(); |
| 725 | } |
| 726 | dialogPolyfill.formSubmitter = null; |
| 727 | |
| 728 | }, true); |
| 729 | } |
| 730 | |
| 731 | |
| 732 | export default dialogPolyfill; |