"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = convertFromJSON;
var _prosemirrorModel = require("prosemirror-model");
var _prosemirrorState = require("prosemirror-state");
var _createEmptyEditorState = _interopRequireDefault(require("./createEmptyEditorState"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function convertFromJSON(json, schema, defaultSchema, effectivePlugins) {
  const editorSchema = schema || defaultSchema;
  let error = false;
  if (typeof json === 'string') {
    try {
      json = JSON.parse(json);
    } catch (ex) {
      console.error('convertFromJSON:', ex);
      error = true;
    }
  }
  if (!json || typeof json !== 'object') {
    console.error('convertFromJSON: invalid object', json);
    error = true;
  }
  if (error) {
    // [FS] IRAD-1455 2021-06-16
    // Use the effectivePlugins, editor hangs, b'coz of missing default core plugins
    return (0, _createEmptyEditorState.default)(schema, defaultSchema, effectivePlugins);
  }

  // [FS] IRAD-1067 2020-09-19
  // Handle gracefully when error thrown on invalid json
  let doc = null;
  try {
    doc = editorSchema.nodeFromJSON(json);
  } catch (error) {
    return null;
  }
  return _prosemirrorState.EditorState.create({
    doc: doc,
    schema: editorSchema,
    plugins: effectivePlugins
  });
}