ifmeorg/ifme

View on GitHub
client/app/hooks/useFocusTrap.js

Summary

Maintainability
A
3 hrs
Test Coverage
// @flow
import { useEffect } from 'react';
 
Function `useFocusTrap` has a Cognitive Complexity of 14 (exceeds 5 allowed). Consider refactoring.
Function `useFocusTrap` has 33 lines of code (exceeds 25 allowed). Consider refactoring.
export const useFocusTrap = (
Parsing error: Unexpected token, expected "," (5:5)
ref: { current: null | HTMLElement },
isOpen: boolean,
) => {
useEffect(() => {
const handleKeyDown = (e: any) => {
const focusableElements = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const element = ref.current;
if (!element) return;
 
const focusableContent = element.querySelectorAll(focusableElements);
const visibleContent = Array.from(focusableContent).filter(
(node) => window.getComputedStyle(node).display !== 'none',
);
 
const firstFocusableElement = visibleContent[0];
const lastFocusableElement = visibleContent[visibleContent.length - 1];
const isTabPressed = e.key === 'Tab' || e.keyCode === 9;
 
if (!isTabPressed) {
return;
}
 
if (e.shiftKey && document.activeElement === firstFocusableElement) {
lastFocusableElement.focus();
e.preventDefault();
} else if (
!e.shiftKey
&& document.activeElement === lastFocusableElement
) {
firstFocusableElement.focus();
e.preventDefault();
}
};
 
if (isOpen) {
document.addEventListener('keydown', handleKeyDown);
}
 
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [isOpen, ref]);
};