import { useRef, useLayoutEffect } from 'react';

/**
 * Returns focus to the previously focused element when the full-screen drawer is dismissed.
 */
export function useReturnFocusOnClose({
  isShown
}) {
  const lastActiveElement = useRef(null);
  useLayoutEffect(() => {
    if (isShown) {
      lastActiveElement.current = document.activeElement;
    } else {
      lastActiveElement.current?.focus();
    }
    return () => lastActiveElement?.current?.focus();
  }, [isShown]);
}