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