"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "OutsideClickTargetRefContext", {
  enumerable: true,
  get: function get() {
    return _OutsideClickTargetRefContext.OutsideClickTargetRefContext;
  }
});
exports.default = withReactEditorViewOuterListeners;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _experiments = require("@atlaskit/tmp-editor-statsig/experiments");
var _OutsideClickTargetRefContext = require("./OutsideClickTargetRefContext");
var _ReactEditorViewContext = _interopRequireDefault(require("./ReactEditorViewContext"));
var _excluded = ["captureClick", "closeOnTab", "handleBackspaceDeleteKeydown", "handleClickOutside", "handleEnterKeydown", "handleEscapeKeydown", "handleKeyDown"];
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
// This needs exporting to be used alongside `withReactEditorViewOuterListeners`
// Ignored via go/ees005
// eslint-disable-next-line @repo/internal/react/no-class-components
var WithOutsideClick = /*#__PURE__*/function (_PureComponent) {
  function WithOutsideClick() {
    var _this;
    (0, _classCallCheck2.default)(this, WithOutsideClick);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, WithOutsideClick, [].concat(args));
    (0, _defineProperty2.default)(_this, "handleClick", function (evt) {
      var _this$props$outsideCl;
      if (!_this.props.isActiveComponent || !_this.props.handleClickOutside) {
        return;
      }
      var domNode = (_this$props$outsideCl = _this.props.outsideClickTargetRef.current) === null || _this$props$outsideCl === void 0 ? void 0 : _this$props$outsideCl.deref();
      if (!domNode || evt.target instanceof Node && !domNode.contains(evt.target)) {
        var _this$props$editorVie;
        _this.props.handleClickOutside(evt);
        // When the menus are closed by clicking outside the focus is set on editor.
        if (!((_this$props$editorVie = _this.props.editorView) !== null && _this$props$editorVie !== void 0 && _this$props$editorVie.hasFocus())) {
          var _this$props$editorVie2;
          (_this$props$editorVie2 = _this.props.editorView) === null || _this$props$editorVie2 === void 0 || _this$props$editorVie2.focus();
        }
      }
    });
    (0, _defineProperty2.default)(_this, "handleKeyDown", function (evt) {
      if (!_this.props.isActiveComponent) {
        return;
      }
      if (evt.code === 'Escape' && _this.props.handleEscapeKeydown) {
        evt.preventDefault();
        evt.stopPropagation();
        _this.props.handleEscapeKeydown(evt);
        // on 'Esc', Focus is handled in 'handleEscapeKeydown'.
        return false;
      } else if (evt.code === 'Enter' && _this.props.handleEnterKeydown) {
        _this.props.handleEnterKeydown(evt);
      } else if (evt.code === 'Tab' && _this.props.handleEscapeKeydown && _this.props.closeOnTab) {
        // The menus should be closed when the tab is pressed as it takes the focus out of the menu
        _this.props.handleEscapeKeydown(evt);
      } else if ((evt.code === 'Delete' || evt.code === 'Backspace') && _this.props.handleBackspaceDeleteKeydown) {
        _this.props.handleBackspaceDeleteKeydown(evt);
      }
      if ((0, _experiments.editorExperiment)('platform_editor_block_menu', true, {
        exposure: true
      })) {
        var _this$props$handleKey, _this$props;
        (_this$props$handleKey = (_this$props = _this.props).handleKeyDown) === null || _this$props$handleKey === void 0 || _this$props$handleKey.call(_this$props, evt);
      }
    });
    return _this;
  }
  (0, _inherits2.default)(WithOutsideClick, _PureComponent);
  return (0, _createClass2.default)(WithOutsideClick, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.handleClickOutside) {
        var options = this.props.captureClick && (0, _experiments.editorExperiment)('platform_editor_controls', 'variant1') ? {
          capture: true
        } : false;
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        document.addEventListener('click', this.handleClick, options);
      }
      if (this.props.handleEscapeKeydown || this.props.handleBackspaceDeleteKeydown || this.props.handleKeyDown && (0, _experiments.editorExperiment)('platform_editor_block_menu', true, {
        exposure: true
      })) {
        var _this$props$editorRef;
        // Attached event to the menu so that 'ESC' events from the opened menu also will be handled.
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        (this.props.popupsMountPoint ? this.props.popupsMountPoint :
        // @ts-ignore - TS2873 TypeScript 5.9.2 upgrade
        undefined || ((_this$props$editorRef = this.props.editorRef) === null || _this$props$editorRef === void 0 ? void 0 : _this$props$editorRef.current) || this.props.targetRef || document

        // Ignored via go/ees005
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ).addEventListener('keydown', this.handleKeyDown, false);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.props.handleClickOutside) {
        var options = this.props.captureClick && (0, _experiments.editorExperiment)('platform_editor_controls', 'variant1') ? {
          capture: true
        } : false;
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        document.removeEventListener('click', this.handleClick, options);
      }
      if (this.props.handleEscapeKeydown || this.props.handleBackspaceDeleteKeydown || this.props.handleKeyDown && (0, _experiments.editorExperiment)('platform_editor_block_menu', true, {
        exposure: true
      })) {
        var _this$props$editorRef2;
        // Ignored via go/ees005
        // eslint-disable-next-line @repo/internal/dom-events/no-unsafe-event-listeners
        (this.props.popupsMountPoint ? this.props.popupsMountPoint :
        // @ts-ignore - TS2873 TypeScript 5.9.2 upgrade
        undefined || ((_this$props$editorRef2 = this.props.editorRef) === null || _this$props$editorRef2 === void 0 ? void 0 : _this$props$editorRef2.current) || this.props.targetRef || document

        // Ignored via go/ees005
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ).removeEventListener('keydown', this.handleKeyDown, false);
      }
    }
  }, {
    key: "render",
    value: function render() {
      return this.props.children;
    }
  }]);
}(_react.PureComponent);
// Ignored via go/ees005
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasIsOpen(props) {
  return 'isOpen' in props;
}
function withReactEditorViewOuterListeners(Component) {
  return function (_ref) {
    var captureClick = _ref.captureClick,
      closeOnTab = _ref.closeOnTab,
      handleBackspaceDeleteKeydown = _ref.handleBackspaceDeleteKeydown,
      handleClickOutside = _ref.handleClickOutside,
      handleEnterKeydown = _ref.handleEnterKeydown,
      handleEscapeKeydown = _ref.handleEscapeKeydown,
      handleKeyDown = _ref.handleKeyDown,
      props = (0, _objectWithoutProperties2.default)(_ref, _excluded);
    var isActiveProp = hasIsOpen(props) ? props.isOpen : true;
    var _useState = (0, _react.useState)(false),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      isActiveComponent = _useState2[0],
      setActiveComponent = _useState2[1];
    var outsideClickTargetRef = (0, _react.useRef)(null);
    var setOutsideClickTargetRef = (0, _react.useCallback)(function (el) {
      outsideClickTargetRef.current = el && new WeakRef(el);
    }, [outsideClickTargetRef]);
    (0, _react.useEffect)(function () {
      requestAnimationFrame(function () {
        setActiveComponent(isActiveProp);
      });
    }, [isActiveProp]);
    return /*#__PURE__*/_react.default.createElement(_ReactEditorViewContext.default.Consumer, null, function (_ref2) {
      var editorView = _ref2.editorView,
        popupsMountPoint = _ref2.popupsMountPoint,
        editorRef = _ref2.editorRef;
      return /*#__PURE__*/_react.default.createElement(_OutsideClickTargetRefContext.OutsideClickTargetRefContext.Provider, {
        value: setOutsideClickTargetRef
      }, /*#__PURE__*/_react.default.createElement(WithOutsideClick, {
        editorView: editorView,
        editorRef: editorRef,
        targetRef: props.targetRef,
        outsideClickTargetRef: outsideClickTargetRef,
        popupsMountPoint: popupsMountPoint,
        isActiveComponent: isActiveComponent,
        handleClickOutside: handleClickOutside,
        handleEnterKeydown: handleEnterKeydown,
        handleEscapeKeydown: handleEscapeKeydown,
        handleBackspaceDeleteKeydown: handleBackspaceDeleteKeydown,
        handleKeyDown: handleKeyDown,
        closeOnTab: closeOnTab,
        captureClick: captureClick
      }, /*#__PURE__*/_react.default.createElement(Component
      // Ignored via go/ees005
      // eslint-disable-next-line react/jsx-props-no-spreading
      , props)));
    });
  };
}
// eslint-disable-next-line @atlaskit/editor/no-re-export