"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useClickAway;

var _react = require("react");

var _events = _interopRequireDefault(require("../utils/events"));

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

var _hooks = require("../utils/hooks");

function useClickAway(target, onClickAway) {
  var eventName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'click';
  var onClickAwayRef = (0, _hooks.useLatest)(onClickAway);
  var eventNameRef = (0, _hooks.useLatest)(eventName);
  var targetRef = (0, _hooks.useLatest)(target);
  (0, _react.useEffect)(function () {
    var handler = function handler(event) {
      var _onClickAwayRef$curre;

      var currentTarget = targetRef.current;
      var targets = Array.isArray(currentTarget) ? currentTarget : [currentTarget];

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

      (_onClickAwayRef$curre = onClickAwayRef.current) === null || _onClickAwayRef$curre === void 0 ? void 0 : _onClickAwayRef$curre.call(onClickAwayRef, event);
    };

    _events.default.on(document, eventNameRef.current, handler);

    return function () {
      _events.default.off(document, eventNameRef.current, handler);
    };
  }, []);
}