forked from WikiDeck/wikideck
32 lines
1.5 KiB
TypeScript
32 lines
1.5 KiB
TypeScript
import { useEffect } from 'react';
|
|
|
|
export function useModalFocus(open: boolean) {
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
const previous = document.activeElement as HTMLElement | null;
|
|
const modal = document.querySelector<HTMLElement>('[role="dialog"]');
|
|
if (!modal) return;
|
|
const background = Array.from(document.querySelectorAll<HTMLElement>('.sidebar, .main-shell'));
|
|
background.forEach(el => { el.inert = true; });
|
|
const oldOverflow = document.body.style.overflow;
|
|
document.body.style.overflow = 'hidden';
|
|
const focusable = () => Array.from(modal.querySelectorAll<HTMLElement>('a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), [tabindex="0"]')).filter(el => el.getClientRects().length > 0);
|
|
focusable()[0]?.focus();
|
|
const trap = (event: KeyboardEvent) => {
|
|
if (event.key !== 'Tab') return;
|
|
const elements = focusable();
|
|
const first = elements[0];
|
|
const last = elements.at(-1);
|
|
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
|
|
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
|
|
};
|
|
modal.addEventListener('keydown', trap);
|
|
return () => {
|
|
modal.removeEventListener('keydown', trap);
|
|
background.forEach(el => { el.inert = false; });
|
|
document.body.style.overflow = oldOverflow;
|
|
if (previous?.isConnected) previous.focus();
|
|
};
|
|
}, [open]);
|
|
}
|