1
0
Fork 0
docsearch/packages/docsearch-react/src/useTrapFocus.ts
Pierre Millot aa666deccc
chore(deps): dependencies 2024-11-04 (#2335)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-11-04 18:15:51 +01:00

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]);
}