const dialogs = new Map( [...document.querySelectorAll('.legal-dialog')].map(dialog => [dialog.id, dialog]), ); let returnFocus; function syncDialog() { const next = dialogs.get(location.hash.slice(1)); let closed = false; for (const dialog of dialogs.values()) { if (dialog.open && dialog !== next) { dialog.close(); closed = true; } } if (next && !next.open) { returnFocus ??= document.querySelector(`[data-legal-open][aria-controls="${next.id}"]`); next.showModal(); next.querySelector('.legal-copy').scrollTop = 0; next.querySelector('h1').focus({ preventScroll: true }); } else if (!next && closed) { returnFocus?.focus({ preventScroll: true }); returnFocus = undefined; } } function dismissDialog() { history.replaceState(null, '', location.pathname + location.search); syncDialog(); } for (const link of document.querySelectorAll('[data-legal-open]')) { link.addEventListener('click', event => { if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; event.preventDefault(); returnFocus = link; history.pushState(null, '', link.hash); syncDialog(); }); } for (const dialog of dialogs.values()) { dialog.querySelector('[data-legal-close]').addEventListener('click', event => { event.preventDefault(); dismissDialog(); }); dialog.addEventListener('cancel', event => { event.preventDefault(); dismissDialog(); }); dialog.addEventListener('keydown', event => { if (event.key !== 'Tab' || event.altKey || event.ctrlKey || event.metaKey) return; const controls = [...dialog.querySelectorAll('a[href], button:not([disabled]), [tabindex="0"]')]; const first = controls[0]; const last = controls.at(-1); const active = document.activeElement; if (!controls.includes(active) || (event.shiftKey && active === first) || (!event.shiftKey && active === last)) { event.preventDefault(); (event.shiftKey ? last : first)?.focus(); } }); // Close only when both ends of a click are on the backdrop, not a text-selection drag. let startedOutside = false; const outside = event => { const rect = dialog.getBoundingClientRect(); return event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom; }; dialog.addEventListener('pointerdown', event => { startedOutside = event.target === dialog && outside(event); }); dialog.addEventListener('click', event => { if (startedOutside && event.target === dialog && outside(event)) dismissDialog(); startedOutside = false; }); } window.addEventListener('hashchange', syncDialog); window.addEventListener('popstate', syncDialog); syncDialog();