// packages/block-library/src/utils/hooks.js
import { useSelect } from "@wordpress/data";
import { useLayoutEffect, useEffect, useRef } from "@wordpress/element";
import { getBlobByURL, isBlobURL, revokeBlobURL } from "@wordpress/blob";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { store as coreStore } from "@wordpress/core-data";
import { useViewportMatch } from "@wordpress/compose";
function useCanEditEntity(kind, name, recordId) {
  return useSelect(
    (select) => select(coreStore).canUser("update", {
      kind,
      name,
      id: recordId
    }),
    [kind, name, recordId]
  );
}
function useUploadMediaFromBlobURL(args = {}) {
  const latestArgsRef = useRef(args);
  const hasUploadStartedRef = useRef(false);
  const { getSettings } = useSelect(blockEditorStore);
  useLayoutEffect(() => {
    latestArgsRef.current = args;
  });
  useEffect(() => {
    if (hasUploadStartedRef.current) {
      return;
    }
    if (!latestArgsRef.current.url || !isBlobURL(latestArgsRef.current.url)) {
      return;
    }
    const file = getBlobByURL(latestArgsRef.current.url);
    if (!file) {
      return;
    }
    const { url, allowedTypes, onChange, onError } = latestArgsRef.current;
    const { mediaUpload } = getSettings();
    if (!mediaUpload) {
      return;
    }
    hasUploadStartedRef.current = true;
    mediaUpload({
      filesList: [file],
      allowedTypes,
      onFileChange: ([media]) => {
        if (isBlobURL(media?.url)) {
          return;
        }
        revokeBlobURL(url);
        onChange(media);
        hasUploadStartedRef.current = false;
      },
      onError: (message) => {
        revokeBlobURL(url);
        onError(message);
        hasUploadStartedRef.current = false;
      }
    });
  }, [getSettings]);
}
function useDefaultAvatar() {
  const { avatarURL: defaultAvatarUrl } = useSelect((select) => {
    const { getSettings } = select(blockEditorStore);
    const { __experimentalDiscussionSettings } = getSettings();
    return __experimentalDiscussionSettings;
  });
  return defaultAvatarUrl;
}
function useToolsPanelDropdownMenuProps() {
  const isMobile = useViewportMatch("medium", "<");
  return !isMobile ? {
    popoverProps: {
      placement: "left-start",
      // For non-mobile, inner sidebar width (248px) - button width (24px) - border (1px) + padding (16px) + spacing (20px)
      offset: 259
    }
  } : {};
}
export {
  useCanEditEntity,
  useDefaultAvatar,
  useToolsPanelDropdownMenuProps,
  useUploadMediaFromBlobURL
};
//# sourceMappingURL=hooks.js.map
