import { Editor } from "slate";
import { useBindingOperations, generateUuid } from "@contember/react-binding";
import { useCallback } from "react";
import { useGetReferenceEntityList } from "./useGetReferenceEntityList.js";
const useCreateElementReference = ({ monolithicReferencesMode, sortedBlocksRef, referenceDiscriminationField, referencesField, refreshBlocks }) => {
  const getReferenceList = useGetReferenceEntityList({ monolithicReferencesMode, sortedBlocksRef, referencesField });
  return useCreateElementReferenceInternal({
    referenceDiscriminationField,
    getReferenceList,
    refreshBlocks
  });
};
const useCreateElementReferenceInternal = ({ referenceDiscriminationField, getReferenceList, refreshBlocks }) => {
  const bindingOperations = useBindingOperations();
  return useCallback((editor, path, referenceDiscriminant, initialize) => {
    const referenceUuid = generateUuid();
    refreshBlocks();
    const references = getReferenceList(path);
    Editor.withoutNormalizing(editor, () => {
      bindingOperations.batchDeferredUpdates(() => {
        const innerInitialize = (getNewReference, options) => {
          getNewReference().getField("id").updateValue(referenceUuid);
          getNewReference().getField(referenceDiscriminationField).updateValue(referenceDiscriminant);
          initialize?.(getNewReference, options);
        };
        references.createNewEntity(innerInitialize);
      });
    });
    return references.getChildEntityById(referenceUuid);
  }, [bindingOperations, getReferenceList, referenceDiscriminationField, refreshBlocks]);
};
export {
  useCreateElementReference
};
//# sourceMappingURL=useCreateElementReference.js.map
