"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const Slate = require("slate");
const index = require("../../../ContemberEditor/index.cjs");
const HeadingElement = require("./HeadingElement.cjs");
const HeadingHtmlDeserializer = require("./HeadingHtmlDeserializer.cjs");
const ReferenceElement = require("../../../blockEditor/elements/ReferenceElement.cjs");
const withHeadings = (editor) => {
  const {
    canToggleElement,
    insertBreak,
    deleteBackward
  } = editor;
  editor.registerElement(HeadingElement.headingElementPlugin);
  editor.htmlDeserializer.registerPlugin(HeadingHtmlDeserializer.headingHtmlDeserializer);
  editor.canToggleElement = (elementType, suchThat) => {
    if (elementType !== HeadingElement.headingElementType) {
      return canToggleElement(elementType, suchThat);
    }
    if (!editor.selection) {
      return false;
    }
    const closestBlockEntry = index.ContemberEditor.closestBlockEntry(editor);
    if (closestBlockEntry === void 0) {
      return true;
    }
    const [closestBlockElement] = closestBlockEntry;
    return Slate.Element.isElement(closestBlockElement) && (editor.isDefaultElement(closestBlockElement) || HeadingElement.isHeadingElement(closestBlockElement) || ReferenceElement.isReferenceElement(closestBlockElement));
  };
  editor.insertBreak = () => {
    Slate.Editor.withoutNormalizing(editor, () => {
      insertBreak();
      const { selection } = editor;
      if (selection === null || Slate.Range.isExpanded(selection)) {
        return;
      }
      const [topLevelElement, path] = Slate.Editor.node(editor, selection, {
        depth: 1
      });
      if (HeadingElement.isHeadingElement(topLevelElement) && Slate.Editor.isEmpty(editor, topLevelElement)) {
        HeadingElement.ejectHeadingElement(editor, path);
      }
    });
  };
  editor.deleteBackward = (unit) => {
    const selection = editor.selection;
    if (unit !== "character" || !selection || !Slate.Range.isCollapsed(selection) || selection.focus.offset !== 0) {
      return deleteBackward(unit);
    }
    const closestNumberedEntry = Slate.Editor.above(editor, {
      match: (node) => Slate.Element.isElement(node) && HeadingElement.isHeadingElement(node, { isNumbered: true })
    });
    if (closestNumberedEntry === void 0) {
      return deleteBackward(unit);
    }
    const [, headingPath] = closestNumberedEntry;
    const headingStartPoint = Slate.Editor.start(editor, headingPath);
    if (!Slate.Point.equals(headingStartPoint, selection.focus)) {
      return deleteBackward(unit);
    }
    Slate.Transforms.setNodes(
      editor,
      { isNumbered: null },
      // null removes the key altogether
      { at: headingPath }
    );
  };
  return editor;
};
exports.withHeadings = withHeadings;
//# sourceMappingURL=withHeadings.cjs.map
