/** Focus helpers for homepage nav sheets (dialog). */ const FOCUSABLE = 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])'; let trapRoot: HTMLElement | null = null; let onKey: ((e: KeyboardEvent) => void) | null = null; function listFocusable(root: HTMLElement): HTMLElement[] { return [...root.querySelectorAll(FOCUSABLE)].filter((el) => { if (el.hasAttribute('disabled') || el.getAttribute('aria-hidden') === 'true') return false; // offsetParent is null for fixed/absolute in some cases — also check client rects const style = window.getComputedStyle(el); if (style.visibility === 'hidden' || style.display === 'none') return false; return el.getClientRects().length > 0; }); } export function activatePanelFocus(root: HTMLElement) { deactivatePanelFocus(); trapRoot = root; const closeBtn = root.querySelector( '.ai-guide-panel__close, .ai-routes-panel__close, [data-panel-close]', ); const nodes = listFocusable(root); (closeBtn && nodes.includes(closeBtn) ? closeBtn : nodes[0])?.focus(); onKey = (e: KeyboardEvent) => { if (e.key !== 'Tab' || !trapRoot) return; const list = listFocusable(trapRoot); if (list.length === 0) return; const first = list[0]; const last = list[list.length - 1]; if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } }; document.addEventListener('keydown', onKey, true); } export function deactivatePanelFocus() { if (onKey) document.removeEventListener('keydown', onKey, true); onKey = null; trapRoot = null; }