import { useEffect, useRef } from 'react';
const useDrawerClickAway = function useDrawerClickAway(drawer) {
  const {
    state,
    toggle
  } = drawer;
  const ref = useRef();
  useEffect(() => {
    // If the drawer is closed we don't have to do anything
    if (state === 'closed') return undefined;
    const handler = e => {
      if (ref.current && ref.current.contains(e.target)) return;
      toggle({
        context: 'ClickAway'
      });
    };

    // Why are we using a timeout here? Well, if we don't, then when the user
    // clicks on a button to open the drawer (say, the menu button in the nav
    // bar), we get a race condition between that click event bubbling up the
    // DOM and React's ability to rerender the drawer component in an "open"
    // state and attach this listener. Anecdotally, React wins, meaning that
    // the same click event that was supposed to open the drawer _also_ closes
    // the drawer, making it look like the drawer doesn't open at all.
    // A timeout of 0ms is sufficient because all we actually need to do is
    // push the attachment of the listener a _little_ deeper in the async event
    // queue.
    const timer = setTimeout(() => {
      window.document.addEventListener('click', handler);
    }, 0);
    return () => {
      clearTimeout(timer);
      window.document.removeEventListener('click', handler);
    };
  }, [state, toggle]);
  return ref;
};
export default useDrawerClickAway;