"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
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 _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _ReactEditorViewContext = _interopRequireDefault(require("./ReactEditorViewContext"));
var _excluded = ["handleClickOutside", "handleEnterKeydown", "handleEscapeKeydown", "closeOnTab"];
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
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 alongisde `withReactEditorViewOuterListeners`
var WithOutsideClick = /*#__PURE__*/function (_PureComponent) {
  (0, _inherits2.default)(WithOutsideClick, _PureComponent);
  var _super = _createSuper(WithOutsideClick);
  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 = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "handleClick", function (evt) {
      if (!_this.props.isActiveComponent) {
        return;
      }
      var domNode = _reactDom.default.findDOMNode((0, _assertThisInitialized2.default)(_this)); // eslint-disable-line react/no-find-dom-node
      if (!domNode || evt.target instanceof Node && !domNode.contains(evt.target)) {
        if (_this.props.handleClickOutside) {
          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)((0, _assertThisInitialized2.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);
      }
    });
    return _this;
  }
  (0, _createClass2.default)(WithOutsideClick, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.handleClickOutside) {
        document.addEventListener('click', this.handleClick, false);
      }
      if (this.props.handleEscapeKeydown) {
        var _this$props$editorRef;
        // Attached event to the menu so that 'ESC' events from the opened menu also will be handled.
        (((_this$props$editorRef = this.props.editorRef) === null || _this$props$editorRef === void 0 ? void 0 : _this$props$editorRef.current) || this.props.targetRef || document).addEventListener('keydown', this.handleKeydown, false);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (this.props.handleClickOutside) {
        document.removeEventListener('click', this.handleClick, false);
      }
      if (this.props.handleEscapeKeydown) {
        var _this$props$editorRef2;
        (((_this$props$editorRef2 = this.props.editorRef) === null || _this$props$editorRef2 === void 0 ? void 0 : _this$props$editorRef2.current) || this.props.targetRef || document).removeEventListener('keydown', this.handleKeydown, false);
      }
    }
  }, {
    key: "render",
    value: function render() {
      return this.props.children;
    }
  }]);
  return WithOutsideClick;
}(_react.PureComponent);
function hasIsOpen(props) {
  return 'isOpen' in props;
}
function withReactEditorViewOuterListeners(Component) {
  return function (_ref) {
    var handleClickOutside = _ref.handleClickOutside,
      handleEnterKeydown = _ref.handleEnterKeydown,
      handleEscapeKeydown = _ref.handleEscapeKeydown,
      closeOnTab = _ref.closeOnTab,
      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];
    (0, _react.useEffect)(function () {
      requestAnimationFrame(function () {
        setActiveComponent(isActiveProp);
      });
    }, [isActiveProp]);
    return /*#__PURE__*/_react.default.createElement(_ReactEditorViewContext.default.Consumer, null, function (_ref2) {
      var editorView = _ref2.editorView,
        editorRef = _ref2.editorRef;
      return /*#__PURE__*/_react.default.createElement(WithOutsideClick, {
        editorView: editorView,
        editorRef: editorRef,
        targetRef: props.targetRef,
        isActiveComponent: isActiveComponent,
        handleClickOutside: handleClickOutside,
        handleEnterKeydown: handleEnterKeydown,
        handleEscapeKeydown: handleEscapeKeydown,
        closeOnTab: closeOnTab
      }, /*#__PURE__*/_react.default.createElement(Component, props));
    });
  };
}