next js 포커스 매니저 컴포넌트

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;

Comments

답글 남기기