"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _slate = require("slate");
var _constants = require("../../constants");
var _core = require("../../core");
var _elementTypes = require("../../constants/element-types");
const HR_PATTERNS = ['---', '***', '___'];
const withDivider = editor => {
  const {
    isVoid,
    insertText,
    normalizeNode
  } = editor;
  const newEditor = editor;
  newEditor.isVoid = element => {
    const {
      type
    } = element;
    if (type === _constants.ELementTypes.DIVIDER) return true;
    return isVoid(element);
  };
  newEditor.insertText = text => {
    const {
      selection
    } = newEditor;
    if (!selection || !_slate.Range.isCollapsed(selection)) {
      insertText(text);
      return;
    }
    const [blockEntry] = _slate.Editor.nodes(newEditor, {
      at: selection,
      match: n => _slate.Element.isElement(n) && n.type === _constants.ELementTypes.PARAGRAPH
    });
    if (!blockEntry) {
      insertText(text);
      return;
    }
    const [blockNode, blockPath] = blockEntry;
    const blockText = _slate.Node.string(blockNode);
    const nextText = blockText + text;
    if (HR_PATTERNS.includes(nextText)) {
      _slate.Editor.withoutNormalizing(newEditor, () => {
        _slate.Transforms.removeNodes(newEditor, {
          at: blockPath
        });
        _slate.Transforms.insertNodes(newEditor, (0, _core.generateEmptyElement)(_constants.ELementTypes.DIVIDER), {
          at: blockPath
        });
        const nextPath = _slate.Path.next(blockPath);
        _slate.Transforms.insertNodes(newEditor, (0, _core.generateEmptyElement)(_constants.ELementTypes.PARAGRAPH), {
          at: nextPath
        });
        _slate.Transforms.select(newEditor, _slate.Editor.start(newEditor, nextPath));
      });
      return;
    }
    return insertText(text);
  };
  newEditor.normalizeNode = _ref => {
    let [node, path] = _ref;
    if (node.type === _elementTypes.DIVIDER) {
      const isLast = (0, _core.isLastNode)(newEditor, node);
      if (isLast) {
        const paragraph = (0, _core.generateEmptyElement)(_elementTypes.PARAGRAPH);
        _slate.Transforms.insertNodes(newEditor, paragraph, {
          at: [path[0] + 1]
        });
        return;
      }
      const isFirst = (0, _core.isFirstNode)(newEditor, node);
      if (isFirst) {
        const paragraph = (0, _core.generateEmptyElement)(_elementTypes.PARAGRAPH);
        _slate.Transforms.insertNodes(newEditor, paragraph, {
          at: [path[0]]
        });
        return;
      }
    }
    return normalizeNode([node, path]);
  };
  return newEditor;
};
var _default = exports.default = withDivider;