"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _loading = _interopRequireDefault(require("../containers/loading"));
var _slateConvert = require("../slate-convert");
var _useMathjax = _interopRequireDefault(require("../hooks/use-mathjax"));
var _simpleSlateEditor = _interopRequireDefault(require("../editors/simple-slate-editor"));
var _inlineEditor = _interopRequireDefault(require("../editors/inline-editor"));
const SimpleEditor = /*#__PURE__*/(0, _react.forwardRef)((_ref, ref) => {
  let {
    isInline,
    isFetching,
    autoFocus,
    value,
    focusEnd = false,
    editorApi,
    mathJaxSource,
    onSave: propsOnSave,
    onContentChanged: propsOnContentChanged,
    ...otherProps
  } = _ref;
  const [richValue, setRichValue] = (0, _react.useState)([]);
  const [isLoading, setIsLoading] = (0, _react.useState)(true);
  const {
    isLoadingMathJax
  } = (0, _useMathjax.default)(mathJaxSource);
  const editorRef = (0, _react.useRef)();
  (0, _react.useImperativeHandle)(ref, () => {
    var _editorRef$current;
    return {
      getValue: () => {
        const mdStringValue = (0, _slateConvert.slateToMdString)(richValue);
        return mdStringValue;
      },
      getSlateValue: () => {
        return richValue;
      },
      getEditor: ((_editorRef$current = editorRef.current) === null || _editorRef$current === void 0 ? void 0 : _editorRef$current.getEditor) || (() => null)
    };
  }, [richValue, editorRef]);
  (0, _react.useEffect)(() => {
    if (!isFetching) {
      const richValue = (0, _slateConvert.mdStringToSlate)(value);
      setRichValue(richValue);
      setIsLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isFetching]);
  const onContentChanged = (0, _react.useCallback)(content => {
    setRichValue(content);
    propsOnContentChanged && propsOnContentChanged(content);
  }, [propsOnContentChanged]);
  const props = {
    isSupportFormula: !!mathJaxSource,
    value: richValue,
    focusEnd,
    autoFocus,
    editorApi: editorApi,
    onSave: propsOnSave,
    onContentChanged: onContentChanged,
    ...otherProps
  };
  if (isFetching || isLoading || isLoadingMathJax) {
    return /*#__PURE__*/_react.default.createElement(_loading.default, null);
  }
  if (isInline) {
    return /*#__PURE__*/_react.default.createElement(_inlineEditor.default, Object.assign({}, props, {
      ref: editorRef
    }));
  }
  return /*#__PURE__*/_react.default.createElement(_simpleSlateEditor.default, Object.assign({}, props, {
    ref: editorRef
  }));
});
var _default = exports.default = SimpleEditor;