interface FocusManagerProps {
isOpen: boolean;
containerId: string;
children: React.ReactNode;
}
const FocusManager = ({
isOpen,
containerId,
children
}: FocusManagerProps) => {
const previousFocusRef = useRef<HTMLElement | null>(null);
useEffect(() => {
const container = document.getElementById(containerId);
if (isOpen && container) {
// 현재 포커스 저장
previousFocusRef.current = document.activeElement as HTMLElement;
// 포커스 이동 처리
setTimeout(() => {
const focusableElement = container.querySelector(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
) as HTMLElement;
if (focusableElement) {
focusableElement.focus();
} else {
container.setAttribute('tabindex', '-1');
container.focus();
}
}, 500);
} else if (!isOpen && container) {
// 이전 포커스로 복귀
setTimeout(() => {
if (previousFocusRef.current && previousFocusRef.current !== document.body) {
previousFocusRef.current.focus();
}
}, 500);
}
}, [isOpen, containerId]);
return <>{children}</>;
};
export default FocusManager;
답글 남기기
댓글을 달기 위해서는 로그인해야합니다.