import { BindingError } from "@contember/react-binding";
import * as Slate from "slate";
import { Element } from "slate";
import { overrideCreateElementReference } from "./overrideCreateElementReference.js";
import { overrideInsertBreak } from "./overrideInsertBreak.js";
import { overrideInsertData } from "./overrideInsertData.js";
import { overrideInsertElementWithReference } from "./overrideInsertElementWithReference.js";
import { overrideInsertNode } from "./overrideInsertNode.js";
import { overrideRenderElement } from "./overrideRenderElement.js";
import { paragraphElementType } from "../../plugins/element/paragraphs/ParagraphElement.js";
import { initializeEditor } from "../../editorFactory/createEditor.js";
import { createReferenceElementPlugin } from "../elements/ReferenceElement.js";
const initBlockEditor = ({ editor, ...options }) => {
  if (options.plugins && options.plugins.indexOf(paragraphElementType) === -1) {
    throw new BindingError(`The block editor plugin set must include the paragraph plugin!`);
  }
  return initializeEditor({
    editor,
    plugins: options.plugins,
    augmentEditor: options.augmentEditor,
    augmentEditorBuiltins: options.augmentEditorBuiltins,
    addEditorBuiltins: (editor2) => {
      const e = editor2;
      e.registerElement(createReferenceElementPlugin(options));
      e.insertElementWithReference = () => {
        throw new BindingError(
          `BlockEditor: trying to insert a referenced element but referencing has not been correctly set up. Check the BlockEditor props.`
        );
      };
      e.getReferencedEntity = () => {
        throw new BindingError(
          `BlockEditor: trying to access a referenced entity but referencing has not been correctly set up. Check the BlockEditor props.`
        );
      };
      const { upgradeFormatBySingleVersion } = e;
      e.upgradeFormatBySingleVersion = (node, oldVersion) => {
        if (oldVersion !== 0 || !Element.isElement(node)) {
          return upgradeFormatBySingleVersion(node, oldVersion);
        }
        if (node.type === "embed" || node.type === "blockReference" || node.type === "blockVoidReference") {
          return {
            ...node,
            type: "reference",
            children: node.children.map((child) => editor2.upgradeFormatBySingleVersion(child, oldVersion))
          };
        }
        return upgradeFormatBySingleVersion(node, oldVersion);
      };
      e.slate = Slate;
      overrideCreateElementReference(e, options);
      overrideInsertBreak(e);
      overrideInsertData(e, options);
      overrideInsertElementWithReference(e, options);
      overrideInsertNode(e);
      overrideRenderElement(e);
      return e;
    }
  });
};
export {
  initBlockEditor
};
//# sourceMappingURL=initBlockEditor.js.map
