diff --git a/packages/frontend/src/scripts/focus-trap.ts b/packages/frontend/src/scripts/focus-trap.ts index efd009af09..4b421415b0 100644 --- a/packages/frontend/src/scripts/focus-trap.ts +++ b/packages/frontend/src/scripts/focus-trap.ts @@ -4,13 +4,24 @@ */ import { getHTMLElementOrNull } from '@/scripts/get-or-null.js'; +const focusTrapElements = new Set(); + +function containsFocusTrappedElements(el: HTMLElement): boolean { + return Array.from(focusTrapElements).some((focusTrapElement) => { + return el.contains(focusTrapElement); + }); +} + function releaseFocusTrap(el: HTMLElement): void { + focusTrapElements.delete(el); if (el.parentElement && el.parentElement !== document.body) { el.parentElement.childNodes.forEach((siblingNode) => { const siblingEl = getHTMLElementOrNull(siblingNode); if (!siblingEl) return; - if (siblingEl !== el) { + if (siblingEl !== el && (focusTrapElements.has(siblingEl) || containsFocusTrappedElements(siblingEl) || focusTrapElements.size === 0)) { siblingEl.inert = false; + } else if (!containsFocusTrappedElements(siblingEl) && !focusTrapElements.has(siblingEl)) { + siblingEl.inert = true; } }); releaseFocusTrap(el.parentElement); @@ -29,6 +40,8 @@ export function focusTrap(el: HTMLElement): { release: () => void; } { focusTrap(el.parentElement); } + focusTrapElements.add(el); + return { release: () => { releaseFocusTrap(el);