41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
import React from 'react';
|
|
|
|
interface UseTrapFocusProps {
|
|
container: HTMLElement | null;
|
|
}
|
|
|
|
export function useTrapFocus({ container }: UseTrapFocusProps): void {
|
|
React.useEffect(() => {
|
|
if (!container) {
|
|
return undefined;
|
|
}
|
|
|
|
const focusableElements = container.querySelectorAll<HTMLElement>(
|
|
'a[href]:not([disabled]), button:not([disabled]), input:not([disabled])',
|
|
);
|
|
const firstElement = focusableElements[0];
|
|
const lastElement = focusableElements[focusableElements.length - 1];
|
|
|
|
function trapFocus(event: KeyboardEvent): void {
|
|
if (event.key !== 'Tab') {
|
|
return;
|
|
}
|
|
|
|
if (event.shiftKey) {
|
|
if (document.activeElement === firstElement) {
|
|
event.preventDefault();
|
|
lastElement.focus();
|
|
}
|
|
} else if (document.activeElement === lastElement) {
|
|
event.preventDefault();
|
|
firstElement.focus();
|
|
}
|
|
}
|
|
|
|
container.addEventListener('keydown', trapFocus);
|
|
|
|
return (): void => {
|
|
container.removeEventListener('keydown', trapFocus);
|
|
};
|
|
}, [container]);
|
|
}
|