"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.SelectionBasedNodeView = void 0;

var React = _interopRequireWildcard(require("react"));

var _prosemirrorState = require("prosemirror-state");

var _reactNodeView = require("../plugins/base/pm-plugins/reactNodeView");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

var ReactNodeView = /*#__PURE__*/function () {
  function ReactNodeView(node, view, getPos, portalProviderAPI, reactComponentProps, reactComponent) {
    var hasContext = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
    var viewShouldUpdate = arguments.length > 7 ? arguments[7] : undefined;

    _classCallCheck(this, ReactNodeView);

    _initialiseProps.call(this);

    this.node = node;
    this.view = view;
    this.getPos = getPos;
    this.portalProviderAPI = portalProviderAPI;
    this.reactComponentProps = reactComponentProps || {};
    this.reactComponent = reactComponent;
    this.hasContext = hasContext;
    this._viewShouldUpdate = viewShouldUpdate;
  }
  /**
   * This method exists to move initialization logic out of the constructor,
   * so object can be initialized properly before calling render first time.
   *
   * Example:
   * Instance properties get added to an object only after super call in
   * constructor, which leads to some methods being undefined during the
   * first render.
   */


  _createClass(ReactNodeView, [{
    key: "init",
    value: function init() {
      var _this = this;

      this.domRef = this.createDomRef();
      this.setDomAttrs(this.node, this.domRef);

      var _ref = this.getContentDOM() || {
        dom: undefined,
        contentDOM: undefined
      },
          contentDOMWrapper = _ref.dom,
          contentDOM = _ref.contentDOM;

      if (this.domRef && contentDOMWrapper) {
        this.domRef.appendChild(contentDOMWrapper);
        this.contentDOM = contentDOM ? contentDOM : contentDOMWrapper;
        this.contentDOMWrapper = contentDOMWrapper || contentDOM;
      } // @see ED-3790
      // something gets messed up during mutation processing inside of a
      // nodeView if DOM structure has nested plain "div"s, it doesn't see the
      // difference between them and it kills the nodeView


      this.domRef.classList.add("".concat(this.node.type.name, "View-content-wrap"));
      this.renderReactComponent(function () {
        return _this.render(_this.reactComponentProps, _this.handleRef);
      });
      return this;
    }
  }, {
    key: "renderReactComponent",
    value: function renderReactComponent(component) {
      if (!this.domRef || !component) {
        return;
      }

      this.portalProviderAPI.render(component, this.domRef, this.hasContext);
    }
  }, {
    key: "createDomRef",
    value: function createDomRef() {
      return this.node.isInline ? document.createElement('span') : document.createElement('div');
    }
  }, {
    key: "getContentDOM",
    value: function getContentDOM() {
      return undefined;
    }
  }, {
    key: "_handleRef",
    value: function _handleRef(node) {
      var contentDOM = this.contentDOMWrapper || this.contentDOM; // move the contentDOM node inside the inner reference after rendering

      if (node && contentDOM && !node.contains(contentDOM)) {
        node.appendChild(contentDOM);
      }
    }
  }, {
    key: "render",
    value: function render(props, forwardRef) {
      return this.reactComponent ? /*#__PURE__*/React.createElement(this.reactComponent, _extends({
        view: this.view,
        getPos: this.getPos,
        node: this.node,
        forwardRef: forwardRef
      }, props)) : null;
    } //@ts-ignore

  }, {
    key: "update",
    value: function update(node, _decorations) {
      var _this2 = this;

      var validUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {
        return true;
      };
      // @see https://github.com/ProseMirror/prosemirror/issues/648
      var isValidUpdate = this.node.type === node.type && validUpdate(this.node, node);

      if (!isValidUpdate) {
        return false;
      }

      if (this.domRef && !this.node.sameMarkup(node)) {
        this.setDomAttrs(node, this.domRef);
      } // View should not process a re-render if this is false.
      // We dont want to destroy the view, so we return true.


      if (!this.viewShouldUpdate(node)) {
        this.node = node;
        return true;
      }

      this.node = node;
      this.renderReactComponent(function () {
        return _this2.render(_this2.reactComponentProps, _this2.handleRef);
      });
      return true;
    }
  }, {
    key: "viewShouldUpdate",
    value: function viewShouldUpdate(nextNode) {
      if (this._viewShouldUpdate) {
        return this._viewShouldUpdate(nextNode);
      }

      return true;
    }
    /**
     * Copies the attributes from a ProseMirror Node to a DOM node.
     * @param node The Prosemirror Node from which to source the attributes
     */

  }, {
    key: "setDomAttrs",
    value: function setDomAttrs(node, element) {
      Object.keys(node.attrs || {}).forEach(function (attr) {
        element.setAttribute(attr, node.attrs[attr]);
      });
    }
  }, {
    key: "dom",
    get: function get() {
      return this.domRef;
    }
  }, {
    key: "destroy",
    value: function destroy() {
      if (!this.domRef) {
        return;
      }

      this.portalProviderAPI.remove(this.domRef);
      this.domRef = undefined;
      this.contentDOM = undefined;
    }
  }], [{
    key: "fromComponent",
    value: function fromComponent(component, portalProviderAPI, props, viewShouldUpdate) {
      return function (node, view, getPos) {
        return new ReactNodeView(node, view, getPos, portalProviderAPI, props, component, false, viewShouldUpdate).init();
      };
    }
  }]);

  return ReactNodeView;
}();
/**
 * A ReactNodeView that handles React components sensitive
 * to selection changes.
 *
 * If the selection changes, it will attempt to re-render the
 * React component. Otherwise it does nothing.
 *
 * You can subclass `viewShouldUpdate` to include other
 * props that your component might want to consider before
 * entering the React lifecycle. These are usually props you
 * compare in `shouldComponentUpdate`.
 *
 * An example:
 *
 * ```
 * viewShouldUpdate(nextNode) {
 *   if (nextNode.attrs !== this.node.attrs) {
 *     return true;
 *   }
 *
 *   return super.viewShouldUpdate(nextNode);
 * }```
 */


exports["default"] = ReactNodeView;

var _initialiseProps = function _initialiseProps() {
  var _this3 = this;

  this.handleRef = function (node) {
    return _this3._handleRef(node);
  };
};

var SelectionBasedNodeView = /*#__PURE__*/function (_ReactNodeView) {
  _inherits(SelectionBasedNodeView, _ReactNodeView);

  var _super = _createSuper(SelectionBasedNodeView);

  function SelectionBasedNodeView(node, view, getPos, portalProviderAPI, reactComponentProps, reactComponent) {
    var _this4;

    var hasContext = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
    var viewShouldUpdate = arguments.length > 7 ? arguments[7] : undefined;

    _classCallCheck(this, SelectionBasedNodeView);

    _this4 = _super.call(this, node, view, getPos, portalProviderAPI, reactComponentProps, reactComponent, hasContext, viewShouldUpdate);

    _this4.isSelectionInsideNode = function (from, to, pos, posEnd) {
      pos = typeof pos !== 'number' ? _this4.pos : pos;
      posEnd = typeof posEnd !== 'number' ? _this4.posEnd : posEnd;

      if (typeof pos !== 'number' || typeof posEnd !== 'number') {
        return false;
      }

      return pos < from && to < posEnd;
    };

    _this4.isSelectedNode = function (selection) {
      if (selection instanceof _prosemirrorState.NodeSelection) {
        var _this4$view$state$sel = _this4.view.state.selection,
            from = _this4$view$state$sel.from,
            to = _this4$view$state$sel.to;
        return selection.node === _this4.node || // If nodes are not the same object, we check if they are referring to the same document node
        _this4.pos === from && _this4.posEnd === to && selection.node.eq(_this4.node);
      }

      return false;
    };

    _this4.insideSelection = function () {
      var _this4$view$state$sel2 = _this4.view.state.selection,
          from = _this4$view$state$sel2.from,
          to = _this4$view$state$sel2.to;
      return _this4.isSelectedNode(_this4.view.state.selection) || _this4.isSelectionInsideNode(from, to);
    };

    _this4.onSelectionChange = function () {
      _this4.update(_this4.node, []);
    };

    _this4.updatePos();

    _this4.oldSelection = view.state.selection;
    _this4.selectionChangeState = _reactNodeView.stateKey.getState(_this4.view.state);

    _this4.selectionChangeState.subscribe(_this4.onSelectionChange);

    return _this4;
  }
  /**
   * Update current node's start and end positions.
   *
   * Prefer `this.pos` rather than getPos(), because calling getPos is
   * expensive, unless you know you're definitely going to render.
   */


  _createClass(SelectionBasedNodeView, [{
    key: "updatePos",
    value: function updatePos() {
      if (typeof this.getPos === 'boolean') {
        return;
      }

      this.pos = this.getPos();
      this.posEnd = this.pos + this.node.nodeSize;
    }
  }, {
    key: "viewShouldUpdate",
    value: function viewShouldUpdate(_nextNode) {
      var selection = this.view.state.selection; // update selection

      var oldSelection = this.oldSelection;
      this.oldSelection = selection; // update cached positions

      var oldPos = this.pos,
          oldPosEnd = this.posEnd;
      this.updatePos();
      var from = selection.from,
          to = selection.to;
      var oldFrom = oldSelection.from,
          oldTo = oldSelection.to;

      if (this.node.type.spec.selectable) {
        var newNodeSelection = selection instanceof _prosemirrorState.NodeSelection && selection.from === this.pos;
        var oldNodeSelection = oldSelection instanceof _prosemirrorState.NodeSelection && oldSelection.from === this.pos;

        if (newNodeSelection && !oldNodeSelection || oldNodeSelection && !newNodeSelection) {
          return true;
        }
      }

      var movedInToSelection = this.isSelectionInsideNode(from, to) && !this.isSelectionInsideNode(oldFrom, oldTo);
      var movedOutOfSelection = !this.isSelectionInsideNode(from, to) && this.isSelectionInsideNode(oldFrom, oldTo);
      var moveOutFromOldSelection = this.isSelectionInsideNode(from, to, oldPos, oldPosEnd) && !this.isSelectionInsideNode(from, to);

      if (movedInToSelection || movedOutOfSelection || moveOutFromOldSelection) {
        return true;
      }

      return false;
    }
  }, {
    key: "destroy",
    value: function destroy() {
      this.selectionChangeState.unsubscribe(this.onSelectionChange);

      _get(_getPrototypeOf(SelectionBasedNodeView.prototype), "destroy", this).call(this);
    }
  }]);

  return SelectionBasedNodeView;
}(ReactNodeView);

exports.SelectionBasedNodeView = SelectionBasedNodeView;