"use strict";

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

exports.__esModule = true;
exports.default = void 0;

var _react = require("react");

var _DOMHelper = _interopRequireDefault(require("../DOMHelper"));

var _ = require("./");

function isLeftClickEvent(event) {
  return (event === null || event === void 0 ? void 0 : event.button) === 0;
}

function isModifiedEvent(event) {
  return !!(event.metaKey || event.altKey || event.ctrlKey || (event === null || event === void 0 ? void 0 : event.shiftKey));
}

/**
 * A hook that listens to the document click event and closes the overlay.
 * @param onRootClose
 * @param param1
 */
function useRootClose(onRootClose, _ref) {
  var disabled = _ref.disabled,
      triggerTarget = _ref.triggerTarget,
      overlayTarget = _ref.overlayTarget;
  var handleDocumentKeyUp = (0, _react.useCallback)(function (event) {
    if (event.keyCode === _.KEY_CODE.ESC) {
      onRootClose === null || onRootClose === void 0 ? void 0 : onRootClose(event);
    }
  }, [onRootClose]);
  var handleDocumentClick = (0, _react.useCallback)(function (event) {
    var triggerElement = (0, _.getDOMNode)(triggerTarget);
    var overlayElement = (0, _.getDOMNode)(overlayTarget); // Check if the clicked element is a trigger.

    if (triggerElement && _DOMHelper.default.contains(triggerElement, event.target)) {
      return;
    } // Check if the clicked element is a overlay.


    if (overlayElement && _DOMHelper.default.contains(overlayElement, event.target)) {
      return;
    }

    if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
      return;
    }

    onRootClose === null || onRootClose === void 0 ? void 0 : onRootClose(event);
  }, [onRootClose, triggerTarget, overlayTarget]);
  (0, _react.useEffect)(function () {
    var currentTarget = (0, _.getDOMNode)(triggerTarget);
    if (disabled || !currentTarget) return;

    var doc = _DOMHelper.default.ownerDocument(currentTarget);

    var onDocumentClickListener = _DOMHelper.default.on(doc, 'click', handleDocumentClick, true);

    var onDocumentKeyupListener = _DOMHelper.default.on(doc, 'keyup', handleDocumentKeyUp);

    return function () {
      onDocumentClickListener === null || onDocumentClickListener === void 0 ? void 0 : onDocumentClickListener.off();
      onDocumentKeyupListener === null || onDocumentKeyupListener === void 0 ? void 0 : onDocumentKeyupListener.off();
    };
  }, [triggerTarget, disabled, onRootClose, handleDocumentClick, handleDocumentKeyUp]);
}

var _default = useRootClose;
exports.default = _default;