1
0
mirror of https://gitlab.nic.cz/turris/reforis/foris-js.git synced 2025-06-18 13:56:17 +02:00

Refactor Modal component to use useFocusTrap hook

This commit is contained in:
Aleksandr Gumroian
2024-09-16 17:59:21 +02:00
parent c86e2c8944
commit 446ec1bbe5
2 changed files with 47 additions and 6 deletions

View File

@ -40,3 +40,41 @@ export function useClickOutside(element, callback) {
};
});
}
/* Trap focus inside modal. */
export function useFocusTrap(modalRef) {
useEffect(() => {
if (shown) {
const modal = modalRef.current;
const focusableElements = modal.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
const handleTab = (event) => {
if (event.key === "Tab") {
if (event.shiftKey) {
if (document.activeElement === firstElement) {
lastElement.focus();
event.preventDefault();
}
} else {
if (document.activeElement === lastElement) {
firstElement.focus();
event.preventDefault();
}
}
}
};
modal.addEventListener("keydown", handleTab);
firstElement.focus();
return () => {
modal.removeEventListener("keydown", handleTab);
};
}
}, [shown]);
}