import React, { useEffect } from 'react';

// 监听事件的捕获阶段，用于 ClickAwayListener 无法监听的事件
function useClickAway(ref: React.RefObject<HTMLElement> | null, onClickAway: (event: MouseEvent) => void) {
  useEffect(() => {
    function handleClick(event: MouseEvent) {
      if (!ref || !ref.current) return;

      // 如果点击事件目标在 menu 元素内，阻止菜单关闭
      if (ref.current.contains(event.target as Node)) {
        return;
      }

      onClickAway(event);
    }

    document.addEventListener('click', handleClick, true);
    return () => {
      document.removeEventListener('click', handleClick, true);
    };
  }, [ref, onClickAway]);
}

export default useClickAway;
