fix focus trap

This commit is contained in:
kakkokari-gtyih 2024-07-09 23:04:30 +09:00
parent 3dcf7da28e
commit fe046efd1d
1 changed files with 14 additions and 1 deletions

View File

@ -4,13 +4,24 @@
*/
import { getHTMLElementOrNull } from '@/scripts/get-or-null.js';
const focusTrapElements = new Set<HTMLElement>();
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);