"use strict";

exports.__esModule = true;
exports.default = useClickAway;

var _react = require("react");

var _getTargetElement = require("../utils/dom/getTargetElement");

// 鼠标点击事件，click 不会监听右键
var defaultEvent = 'click';

function useClickAway(target, onClickAway, eventName) {
  if (eventName === void 0) {
    eventName = defaultEvent;
  }

  var onClickAwayRef = (0, _react.useRef)(onClickAway);
  onClickAwayRef.current = onClickAway;
  (0, _react.useEffect)(function () {
    var handler = function handler(event) {
      var targets = Array.isArray(target) ? target : [target];

      if (targets.some(function (targetItem) {
        var targetElement = (0, _getTargetElement.getTargetElement)(targetItem);
        return !targetElement || (targetElement == null ? void 0 : targetElement.contains(event.target));
      })) {
        return;
      }

      onClickAwayRef.current(event);
    };

    document.addEventListener(eventName, handler);
    return function () {
      document.removeEventListener(eventName, handler);
    };
  }, [target, eventName]);
}