useCopyUrl.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { useCallback } from 'react'
  2. import { toast } from 'sonner'
  3. import { copyToClipboard } from 'ui'
  4. import { URL_EXPIRY_DURATION } from '../Storage.constants'
  5. import { fetchFileUrl } from './useFetchFileUrlQuery'
  6. import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
  7. import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'
  8. export const useCopyUrl = () => {
  9. const { projectRef, selectedBucket } = useStorageExplorerStateSnapshot()
  10. const { hostEndpoint, customEndpoint } = useProjectApiUrl({ projectRef })
  11. const isCustomDomainActive = !!customEndpoint
  12. const getFileUrl = useCallback(
  13. (filePath: string, expiresIn?: URL_EXPIRY_DURATION) => {
  14. return fetchFileUrl(filePath, projectRef, selectedBucket.id, selectedBucket.public, expiresIn)
  15. },
  16. [projectRef, selectedBucket]
  17. )
  18. const onCopyUrl = useCallback(
  19. (filePath: string, expiresIn?: URL_EXPIRY_DURATION) => {
  20. const formattedUrl = getFileUrl(filePath, expiresIn).then((url) => {
  21. return isCustomDomainActive && hostEndpoint
  22. ? url.replace(hostEndpoint, customEndpoint)
  23. : url
  24. })
  25. return copyToClipboard(formattedUrl, () => {
  26. toast.success(`Copied URL for ${filePath} to clipboard.`)
  27. })
  28. },
  29. [customEndpoint, getFileUrl, hostEndpoint, isCustomDomainActive]
  30. )
  31. return { onCopyUrl }
  32. }