import { useDesugaredRelativeSingleField, BindingError } from "@contember/binding";
import { Editor } from "slate";
const useBlockEditorSlateNodes = ({
  editor,
  blockElementCache,
  blockElementPathRefs,
  blockContentField,
  topLevelBlocks
}) => {
  const desugaredContentField = useDesugaredRelativeSingleField(blockContentField);
  if (editor.operations.length) {
    return editor.children;
  }
  const topLevelBlockElements = topLevelBlocks.length ? topLevelBlocks.map((entity, index) => {
    const existingBlockElement = blockElementCache.get(entity);
    const blockPathRef = blockElementPathRefs.get(entity.id);
    if (blockPathRef === void 0) {
      blockElementPathRefs.set(entity.id, Editor.pathRef(editor, [index], { affinity: "backward" }));
    } else {
      const current = blockPathRef.current;
      if (current === null || current.length !== 1 || current[0] !== index) {
        blockPathRef.unref();
        blockElementPathRefs.set(entity.id, Editor.pathRef(editor, [index], { affinity: "backward" }));
      }
    }
    if (existingBlockElement) {
      return existingBlockElement;
    }
    const contentField = entity.getRelativeSingleField(desugaredContentField);
    let blockElement;
    if (contentField.value === null || contentField.value === "") {
      blockElement = editor.createDefaultElement([{ text: "" }]);
    } else if (typeof contentField.value !== "string") {
      throw new BindingError(`BlockEditor: The 'textBlockField' does not contain a string value.`);
    } else {
      blockElement = editor.deserializeNodes(contentField.value, `BlockEditor: The 'contentField' of a block contains invalid data.`)[0];
    }
    blockElementCache.set(entity, blockElement);
    return blockElement;
  }) : [
    editor.createDefaultElement([{ text: "" }])
  ];
  return topLevelBlockElements;
};
export { useBlockEditorSlateNodes };
//# sourceMappingURL=useBlockEditorSlateNodes.js.map
