"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _unified = require("unified");
var _slate = require("slate");
var _remarkParse = _interopRequireDefault(require("remark-parse"));
var _remarkGfm = _interopRequireDefault(require("remark-gfm"));
var _remarkStringify = _interopRequireDefault(require("remark-stringify"));
var _remarkMath = _interopRequireDefault(require("remark-math"));
var _transform = require("./transform");
var _constants = require("../html-to-slate/constants");
const isContentValid = value => {
  if (!value || !Array.isArray(value)) return false;
  return true;
};
const isEmptyParagraph = node => {
  const voidNodeTypes = ['image', 'column', 'formula'];
  if (node.type !== _constants.PARAGRAPH) return false;
  const hasBlock = node.children.some(item => voidNodeTypes.includes(item.type));
  const hasHtml = node.children.some(item => item.type === 'html');
  if (hasBlock) return false;
  if (hasHtml) return false;
  if (_slate.Node.string(node).length !== 0) return false;
  return true;
};

// slateNode -> mdast -> mdString
const slateToMdString = value => {
  if (!isContentValid(value)) return '';
  if (value.length === 0) return '';

  // is only one empty paragraph child
  if (value.length === 1 && isEmptyParagraph(value[0])) {
    return '';
  }

  // slateNode -> mdast
  // https://github.com/syntax-tree/mdast#phrasingcontent
  const mdASTNodes = (0, _transform.formatSlateToMd)(value);
  const root = {
    type: 'root',
    children: mdASTNodes
  };

  // convert slate value to md
  const stringifyOptions = {
    rule: '-',
    ruleSpaces: false,
    bullet: '*',
    commonmarks: true,
    fences: true
  };
  const res = (0, _unified.unified)().use(_remarkParse.default).use(_remarkGfm.default).use(_remarkStringify.default, stringifyOptions).use(_remarkMath.default).stringify(root);
  return res;
};

// transform rules: https://github.com/syntax-tree/mdast
var _default = exports.default = slateToMdString;