import { useEffect } from 'react';

export default function useOnClickOutside(ref, handler) {
  useEffect(() => {
    const onEvent = (event) => {
      if (!ref.current) {
        return;
      }

      if (event instanceof KeyboardEvent && event.key === 'Escape') {
        handler(event);
      } else if (ref.current.contains(event.target)) {
        return;
      }

      handler(event);
    };

    document.addEventListener('mousedown', onEvent);
    document.addEventListener('touchstart', onEvent);
    document.addEventListener('keydown', onEvent);

    return () => {
      document.removeEventListener('mousedown', onEvent);
      document.removeEventListener('touchstart', onEvent);
      document.removeEventListener('keydown', onEvent);
    };
  }, [ref, handler]);
}
