import { useDesugaredRelativeSingleField, useEntityBeforeUpdate } from "@contember/react-binding";
import { useState, useCallback } from "react";
import { Element } from "slate";
const useBlockElementCache = ({ editor, blockList, sortableBy, contentField }) => {
  const [blockElementCache] = useState(() => /* @__PURE__ */ new WeakMap());
  const desugaredSortableByField = useDesugaredRelativeSingleField(sortableBy);
  const desugaredBlockContentField = useDesugaredRelativeSingleField(contentField);
  useEntityBeforeUpdate(
    useCallback(
      (getAccessor) => {
        const hasPendingOperations = !!editor.operations.length;
        if (hasPendingOperations) {
          return;
        }
        for (const blockEntity of getAccessor().getEntityList(blockList)) {
          const cachedElement = blockElementCache.get(blockEntity);
          if (cachedElement !== void 0) {
            continue;
          }
          const blockIndex = blockEntity.getRelativeSingleField(desugaredSortableByField).value;
          if (editor.children.length < blockIndex) {
            continue;
          }
          const previousNode = editor.children[blockIndex];
          const contentField2 = blockEntity.getRelativeSingleField(desugaredBlockContentField);
          const currentNode = editor.deserializeNodes(
            contentField2.value,
            `BlockEditor: The 'contentField' of a block contains invalid data.`
          )[0];
          if (Element.isElement(previousNode) && JSON.stringify(previousNode) === JSON.stringify(currentNode)) {
            blockElementCache.set(blockEntity, previousNode);
          }
        }
      },
      [blockElementCache, blockList, desugaredBlockContentField, desugaredSortableByField, editor]
    )
  );
  return blockElementCache;
};
export {
  useBlockElementCache
};
//# sourceMappingURL=useBlockElementCache.js.map
