import { Editor, Range, Transforms, Path, Node, Point } from "slate";
import { ContemberEditor } from "../../ContemberEditor/index.js";
import { isReferenceElement } from "../elements/ReferenceElement.js";
const prepareElementForInsertion = (editor, node) => {
  const selection = editor.selection;
  let targetLocation;
  if (selection) {
    targetLocation = selection;
  } else if (editor.children.length) {
    targetLocation = Editor.end(editor, []);
  } else {
    targetLocation = { path: [], offset: 0 };
  }
  if (Range.isRange(targetLocation)) {
    if (Range.isExpanded(targetLocation)) {
      const [, end2] = Range.edges(targetLocation);
      const pointRef = Editor.pointRef(editor, end2);
      Transforms.delete(editor, { at: targetLocation });
      targetLocation = pointRef.unref();
    } else {
      targetLocation = targetLocation.focus;
    }
  }
  const targetPoint = targetLocation;
  if (!isReferenceElement(node)) {
    if (targetPoint.offset === 0) {
      return targetPoint.path;
    }
    Transforms.splitNodes(editor, {
      at: targetPoint
    });
    return Path.next(targetPoint.path);
  }
  const [closestBlockElement, closestBlockPath] = ContemberEditor.closestBlockEntry(editor, {
    at: targetPoint
  });
  if (editor.canContainAnyBlocks(closestBlockElement)) {
    return targetPoint.path;
  }
  if (isReferenceElement(closestBlockElement)) {
    const newPath = Path.next(closestBlockPath);
    Promise.resolve().then(() => {
      Transforms.select(editor, newPath);
    });
    return newPath;
  }
  if (Node.string(closestBlockElement) === "") {
    Transforms.removeNodes(editor, {
      at: closestBlockPath
    });
    return closestBlockPath;
  }
  const [start, end] = Editor.edges(editor, closestBlockPath);
  if (Point.equals(start, targetPoint)) {
    return closestBlockPath;
  } else if (Point.equals(end, targetPoint)) {
    return Path.next(closestBlockPath);
  } else {
    Transforms.splitNodes(editor, {
      at: targetPoint
    });
    return Path.next(Path.parent(targetPoint.path));
  }
};
export { prepareElementForInsertion };
//# sourceMappingURL=prepareElementForInsertion.js.map
