import { Text, Element, Transforms } from "slate";
import { referenceElementType } from "../elements/ReferenceElement.js";
import { isInReferenceElement } from "../utils/isInReferenceElement.js";
import { parseUrl } from "../../utils/parseUrl.js";
const overrideInsertData = (editor, options) => {
  let { insertData, insertFragment } = editor;
  const stripNodeReferences = (nodes) => nodes.flatMap((node) => {
    if (Text.isText(node)) {
      return node;
    }
    if (Element.isElement(node) && "referenceId" in node) {
      return stripNodeReferences(node.children);
    }
    return {
      ...node,
      children: stripNodeReferences(node.children)
    };
  });
  editor.insertFragment = (fragment) => {
    insertFragment(stripNodeReferences(fragment));
  };
  editor.insertData = (data) => {
    if (editor.selection && isInReferenceElement(editor)) {
      const text = data.getData("text/plain").trim();
      Transforms.insertText(editor, text);
      return;
    }
    return insertData(data);
  };
  const { embedReferenceDiscriminateBy, embedHandlers, embedContentDiscriminationField } = options;
  if (embedReferenceDiscriminateBy === void 0 || embedHandlers === void 0 || embedContentDiscriminationField === void 0) {
    return;
  }
  const insertEmbed = (embedHandler, embedArtifacts, source) => {
    const partialEmbedReference = {
      type: referenceElementType,
      children: [{ text: "" }]
    };
    return editor.insertElementWithReference(partialEmbedReference, embedReferenceDiscriminateBy, (getEmbedReference) => {
      getEmbedReference().getRelativeSingleField(embedContentDiscriminationField).updateValue(embedHandler.discriminateBy);
      const reference = getEmbedReference();
      embedHandler.datum.populateEmbedData({
        embedArtifacts,
        source,
        entity: reference
      });
    });
  };
  const insertDataEmbed = editor.insertData;
  editor.insertData = (data) => {
    if (data.getData("application/x-slate-fragment")) {
      return insertDataEmbed(data);
    }
    const text = data.getData("text/plain").trim();
    if (!text) {
      return insertDataEmbed(data);
    }
    const url = parseUrl(text);
    (async () => {
      for (const [, handler] of options.embedHandlers) {
        const result = await handler.datum.handleSource(text, url);
        if (result !== void 0) {
          return insertEmbed(handler, result, text);
        }
      }
      insertDataEmbed(data);
    })();
  };
};
export { overrideInsertData };
//# sourceMappingURL=overrideInsertData.js.map
