import { useRef } from 'react';
import { useEventListener } from './EventListener';
/**
 * @deprecatedSince 9
 * @deprecated Never officially documented/supported
 */
// To support MenuRef had to change to any. Could manually do <HTMLElement & MenuRef> but seems brittle
export function isEventSource(ref, event) {
  if (ref !== null && ref !== void 0 && ref.current && event && (event.target instanceof HTMLElement || event.target instanceof SVGElement)) {
    return ref.current.contains(event.target);
  } else {
    return false;
  }
}

/**
 * @deprecatedSince 9
 * @deprecated Never officially documented/supported
 */
export function useClickOutside(_ref) {
  var _ref$refs = _ref.refs,
    refs = _ref$refs === void 0 ? [] : _ref$refs,
    onClickOutside = _ref.onClickOutside,
    container = _ref.container;
  var mousedownTarget = useRef(null);
  var handleMouseDown = function handleMouseDown(event) {
    mousedownTarget.current = event.target;
  };

  // Only trigger if the mouseup target is the same as the mousedown target
  // and it's outside of our refs
  var handleMouseUp = function handleMouseUp(event) {
    var _mousedownTarget$curr, _mousedownTarget$curr2;
    var isSameTarget = mousedownTarget.current instanceof Element && event.target instanceof Element && ((_mousedownTarget$curr = (_mousedownTarget$curr2 = mousedownTarget.current).isSameNode) === null || _mousedownTarget$curr === void 0 ? void 0 : _mousedownTarget$curr.call(_mousedownTarget$curr2, event.target));
    var isOutsideTarget = !refs.find(function (ref) {
      return isEventSource(ref, event);
    });
    if (isOutsideTarget && isSameTarget) {
      onClickOutside(event);
    }
    mousedownTarget.current = null;
  };
  var options = {
    capture: true
  };
  var containerDocument = container === null || container === void 0 ? void 0 : container.ownerDocument;
  var scope = (containerDocument === null || containerDocument === void 0 ? void 0 : containerDocument.defaultView) || undefined;
  useEventListener({
    event: 'mousedown',
    handler: handleMouseDown,
    options: options,
    scope: scope
  });
  useEventListener({
    event: 'mouseup',
    handler: handleMouseUp,
    options: options,
    scope: scope
  });
  useEventListener({
    event: 'touchend',
    handler: handleMouseUp,
    options: options,
    scope: scope
  });
}
//# sourceMappingURL=ClickOutside.js.map