dialog-polyfill.js 28 KB

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