|
| 1 | +import { getViewportSize } from '../../commons/dom'; |
| 2 | +export default function detectModalStack(options) { |
| 3 | + options = options || {}; |
| 4 | + const modalPercent = options.modalPercent || 0.75; |
| 5 | + |
| 6 | + // there is no "definitive" way to code a modal so detecting when one is open |
| 7 | + // is a bit of a guess. a modal won't always be accessible, so we can't rely |
| 8 | + // on the `role` attribute, and relying on a class name as a convention is |
| 9 | + // unreliable. we also cannot rely on the body/html not scrolling. |
| 10 | + // |
| 11 | + // because of this, we will look for two different types of modals: |
| 12 | + // "definitely a modal" and "could be a modal." |
| 13 | + // |
| 14 | + // "definitely a modal" is any visible element that is coded to be a modal |
| 15 | + // by using one of the following criteria: |
| 16 | + // |
| 17 | + // - has the attribute `role=dialog` |
| 18 | + // - has the attribute `aria-modal=true` |
| 19 | + // - is the dialog element |
| 20 | + // |
| 21 | + // "could be a modal" is a visible element that takes up more than 75% of |
| 22 | + // the screen (though typically full width/height) and is the top-most element |
| 23 | + // in the viewport. since we aren't sure if it is or is not a modal this is |
| 24 | + // just our best guess of being one based on convention. |
| 25 | + |
| 26 | + const definiteModals = Array.from( |
| 27 | + document.querySelectorAll( |
| 28 | + 'dialog[open], [role="dialog"], [role="alertdialog"], [aria-modal="true"]' |
| 29 | + ) |
| 30 | + ); |
| 31 | + |
| 32 | + // to find a "could be a modal" we will take the element stack from each of |
| 33 | + // four corners and one from the middle of the viewport (total of 5). if each |
| 34 | + // stack contains an element whose width/height is >= 75% of the screen, we |
| 35 | + // found a "could be a modal" |
| 36 | + const viewport = getViewportSize(window); |
| 37 | + const percentWidth = viewport.width * modalPercent; |
| 38 | + const percentHeight = viewport.height * modalPercent; |
| 39 | + const x = (viewport.width - percentWidth) / 2; |
| 40 | + const y = (viewport.height - percentHeight) / 2; |
| 41 | + |
| 42 | + const points = [ |
| 43 | + // top-left corner |
| 44 | + { x, y }, |
| 45 | + // top-right corner |
| 46 | + { x: viewport.width - x, y }, |
| 47 | + // center |
| 48 | + { x: viewport.width / 2, y: viewport.height / 2 }, |
| 49 | + // bottom-left corner |
| 50 | + { x, y: viewport.height - y }, |
| 51 | + // bottom-right corner |
| 52 | + { x: viewport.width - x, y: viewport.height - y } |
| 53 | + ]; |
| 54 | + |
| 55 | + const stacks = points.map(point => { |
| 56 | + return Array.from(document.elementsFromPoint(point.x, point.y)); |
| 57 | + }); |
| 58 | + |
| 59 | + return { definiteModals, stacks }; |
| 60 | +} |
0 commit comments