"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 = MarkdownViewer;
var _react = _interopRequireWildcard(require("react"));
var _loading = _interopRequireDefault(require("../containers/loading"));
var _slateConvert = require("../slate-convert");
var _useMathjax = _interopRequireDefault(require("../hooks/use-mathjax"));
var _slateViewer = _interopRequireDefault(require("../editors/slate-viewer"));
/**
 *
 * @param {
 *   options: {
 *     loading: {
 *       render: Custom loading renderer,
 *       ... // others
 *     },
 *     [ELementTypes.LINK_REFERENCE]: {
 *       render: Custom LinkReference renderer
 *     },
 *     ... // others
 *   }
 * }
 * @returns SlateViewer
 */

function MarkdownViewer(_ref) {
  let {
    isFetching,
    isShowLoading = true,
    value,
    mathJaxSource,
    isShowOutline,
    scrollRef,
    onLinkClick,
    beforeRenderCallback,
    options
  } = _ref;
  const [richValue, setRichValue] = (0, _react.useState)([]);
  const [isLoading, setIsLoading] = (0, _react.useState)(Boolean(isShowLoading));
  const {
    isLoadingMathJax
  } = (0, _useMathjax.default)(mathJaxSource);
  (0, _react.useEffect)(() => {
    if (!isFetching) {
      if (isShowLoading) {
        setIsLoading(true);
      }
      const richValue = (0, _slateConvert.mdStringToSlate)(value);
      beforeRenderCallback && beforeRenderCallback(richValue);
      setRichValue(richValue);
      if (isShowLoading) {
        setTimeout(() => {
          setIsLoading(false);
        }, 0);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isFetching, value, isShowLoading]);
  const props = {
    options,
    isSupportFormula: !!mathJaxSource,
    value: richValue,
    isShowOutline: isShowOutline,
    scrollRef: scrollRef,
    onLinkClick: onLinkClick
  };
  if (isShowLoading && (isFetching || isLoading || isLoadingMathJax)) {
    const loadingOption = (options === null || options === void 0 ? void 0 : options.loading) || {};
    const {
      render
    } = loadingOption || {};
    if (render && /*#__PURE__*/(0, _react.isValidElement)(render)) {
      return /*#__PURE__*/(0, _react.cloneElement)(render);
    }
    return /*#__PURE__*/_react.default.createElement(_loading.default, null);
  }
  return /*#__PURE__*/_react.default.createElement(_slateViewer.default, props);
}