import { Range, Editor, Text, Element, Node, Transforms } from "slate";
import { horizontalRuleElementPlugin, horizontalRuleElementType } from "./HorizontalRuleElement.js";
const withHorizontalRules = (editor) => {
  const { insertText } = editor;
  editor.registerElement(horizontalRuleElementPlugin);
  editor.insertText = (text) => {
    insertText(text);
    if (text !== "-") {
      return;
    }
    const selection = editor.selection;
    if (!selection || !Range.isCollapsed(selection)) {
      return;
    }
    const focusPoint = selection.focus;
    if (focusPoint.offset < 3) {
      return;
    }
    const [targetTextNode, targetPath] = Editor.node(editor, focusPoint);
    if (!Text.isText(targetTextNode)) {
      return;
    }
    const slice = targetTextNode.text.slice(focusPoint.offset - 3, focusPoint.offset);
    if (slice !== "---") {
      return;
    }
    Editor.withoutNormalizing(editor, () => {
      let closestBlockEntry = Editor.above(editor, {
        at: focusPoint,
        mode: "lowest",
        match: (matchedNode) => Element.isElement(matchedNode) && !editor.isInline(matchedNode) && editor.isDefaultElement(matchedNode)
      });
      if (!closestBlockEntry) {
        return;
      }
      const [closestBlock, closestBlockPath] = closestBlockEntry;
      if (closestBlockPath.length !== 1 || Node.string(closestBlock) !== "---") {
        return;
      }
      const horizontalRule = {
        type: horizontalRuleElementType,
        children: [{ text: "" }]
      };
      const newHrPath = [...closestBlockPath.slice(0, -1), closestBlockPath[closestBlockPath.length - 1] + 1];
      Transforms.insertNodes(editor, horizontalRule, {
        at: newHrPath
      });
      editor.deleteBackward("character");
      editor.deleteBackward("character");
      editor.deleteBackward("character");
      const pointAfter = Editor.after(editor, newHrPath);
      if (pointAfter) {
        Transforms.select(editor, pointAfter);
      } else {
        const targetPath2 = [...newHrPath.slice(0, -1), newHrPath[newHrPath.length - 1] + 1];
        Transforms.insertNodes(editor, editor.createDefaultElement([{ text: "" }]), {
          at: targetPath2,
          select: true
        });
      }
      closestBlockEntry = Editor.node(editor, closestBlockPath);
      if (!closestBlockEntry) {
        return;
      }
      Transforms.removeNodes(editor, {
        at: closestBlockEntry[1]
      });
    });
  };
  return editor;
};
export {
  withHorizontalRules
};
//# sourceMappingURL=withHorizontalRules.js.map
