"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _slate = require("slate");
var _core = require("../../core");
var _elementTypes = require("../../constants/element-types");
var _helper = require("../paragraph/helper");
var _constants = require("../../constants");
const withCheckList = editor => {
  const {
    insertBreak,
    deleteBackward,
    insertFragment
  } = editor;
  const newEditor = editor;
  newEditor.insertBreak = () => {
    if (!newEditor.selection) {
      insertBreak();
      return;
    }
    const checkListNode = (0, _core.getSelectedNodeByType)(newEditor, _elementTypes.CHECK_LIST_ITEM);
    if (!checkListNode) {
      insertBreak();
      return;
    }
    const nodeText = _slate.Node.string(checkListNode);
    if (nodeText.length === 0) {
      (0, _helper.transformToParagraph)(newEditor);
    } else {
      _slate.Transforms.splitNodes(newEditor, {
        always: true
      });
    }
  };
  newEditor.deleteBackward = unit => {
    const {
      selection
    } = newEditor;
    if (selection && _slate.Range.isCollapsed(selection)) {
      const selectedCheckListNode = (0, _core.getSelectedNodeByType)(newEditor, _elementTypes.CHECK_LIST_ITEM);
      if (selectedCheckListNode && (0, _core.isSelectionAtBlockStart)(editor)) {
        (0, _helper.transformToParagraph)(newEditor);
        return;
      }
    }
    deleteBackward(unit);
  };
  newEditor.insertFragment = fragment => {
    const match = {
      type: [_elementTypes.CHECK_LIST_ITEM]
    };
    const [checkListEntry] = (0, _core.getNodeEntries)(newEditor, {
      match
    });
    if (!checkListEntry) return insertFragment(fragment);
    const firstChild = fragment[0];
    if (fragment.length === 1 && _constants.LIST_TYPE_ARRAY.includes(firstChild.type)) {
      // insert text
      if (firstChild.children.length === 1) {
        const text = _slate.Node.string(fragment[0]);
        (0, _slate.insertText)(text);
        return;
      }

      // insert list at current path
      if ((0, _core.isSelectionAtBlockStart)(editor)) {
        _slate.Transforms.insertNodes(newEditor, fragment);
        return;
      }

      // insert list at next path
      const nextPath = _slate.Path.next(checkListEntry[1]);
      _slate.Transforms.insertNodes(newEditor, fragment, {
        at: nextPath
      });
      return;
    }
    if (fragment.length === 1 && firstChild.type === _elementTypes.TABLE) {
      const nextPath = _slate.Path.next(checkListEntry[1]);
      _slate.Transforms.insertNodes(newEditor, fragment, {
        at: nextPath
      });
      return;
    }
    return insertFragment(fragment);
  };
  return newEditor;
};
var _default = exports.default = withCheckList;