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