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