"use strict";

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

var _prosemirrorDevTools = _interopRequireDefault(require("prosemirror-dev-tools"));

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

var _prosemirrorModel = require("prosemirror-model");

var _prosemirrorTransform = require("prosemirror-transform");

var _prosemirrorView = require("prosemirror-view");

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

var _convertFromJSON = _interopRequireDefault(require("../convertFromJSON"));

var _RichTextEditor = _interopRequireDefault(require("../ui/RichTextEditor"));

var _uuid = _interopRequireDefault(require("../uuid"));

var _SimpleConnector = _interopRequireDefault(require("./SimpleConnector"));

var _CollabConnector = _interopRequireDefault(require("./CollabConnector"));

var _createEmptyEditorState = require("../createEmptyEditorState");

var _createPopUp = _interopRequireDefault(require("../ui/createPopUp"));

var _PopUpPosition = require("../ui/PopUpPosition");

var _AlertInfo = _interopRequireDefault(require("../ui/AlertInfo"));

var _licitDocAttrsStep = require("@modusoperandi/licit-doc-attrs-step");

require("./licit.css");

var _buildEditorPlugins = _interopRequireDefault(require("../buildEditorPlugins"));

var _EditorMarks = _interopRequireDefault(require("../EditorMarks"));

var _EditorNodes = _interopRequireDefault(require("../EditorNodes"));

var _Types = require("../Types");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

const ATTR_OBJID = 'objectId';
const ATTR_OBJMETADATA = 'objectMetaData';
/**
 * LICIT properties:
 *  docID {number} [0] Collaborative Doument ID
 *  debug {boolean} [false] To enable/disable ProseMirror Debug Tools, available only in development.
 *  width {string} [100%] Width of the editor.
 *  height {height} [100%] Height of the editor.
 *  readOnly {boolean} [false] To enable/disable editing mode.
 *  onChange {@callback} [null] Fires after each significant change.
 *      @param data {JSON} Modified document data.
 *  onReady {@callback} [null] Fires when the editor is fully ready.
 *      @param ref {LICIT} Rerefence of the editor.
 *  data {JSON} [null] Document data to be loaded into the editor.
 *  disabled {boolean} [false] Disable the editor.
 *  embedded {boolean} [false] Disable/Enable inline behaviour.
 *  plugins [plugins] External Plugins into the editor.
 */

class Licit extends React.Component {
  // This will be handy in updating document's content.
  // Flag to decide whether to skip shouldComponentUpdate

  /**
   * Provides access to prosemirror view.
   */
  get editorView() {
    return this._editorView;
  }

  constructor(_props, context) {
    var _this;

    super(_props, context);
    _this = this;

    _defineProperty(this, "_runtime", void 0);

    _defineProperty(this, "_connector", void 0);

    _defineProperty(this, "_clientID", void 0);

    _defineProperty(this, "_editorView", void 0);

    _defineProperty(this, "_skipSCU", void 0);

    _defineProperty(this, "_defaultEditorSchema", void 0);

    _defineProperty(this, "_defaultEditorPlugins", void 0);

    _defineProperty(this, "_popUp", null);

    _defineProperty(this, "setContent", function () {
      let content = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      const {
        doc,
        schema
      } = _this._connector.getState();

      let {
        tr
      } = _this._connector.getState();

      const document = content ? schema.nodeFromJSON(content) : schema.nodeFromJSON(_createEmptyEditorState.EMPTY_DOC_JSON);

      const selection = _prosemirrorState.TextSelection.create(doc, 0, doc.content.size);

      tr = tr.setSelection(selection).replaceSelectionWith(document, false); // [FS] IRAD-1092 2020-12-03
      // set the value for object metadata  and objectId

      tr = _this.isNodeHasAttribute(document, ATTR_OBJMETADATA) ? tr.step(new _licitDocAttrsStep.SetDocAttrStep(ATTR_OBJMETADATA, document.attrs.objectMetaData)) : tr;
      tr = _this.isNodeHasAttribute(document, ATTR_OBJID) ? tr.step(new _licitDocAttrsStep.SetDocAttrStep(ATTR_OBJID, document.attrs.objectId)) : tr;
      _this._skipSCU = true;

      _this._editorView.dispatch(tr);
    });

    _defineProperty(this, "_onChange", data => {
      const {
        transaction
      } = data;
      /*
       ** ProseMirror Debug Tool's Snapshot creates a new state and sets that to editor view's state.
       ** This results in the connector's state as an orphan and thus transaction mismatch error.
       ** To resolve check and update the connector's state to keep in sync.
       */

      if (this._editorView) {
        const isSameState = this._connector._editorState == this._editorView.state;
        let invokeOnEdit = false;

        if (!isSameState) {
          this._connector._editorState = this._editorView.state;
          invokeOnEdit = true;
        } else {
          // [FS] IRAD-1264 2021-03-19
          // check if in non-collab mode.
          if (!(this._connector instanceof _CollabConnector.default)) {
            invokeOnEdit = true;
          }
        }

        if (invokeOnEdit) {
          // [FS] IRAD-1236 2020-03-05
          // Only need to call if there is any difference in collab mode OR always in non-collab mode.
          this._connector.onEdit(transaction, this._editorView);
        }

        if (transaction.docChanged) {
          const docJson = transaction.doc.toJSON();
          let isEmpty = false;

          if (docJson.content && docJson.content.length === 1) {
            if (!docJson.content[0].content || docJson.content[0].content && docJson.content[0].content[0].text && '' === docJson.content[0].content[0].text.trim()) {
              isEmpty = true;
            }
          } // setCFlags is/was always the opposite of isEmpty.


          if (isEmpty) {
            this.resetCounters(transaction);
          } else {
            this.setCounterFlags(transaction, false);
          } // Changing 2nd parameter from boolean to object was not in any way
          // backwards compatible. Any conditional logic placed on isEmpty was
          // broken. Reverting that change, then adding view as a 3rd parameter.


          this.state.onChangeCB(docJson, isEmpty, this._editorView);
          this.closeOpenedPopupModels();
        }
      }
    });

    _defineProperty(this, "_onReady", editorView => {
      // [FS][06-APR-2020][IRAD-922]
      // Showing focus in the editor.
      const {
        state,
        dispatch
      } = editorView;
      this._editorView = editorView;
      const tr = state.tr;
      const doc = state.doc;
      const trx = tr.setSelection(_prosemirrorState.TextSelection.create(doc, 0, doc.content.size));
      dispatch(trx.scrollIntoView());
      editorView.focus();

      if (this.state.onReadyCB) {
        this.state.onReadyCB(this);
      }

      if (this.state.debug) {
        window.debugProseMirror = () => {
          (0, _prosemirrorDevTools.default)(editorView);
        };

        window.debugProseMirror();
      }
    });

    _defineProperty(this, "setProps", props => {
      if (this.state.readOnly) {
        // It should be possible to load content into the editor in readonly as well.
        // It should not be necessary to make the component writable any time during the process
        const propsCopy = {};
        this._skipSCU = true;
        Object.assign(propsCopy, props); // make writable without content change

        propsCopy.readOnly = false;
        delete propsCopy.data;
        this.setState(propsCopy);
      } // Need to go through shouldComponentUpdate lifecycle here, when updated from outside,
      // so that content is modified gracefully using transaction so that undo/redo works too.


      this._skipSCU = false;
      this.setState(props);
    });

    this.state = {
      loaded: false
    };
    setTimeout(p => this.loadStyles(p), 100, _props);
  }
  /**
   * Ensures that custom styles are loaded from server before the underlying
   * editor is rendered.  This is a band-aid method, and is necessary here
   * because other parts of the editor attempt to use styles synchronously.
   *
   * @param {*} props Editor properties passed to constructor
   */


  async loadStyles(props) {
    // Only load styles if there's a method to load them.
    if (props.runtime && props.runtime.getStylesAsync) {
      // Force preload of styles before every editor instance is created.
      await props.runtime.getStylesAsync().catch(error => {
        // Log the failure, but proceed to display editor without any styles.
        console.warn('Failed to load custom styles:', error);
      });
    }

    this.initialize(props);
  }

  initialize(props) {
    this._clientID = (0, _uuid.default)();
    this._editorView = null;
    this._skipSCU = true;

    const noop = function () {}; // [FS] IRAD-981 2020-06-10
    // Component's configurations.


    const docID = props.docID || 0; // 0 < means collaborative.

    const collaborative = 0 < docID;
    const debug = props.debug || false; // Default width and height to undefined

    const width = props.width || undefined;
    const height = props.height || undefined;
    const onChangeCB = typeof props.onChange === 'function' ? props.onChange : noop;
    const onReadyCB = typeof props.onReady === 'function' ? props.onReady : noop;
    const readOnly = props.readOnly || false;
    const data = props.data || null;
    const disabled = props.disabled || false;
    const embedded = props.embedded || false; // [FS] IRAD-996 2020-06-30
    // [FS] 2020-07-03
    // Handle Image Upload from Angular App

    const runtime = props.runtime || null;
    const plugins = props.plugins || null;
    this._defaultEditorSchema = new _prosemirrorModel.Schema({
      nodes: _EditorNodes.default,
      marks: _EditorMarks.default
    });
    this._defaultEditorPlugins = new _buildEditorPlugins.default(this._defaultEditorSchema).get();
    let editorState = (0, _convertFromJSON.default)(data, null, this._defaultEditorSchema, plugins, this._defaultEditorPlugins); // [FS] IRAD-1067 2020-09-19
    // The editorState will return null if the doc Json is mal-formed

    if (null === editorState) {
      editorState = (0, _convertFromJSON.default)(_createEmptyEditorState.EMPTY_DOC_JSON, null, this._defaultEditorSchema, plugins, this._defaultEditorPlugins);
      this.showAlert();
    }

    const setState = this.setState.bind(this);
    this._connector = collaborative ? new _CollabConnector.default(editorState, setState, {
      docID
    }, this._defaultEditorSchema, this._defaultEditorPlugins) : new _SimpleConnector.default(editorState, setState);
    const loaded = true; // FS IRAD-989 2020-18-06
    // updating properties should automatically render the changes

    this.setState({
      docID,
      data,
      editorState,
      width,
      height,
      readOnly,
      onChangeCB,
      onReadyCB,
      debug,
      disabled,
      embedded,
      runtime,
      loaded
    }); // FS IRAD-1040 2020-26-08
    // Get the modified schema from editorstate and send it to collab server

    if (this._connector.updateSchema) {
      // Use known editorState to update schema.
      this._connector.updateSchema(editorState.schema);
    }
  } // [FS] IRAD-1067 2020-09-19
  // Alert funtion to show document is corrupted


  showAlert() {
    const anchor = null;
    this._popUp = (0, _createPopUp.default)(_AlertInfo.default, null, {
      anchor,
      position: _PopUpPosition.atViewportCenter,
      onClose: val => {
        if (this._popUp) {
          this._popUp = null;
        }
      }
    });
  }

  resetCounters(transaction) {
    for (let index = 1; index <= 10; index++) {
      const counterVar = 'set-cust-style-counter-' + index;
      const setCounterVal = window[counterVar];

      if (setCounterVal) {
        delete window[counterVar];
      }
    }

    this.setCounterFlags(transaction, true);
  }

  setCounterFlags(transaction, reset) {
    let modified = false;
    let counterFlags = null;
    const existingCFlags = transaction.doc.attrs.counterFlags;

    if (reset && !existingCFlags) {
      return;
    }

    for (let index = 1; index <= 10; index++) {
      const counterVar = 'set-cust-style-counter-' + index;
      const setCounterVal = window[counterVar];

      if (setCounterVal) {
        if (!counterFlags) {
          counterFlags = {};
        }

        counterFlags[counterVar] = true;

        if (!existingCFlags) {
          modified = true;
        }
      }

      if (!modified) {
        if (existingCFlags) {
          if (setCounterVal) {
            modified = undefined == existingCFlags[counterVar];
          } else {
            modified = undefined != existingCFlags[counterVar];
          }
        } else {
          modified = setCounterVal;
        }
      }
    }

    if (modified) {
      const tr = this._editorView.state.tr.step(new _licitDocAttrsStep.SetDocAttrStep('counterFlags', counterFlags));

      this._editorView.dispatch(tr);
    }
  }

  getDeletedArtifactIds() {
    if (this._connector.getDeletedArtifactIds) {
      this._connector.getDeletedArtifactIds(this.state.editorState.schema);
    }
  }

  isNodeHasAttribute(node, attrName) {
    return node.attrs && node.attrs[attrName];
  }

  shouldComponentUpdate(nextProps, nextState) {
    // Only interested if properties are set from outside.
    if (!this._skipSCU) {
      this._skipSCU = false;
      let dataChanged = false; // Compare data, if found difference, update editorState

      if (this.state.data !== nextState.data) {
        dataChanged = true;
      } else if (null === nextState.data) {
        if (this.state.editorState.doc.textContent && 0 < this.state.editorState.doc.textContent.trim().length) {
          dataChanged = true;
        }
      }

      if (dataChanged) {
        // data changed, so update document content
        this.setContent(nextState.data);
      }

      if (this.state.docID !== nextState.docID) {
        // Collaborative mode changed
        const collabEditing = nextState.docID != 0;

        const editorState = this._connector.getState();

        const setState = this.setState.bind(this);
        const docID = nextState.docID || 1; // create new connector

        this._connector = collabEditing ? new _CollabConnector.default(editorState, setState, {
          docID
        }, this._defaultEditorSchema, this._defaultEditorPlugins) : new _SimpleConnector.default(editorState, setState);
      }
    }

    return true;
  }

  render() {
    if (this.state.loaded) {
      const {
        editorState,
        width,
        height,
        readOnly,
        disabled,
        embedded,
        runtime
      } = this.state; // [FS] IRAD-978 2020-06-05
      // Using 100vw & 100vh (100% viewport) is not ideal for a component which is expected to be a part of a page,
      // so changing it to 100%  width & height which will occupy the area relative to its parent.

      return /*#__PURE__*/React.createElement(_RichTextEditor.default, {
        disabled: disabled,
        editorState: editorState,
        embedded: embedded,
        height: height,
        onChange: this._onChange,
        onReady: this._onReady,
        readOnly: readOnly,
        runtime: runtime,
        width: width
      });
    } else {
      return /*#__PURE__*/React.createElement("div", null, "Loading Styles...");
    }
  }

  // [FS] IRAD-1173 2021-02-25
  // Bug fix: Transaction mismatch error when a dialog is opened and keep typing.
  closeOpenedPopupModels() {
    const element = document.getElementsByClassName('czi-pop-up-element')[0];

    if (element && element.parentElement) {
      element.parentElement.removeChild(element);
    }
  }

}

var _default = Licit;
exports.default = _default;