const FOCUSABLE_SELECTOR = "a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])"; export function getFocusableControls(root: HTMLElement | null): HTMLElement[] { return Array.from(root?.querySelectorAll(FOCUSABLE_SELECTOR) ?? []).filter( (control) => control.getClientRects().length > 0, ); } export function trapTabKey(event: KeyboardEvent, controls: readonly HTMLElement[]): void { if (event.key !== "Tab" || controls.length === 0) return; const first = controls[0]; const last = controls[controls.length - 1]; if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } }