Name dialogs and contain native overlay keyboard focus

This commit is contained in:
Joseph Doherty
2026-11-13 17:42:14 -05:00
parent cdd3adf6fc
commit 87c882ec0a
46 changed files with 1353 additions and 119 deletions
@@ -1,63 +1,88 @@
// Focus management helpers for the centralised DialogHost (T33a). Small and
// dependency-free: capture/restore the trigger element's focus across a modal's
// lifetime, and trap Tab focus inside an open modal. Blazor calls these via
// JS interop (window.sbDialog.*); they are no-ops when there is nothing to act
// on, so prerender / loose-mode test calls do no harm.
// Local overlay pilot: synchronous native Tab handling and per-instance cleanup.
// Generic extraction waits for a second consumer. No dependency on window.event.
(function () {
'use strict';
// CSS selector for elements that can receive keyboard focus within the modal.
const FOCUSABLE =
"a[href],button:not([disabled]),input:not([disabled])," +
"select:not([disabled]),textarea:not([disabled])," +
"[tabindex]:not([tabindex='-1'])";
// The element that had focus when the most recent dialog opened. Module-level
// so it survives between the capture (on open) and restore (on close) calls.
let savedActiveElement = null;
window.sbDialog = {
// Stash the currently focused element so it can be restored on close.
// Called BEFORE the modal steals focus.
captureActiveElement: function () {
savedActiveElement = document.activeElement;
},
// Return focus to the stashed element if it is still in the document,
// then clear the stash so a later dialog starts fresh.
restoreActiveElement: function () {
const el = savedActiveElement;
savedActiveElement = null;
if (el && typeof el.focus === 'function' && el.isConnected) {
el.focus();
}
},
// Cycle focus within the modal: at the first focusable element a
// Shift+Tab wraps to the last; at the last a Tab wraps to the first. In
// both cases the default browser move (which would leave the modal) is
// prevented. Anywhere else, the native Tab order applies untouched.
focusTrap: function (modalEl, shiftKey) {
if (!modalEl) return;
const focusable = modalEl.querySelectorAll(FOCUSABLE);
if (focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement;
// Blazor interop does not hand us the DOM event, but window.event is
// populated during the synchronous keydown dispatch on the engines we
// target — guard the preventDefault so the wrap still works if it is
// ever absent (the explicit .focus() override is the real trap).
const evt = window.event;
if (shiftKey && active === first) {
last.focus();
if (evt) evt.preventDefault();
} else if (!shiftKey && active === last) {
first.focus();
if (evt) evt.preventDefault();
const selector = 'a[href],button,input,select,textarea,[tabindex]';
const states = new Map();
const inertLocks = new Map();
let hadModalOpen = false;
function focusable(root) {
return Array.from(root.querySelectorAll(selector)).filter(el =>
el.tabIndex >= 0 && !el.matches(':disabled') && !el.closest('[inert],[hidden]') &&
el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden');
}
function lock(el) {
const old = inertLocks.get(el);
if (old) old.count++;
else { inertLocks.set(el, { count: 1, previous: el.inert }); el.inert = true; }
}
function unlock(el) {
const old = inertLocks.get(el);
if (!old || --old.count) return;
el.inert = old.previous; inertLocks.delete(el);
}
function deactivate(id) {
const state = states.get(id);
if (!state) return;
const wasTop = Array.from(states.keys()).at(-1) === id;
states.delete(id);
state.el.removeEventListener('keydown', state.keydown);
state.locked.forEach(unlock);
if (!states.size && !hadModalOpen) document.body.classList.remove('modal-open');
if (!wasTop) return;
if (state.trigger?.isConnected && !state.trigger.closest('[inert]')) state.trigger.focus();
// A connected trigger may now be disabled, hidden, or unfocusable.
// Verify the browser accepted focus rather than trusting connectivity.
if (document.activeElement !== state.trigger) {
const fallback = document.querySelector('main h1,.page h1') || document.querySelector('main,.page');
if (fallback) {
const previous = fallback.getAttribute('tabindex');
fallback.setAttribute('tabindex', '-1'); fallback.focus();
// Removing tabindex immediately blurs an otherwise nonfocusable
// heading in Chromium. Restore its markup only after focus leaves.
if (previous === null) fallback.addEventListener('blur', () => fallback.removeAttribute('tabindex'), { once: true });
else fallback.setAttribute('tabindex', previous);
}
}
};
}
function activate(id, initialSelector) {
const el = document.getElementById(id);
if (!el) return false;
if (states.has(id)) return true;
// One active overlay is supported. Reject sibling and descendant opens;
// callers cancel the rejected presentation through existing close paths.
if (states.size || el.closest('[inert]')) return false;
if (!states.size) hadModalOpen = document.body.classList.contains('modal-open');
const state = { el, trigger: document.activeElement, locked: [] };
// Inert siblings along the ancestor path, never the dialog or its host.
for (let node = el; node.parentElement; node = node.parentElement) {
for (const sibling of node.parentElement.children) {
if (sibling === node || sibling.matches('script,style,link,.modal-backdrop,.offcanvas-backdrop')) continue;
lock(sibling); state.locked.push(sibling);
}
if (node.parentElement === document.body) break;
}
state.keydown = event => {
if (Array.from(states.keys()).at(-1) !== id) return;
if (event.key === 'Escape') event.preventDefault(); // Blazor retains cancellation semantics.
if (event.key !== 'Tab') return;
const items = focusable(el);
const first = items[0], last = items.at(-1), active = document.activeElement;
if (!items.length) { event.preventDefault(); el.focus(); }
else if (event.shiftKey && (active === first || !items.includes(active))) {
event.preventDefault(); last.focus();
} else if (!event.shiftKey && (active === last || !items.includes(active))) {
event.preventDefault(); first.focus();
}
};
states.set(id, state); el.addEventListener('keydown', state.keydown);
document.body.classList.add('modal-open');
const initial = initialSelector ? el.querySelector(initialSelector) : null;
(initial || el).focus();
return true;
}
new MutationObserver(() => {
for (const [id, state] of states) if (!state.el.isConnected) deactivate(id);
}).observe(document.documentElement, { childList: true, subtree: true });
window.sbDialog = { activate, deactivate };
})();