Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Chore/refactor storage explorer store part 2 (#35382)

Joshen Limacd86da9e524
diff --git a/apps/studio/components/interfaces/Reports/Reports.tsx b/apps/studio/components/interfaces/Reports/Reports.tsx
index b4067ea3c61..53685bfdb1d 100644
--- a/apps/studio/components/interfaces/Reports/Reports.tsx
+++ b/apps/studio/components/interfaces/Reports/Reports.tsx
@@ -101,7 +101,7 @@ const Reports = () => {
function checkEditState() {
if (config === undefined) return
/*
- * Shallow copying the config state variable maintains a mobx reference
+ * Shallow copying the config state variable maintains a reference
* Instead, we stringify it and parse it again to remove anything
* that can be mutated at component state level.
*
diff --git a/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx b/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx
index b5d8eff7df0..4b0eb1d68bd 100644
--- a/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx
+++ b/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx
@@ -1,12 +1,6 @@
-import { useParams } from 'common'
-import { ReactNode, useEffect } from 'react'
-import { toast } from 'sonner'
+import { ReactNode } from 'react'
-import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
-import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { withAuth } from 'hooks/misc/withAuth'
-import { PROJECT_STATUS } from 'lib/constants'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import ProjectLayout from '../ProjectLayout/ProjectLayout'
import StorageMenu from './StorageMenu'
@@ -16,36 +10,6 @@ export interface StorageLayoutProps {
}
const StorageLayout = ({ title, children }: StorageLayoutProps) => {
- const { ref: projectRef } = useParams()
- const project = useSelectedProject()
- const storageExplorerStore = useStorageStore()
-
- const { data: settings, isLoading } = useProjectSettingsV2Query({ projectRef })
- const endpoint = settings?.app_config?.endpoint
- const { serviceKey } = getAPIKeys(settings)
-
- const isPaused = project?.status === PROJECT_STATUS.INACTIVE
-
- useEffect(() => {
- if (!isLoading && endpoint && serviceKey?.api_key) {
- initializeStorageStore(endpoint, serviceKey.api_key)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isLoading, projectRef, endpoint, serviceKey?.api_key])
-
- const initializeStorageStore = async (endpoint: string, serviceApiKey: string) => {
- if (isPaused) return
-
- if (endpoint) {
- const protocol = settings?.app_config?.protocol ?? 'https'
- storageExplorerStore.initStore(projectRef!, endpoint, serviceApiKey, protocol)
- } else {
- toast.error(
- 'Failed to fetch project configuration. Try refreshing your browser, or reach out to us at [email protected]'
- )
- }
- }
-
return (
<ProjectLayout title={title || 'Storage'} product="Storage" productMenu={<StorageMenu />}>
{children}
diff --git a/apps/studio/components/to-be-cleaned/Storage/EmptyBucketModal.tsx b/apps/studio/components/to-be-cleaned/Storage/EmptyBucketModal.tsx
index 7c125baa58f..0cd2db00acf 100644
--- a/apps/studio/components/to-be-cleaned/Storage/EmptyBucketModal.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/EmptyBucketModal.tsx
@@ -3,7 +3,7 @@ import { toast } from 'sonner'
import { useBucketEmptyMutation } from 'data/storage/bucket-empty-mutation'
import type { Bucket } from 'data/storage/buckets-query'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
export interface EmptyBucketModalProps {
@@ -14,12 +14,12 @@ export interface EmptyBucketModalProps {
export const EmptyBucketModal = ({ visible = false, bucket, onClose }: EmptyBucketModalProps) => {
const { ref: projectRef } = useParams()
- const { fetchFolderContents } = useStorageStore()
+ const { fetchFolderContents } = useStorageExplorerStateSnapshot()
const { mutate: emptyBucket, isLoading } = useBucketEmptyMutation({
onSuccess: async () => {
if (bucket === undefined) return
- await fetchFolderContents(bucket.id, bucket.name, -1)
+ await fetchFolderContents({ folderId: bucket.id, folderName: bucket.name, index: -1 })
toast.success(`Successfully deleted bucket ${bucket!.name}`)
onClose()
},
@@ -38,6 +38,7 @@ export const EmptyBucketModal = ({ visible = false, bucket, onClose }: EmptyBuck
title={`Confirm to delete all contents from ${bucket?.name}`}
confirmLabel="Empty bucket"
visible={visible}
+ loading={isLoading}
onCancel={() => onClose()}
onConfirm={onEmptyBucket}
alert={{
diff --git a/apps/studio/components/to-be-cleaned/Storage/README.md b/apps/studio/components/to-be-cleaned/Storage/README.md
deleted file mode 100644
index a3b03939136..00000000000
--- a/apps/studio/components/to-be-cleaned/Storage/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-## What to clean for Storage
-
-- Convert files from javascript to typescript
-- Not use mobx store for UI related states, these could simply be done via react's useState or useReducer
- - Involves some heavy surgery nonetheless as 90% of the explorer logic is written a mobx store StorageExplorerStore
- - If anyone is able to get to it before I do, please feel free to take this on and perhaps even write it more simply 🙏
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ColumnContextMenu.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ColumnContextMenu.tsx
index 3fa51bfcdfd..ea17e28b8eb 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ColumnContextMenu.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ColumnContextMenu.tsx
@@ -4,7 +4,6 @@ import 'react-contexify/dist/ReactContexify.css'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import { ChevronRight, ChevronsDown, ChevronsUp, Clipboard, Eye, FolderPlus } from 'lucide-react'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import {
@@ -20,7 +19,6 @@ interface ColumnContextMenuProps {
const ColumnContextMenu = ({ id = '' }: ColumnContextMenuProps) => {
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
- const storageExplorerStore = useStorageStore()
const {
columns,
selectedItems,
@@ -28,7 +26,7 @@ const ColumnContextMenu = ({ id = '' }: ColumnContextMenuProps) => {
setSortBy,
setSortByOrder,
addNewFolderPlaceholder,
- } = storageExplorerStore
+ } = useStorageExplorerStateSnapshot()
const snap = useStorageExplorerStateSnapshot()
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx
index 9ed960b2130..1e56e753cd8 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/CustomExpiryModal.tsx
@@ -1,9 +1,8 @@
import dayjs from 'dayjs'
-import { observer } from 'mobx-react-lite'
import { Button, Form, Input, Listbox, Modal } from 'ui'
import { DATETIME_FORMAT } from 'lib/constants'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { useCopyUrl } from './useCopyUrl'
const unitMap = {
@@ -14,9 +13,9 @@ const unitMap = {
}
const CustomExpiryModal = () => {
- const storageExplorerStore = useStorageStore()
const { onCopyUrl } = useCopyUrl()
- const { selectedFileCustomExpiry, setSelectedFileCustomExpiry } = storageExplorerStore
+ const snap = useStorageExplorerStateSnapshot()
+ const { selectedFileCustomExpiry, setSelectedFileCustomExpiry } = snap
const visible = selectedFileCustomExpiry !== undefined
const onClose = () => setSelectedFileCustomExpiry(undefined)
@@ -102,4 +101,4 @@ const CustomExpiryModal = () => {
)
}
-export default observer(CustomExpiryModal)
+export default CustomExpiryModal
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
index dfbd8a9bc1c..f9db7769c7e 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
@@ -1,5 +1,4 @@
import { noop } from 'lodash'
-import { observer } from 'mobx-react-lite'
import { useEffect, useRef } from 'react'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
@@ -95,4 +94,4 @@ const FileExplorer = ({
)
}
-export default observer(FileExplorer)
+export default FileExplorer
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
index 2574c9f862b..32814c3cd0d 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
@@ -6,7 +6,6 @@ import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeatureP
import APIDocsButton from 'components/ui/APIDocsButton'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import {
Check,
ChevronLeft,
@@ -160,7 +159,6 @@ const FileExplorerHeader = ({
const uploadButtonRef: any = useRef(null)
const previousBreadcrumbs: any = useRef(null)
- const storageExplorerStore = useStorageStore()
const {
columns,
sortBy,
@@ -175,9 +173,9 @@ const FileExplorerHeader = ({
refetchAllOpenedFolders,
addNewFolderPlaceholder,
clearOpenedFolders,
- closeFilePreview,
+ setSelectedFilePreview,
selectedBucket,
- } = storageExplorerStore
+ } = useStorageExplorerStateSnapshot()
const breadcrumbs = columns.map((column) => column.name)
const backDisabled = columns.length <= 1
@@ -206,7 +204,7 @@ const FileExplorerHeader = ({
const onSelectBack = () => {
popColumn()
popOpenedFolders()
- closeFilePreview()
+ setSelectedFilePreview(undefined)
}
const onSelectUpload = () => {
@@ -239,11 +237,11 @@ const FileExplorerHeader = ({
if (paths.length === 0) {
popColumnAtIndex(0)
clearOpenedFolders()
- closeFilePreview()
+ setSelectedFilePreview(undefined)
} else {
const pathString = paths.join('/')
setLoading({ isLoading: true, message: `Navigating to ${pathString}...` })
- await fetchFoldersByPath(paths)
+ await fetchFoldersByPath({ paths })
setLoading({ isLoading: false, message: '' })
}
}
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
index b69bafc6ac6..5dea522960d 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
@@ -1,24 +1,24 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { Download, Move, Trash2, X } from 'lucide-react'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { Button } from 'ui'
import { downloadFile } from './StorageExplorer.utils'
const FileExplorerHeaderSelection = () => {
const { ref: projectRef, bucketId } = useParams()
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
- const storageExplorerStore = useStorageStore()
+
const {
selectedItems,
downloadSelectedFiles,
clearSelectedItems,
setSelectedItemsToDelete,
setSelectedItemsToMove,
- } = storageExplorerStore
+ } = useStorageExplorerStateSnapshot()
return (
<div className="z-10 flex h-[40px] items-center rounded-t-md bg-brand-400 px-2 py-1 shadow [[data-theme*=dark]_&]:bg-brand-500">
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
index d1df99ba571..8cfb5ef7cc4 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
@@ -22,9 +22,10 @@ import type { ItemRenderer } from 'components/ui/InfiniteList'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { BASE_PATH } from 'lib/constants'
import { formatBytes } from 'lib/helpers'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import {
Checkbox,
+ cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -113,25 +114,24 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
openedFolders = [],
}) => {
const { ref: projectRef, bucketId } = useParams()
- const storageExplorerStore = useStorageStore()
+
const {
+ selectedBucket,
+ selectedFilePreview,
popColumnAtIndex,
pushOpenedFolderAtIndex,
popOpenedFoldersAtIndex,
- setFilePreview,
- closeFilePreview,
clearSelectedItems,
- selectedBucket,
+ setSelectedFilePreview,
+ setSelectedFileCustomExpiry,
setSelectedItems,
setSelectedItemsToDelete,
setSelectedItemToRename,
setSelectedItemsToMove,
- setSelectedFileCustomExpiry,
fetchFolderContents,
downloadFolder,
selectRangeItems,
- selectedFilePreview,
- } = storageExplorerStore
+ } = useStorageExplorerStateSnapshot()
const { onCopyUrl } = useCopyUrl()
const isPublic = selectedBucket.public
@@ -147,16 +147,16 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
const onSelectFile = async (columnIndex: number, file: StorageItem) => {
popColumnAtIndex(columnIndex)
popOpenedFoldersAtIndex(columnIndex - 1)
- setFilePreview(itemWithColumnIndex)
+ setSelectedFilePreview(itemWithColumnIndex)
clearSelectedItems()
}
const onSelectFolder = async (columnIndex: number, folder: StorageItem) => {
- closeFilePreview()
+ setSelectedFilePreview(undefined)
clearSelectedItems(columnIndex + 1)
popOpenedFoldersAtIndex(columnIndex - 1)
pushOpenedFolderAtIndex(folder, columnIndex)
- await fetchFolderContents(folder.id, folder.name, columnIndex)
+ await fetchFolderContents({ folderId: folder.id, folderName: folder.name, index: columnIndex })
}
const onCheckItem = (isShiftKeyHeld: boolean) => {
@@ -172,7 +172,7 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
} else {
setSelectedItems([...selectedItems, itemWithColumnIndex])
}
- closeFilePreview()
+ setSelectedFilePreview(undefined)
}
const rowOptions =
@@ -324,13 +324,13 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
}}
>
<div
- className={[
+ className={cn(
'storage-row group flex h-full items-center px-2.5',
'hover:bg-panel-footer-light [[data-theme*=dark]_&]:hover:bg-panel-footer-dark',
`${isOpened ? 'bg-surface-200' : ''}`,
`${isPreviewed ? 'bg-green-500 hover:bg-green-500' : ''}`,
- `${item.status !== STORAGE_ROW_STATUS.LOADING ? 'cursor-pointer' : ''}`,
- ].join(' ')}
+ `${item.status !== STORAGE_ROW_STATUS.LOADING ? 'cursor-pointer' : ''}`
+ )}
onClick={(event) => {
event.stopPropagation()
event.preventDefault()
@@ -342,10 +342,10 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
}}
>
<div
- className={[
+ className={cn(
'flex items-center',
- view === STORAGE_VIEWS.LIST ? 'w-[40%] min-w-[250px]' : 'w-[90%]',
- ].join(' ')}
+ view === STORAGE_VIEWS.LIST ? 'w-[40%] min-w-[250px]' : 'w-[90%]'
+ )}
>
<div className="relative w-[30px]" onClick={(event) => event.stopPropagation()}>
{!isSelected && (
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRowEditing.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRowEditing.tsx
index d447371d726..2be0df79f40 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRowEditing.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRowEditing.tsx
@@ -1,6 +1,7 @@
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import { has } from 'lodash'
import { useEffect, useRef, useState } from 'react'
+
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { STORAGE_ROW_TYPES, STORAGE_VIEWS } from '../Storage.constants'
import { StorageItem } from '../Storage.types'
import { RowIcon } from './FileExplorerRow'
@@ -12,8 +13,7 @@ export interface FileExplorerRowEditingProps {
}
const FileExplorerRowEditing = ({ item, view, columnIndex }: FileExplorerRowEditingProps) => {
- const storageExplorerStore = useStorageStore()
- const { renameFile, renameFolder, addNewFolder } = storageExplorerStore
+ const { renameFile, renameFolder, addNewFolder } = useStorageExplorerStateSnapshot()
const inputRef = useRef<any>(null)
const [itemName, setItemName] = useState(item.name)
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FolderContextMenu.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FolderContextMenu.tsx
index 12eaec45dda..d4b2dafff54 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FolderContextMenu.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FolderContextMenu.tsx
@@ -4,7 +4,7 @@ import { Item, Menu, Separator } from 'react-contexify'
import 'react-contexify/dist/ReactContexify.css'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { copyPathToFolder } from './StorageExplorer.utils'
interface FolderContextMenuProps {
@@ -12,9 +12,8 @@ interface FolderContextMenuProps {
}
const FolderContextMenu = ({ id = '' }: FolderContextMenuProps) => {
- const storageExplorerStore = useStorageStore()
const { openedFolders, downloadFolder, setSelectedItemToRename, setSelectedItemsToDelete } =
- storageExplorerStore
+ useStorageExplorerStateSnapshot()
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
return (
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
index b52a350b802..4ce816e86aa 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
@@ -1,12 +1,11 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { ChevronRight, Clipboard, Download, Edit, Move, Trash2 } from 'lucide-react'
-import { observer } from 'mobx-react-lite'
import { Item, Menu, Separator, Submenu } from 'react-contexify'
import 'react-contexify/dist/ReactContexify.css'
import { useParams } from 'common'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { URL_EXPIRY_DURATION } from '../Storage.constants'
import { StorageItemWithColumn } from '../Storage.types'
import { downloadFile } from './StorageExplorer.utils'
@@ -18,14 +17,15 @@ interface ItemContextMenuProps {
const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
const { ref: projectRef, bucketId } = useParams()
- const storageExplorerStore = useStorageStore()
+ const snap = useStorageExplorerStateSnapshot()
+ const { setSelectedFileCustomExpiry } = snap
+
const {
selectedBucket,
setSelectedItemsToDelete,
setSelectedItemToRename,
setSelectedItemsToMove,
- setSelectedFileCustomExpiry,
- } = storageExplorerStore
+ } = useStorageExplorerStateSnapshot()
const { onCopyUrl } = useCopyUrl()
const isPublic = selectedBucket.public
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
@@ -107,4 +107,4 @@ const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
)
}
-export default observer(ItemContextMenu)
+export default ItemContextMenu
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/MoveItemsModal.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/MoveItemsModal.tsx
index 8e6625eeb15..9ec26ea001e 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/MoveItemsModal.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/MoveItemsModal.tsx
@@ -1,5 +1,6 @@
import { noop } from 'lodash'
import { useEffect, useState } from 'react'
+
import { Button, Input, Modal } from 'ui'
import { StorageItemWithColumn } from '../Storage.types'
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
index 1374b522a66..a7f39873b67 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
@@ -9,7 +9,7 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { BASE_PATH } from 'lib/constants'
import { formatBytes } from 'lib/helpers'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import {
Button,
DropdownMenu,
@@ -26,8 +26,7 @@ import { useFetchFileUrlQuery } from './useFetchFileUrlQuery'
const PREVIEW_SIZE_LIMIT = 10 * 1024 * 1024 // 10MB
const PreviewFile = ({ item }: { item: StorageItem }) => {
- const storageExplorerStore = useStorageStore()
- const { projectRef, selectedBucket } = storageExplorerStore
+ const { projectRef, selectedBucket } = useStorageExplorerStateSnapshot()
const { data: previewUrl, isLoading } = useFetchFileUrlQuery({
file: item,
@@ -118,14 +117,14 @@ const PreviewFile = ({ item }: { item: StorageItem }) => {
const PreviewPane = () => {
const { ref: projectRef, bucketId } = useParams()
- const storageExplorerStore = useStorageStore()
+
const {
selectedBucket,
selectedFilePreview: file,
- closeFilePreview,
setSelectedItemsToDelete,
+ setSelectedFilePreview,
setSelectedFileCustomExpiry,
- } = storageExplorerStore
+ } = useStorageExplorerStateSnapshot()
const { onCopyUrl } = useCopyUrl()
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
@@ -150,19 +149,14 @@ const PreviewPane = () => {
leaveFrom="transform opacity-100"
leaveTo="transform opacity-0"
>
- <div
- className="
- h-full border-l
- border-overlay bg-surface-100 p-4"
- style={{ width }}
- >
+ <div className="h-full border-l border-overlay bg-surface-100 p-4" style={{ width }}>
{/* Preview Header */}
<div className="flex w-full justify-end text-foreground-lighter transition-colors hover:text-foreground">
<X
className="cursor-pointer"
size={14}
strokeWidth={2}
- onClick={() => closeFilePreview()}
+ onClick={() => setSelectedFilePreview(undefined)}
/>
</div>
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
index 020eacb45ab..c26df6d1dcc 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
@@ -1,12 +1,10 @@
import { compact, get, isEmpty, uniqBy } from 'lodash'
-import { observer } from 'mobx-react-lite'
import { useEffect, useRef, useState } from 'react'
import { useParams } from 'common'
import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'
import type { Bucket } from 'data/storage/buckets-query'
import { IS_PLATFORM } from 'lib/constants'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { STORAGE_ROW_TYPES, STORAGE_VIEWS } from '../Storage.constants'
import { ConfirmDeleteModal } from './ConfirmDeleteModal'
@@ -22,24 +20,17 @@ interface StorageExplorerProps {
}
const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
- const storageExplorerStore = useStorageStore()
+ const { ref } = useParams()
+ const storageExplorerRef = useRef(null)
const {
+ view,
columns,
- closeFilePreview,
selectedItems,
- setSelectedItems,
- clearSelectedItems,
selectedItemsToDelete,
- clearSelectedItemsToDelete,
openedFolders,
- popColumnAtIndex,
- popOpenedFoldersAtIndex,
selectedItemsToMove,
- clearSelectedItemsToMove,
- currentBucketName,
+ selectedBucket,
openBucket,
-
- loadExplorerPreferences,
fetchFolderContents,
fetchMoreFolderContents,
fetchFoldersByPath,
@@ -47,18 +38,18 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
uploadFiles,
deleteFiles,
moveFiles,
- } = storageExplorerStore
-
- const { ref } = useParams()
- const storageExplorerRef = useRef(null)
- const snap = useStorageExplorerStateSnapshot()
+ popColumnAtIndex,
+ popOpenedFoldersAtIndex,
+ setSelectedItems,
+ clearSelectedItems,
+ setSelectedFilePreview,
+ setSelectedItemsToMove,
+ setSelectedItemsToDelete,
+ } = useStorageExplorerStateSnapshot()
- // [Joshen] This is to ensure that StorageExplorerStore can get the storage file size limit
- // Will be better once we deprecate the mobx store entirely, which we will get there
useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })
// This state exists outside of the header because FileExplorerColumn needs to listen to these as well
- // I'm keeping them outside of the mobx store as I feel that the store should contain persistent data
// Things like showing results from a search filter is "temporary", hence we use react state to manage
const [itemSearchString, setItemSearchString] = useState('')
@@ -68,44 +59,48 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
const fetchContents = async () => {
- if (snap.view === STORAGE_VIEWS.LIST) {
+ if (view === STORAGE_VIEWS.LIST) {
const currentFolderIdx = openedFolders.length - 1
const currentFolder = openedFolders[currentFolderIdx]
if (itemSearchString) {
if (!currentFolder) {
// At root of bucket
- await fetchFolderContents(bucket.id, bucket.name, -1, itemSearchString)
+ await fetchFolderContents({
+ folderId: bucket.id,
+ folderName: bucket.name,
+ index: -1,
+ searchString: itemSearchString,
+ })
} else {
- await fetchFolderContents(
- currentFolder.id,
- currentFolder.name,
- currentFolderIdx,
- itemSearchString
- )
+ await fetchFolderContents({
+ folderId: currentFolder.id,
+ folderName: currentFolder.name,
+ index: currentFolderIdx,
+ searchString: itemSearchString,
+ })
}
} else {
if (!currentFolder) {
// At root of bucket
- await fetchFolderContents(bucket.id, bucket.name, -1)
+ await fetchFolderContents({ folderId: bucket.id, folderName: bucket.name, index: -1 })
} else {
- await fetchFolderContents(currentFolder.id, currentFolder.name, currentFolderIdx)
+ await fetchFolderContents({
+ folderId: currentFolder.id,
+ folderName: currentFolder.name,
+ index: currentFolderIdx,
+ })
}
}
- } else if (snap.view === STORAGE_VIEWS.COLUMNS) {
+ } else if (view === STORAGE_VIEWS.COLUMNS) {
const paths = openedFolders.map((folder) => folder.name)
- fetchFoldersByPath(paths, itemSearchString, true)
+ fetchFoldersByPath({ paths, searchString: itemSearchString, showLoading: true })
}
}
fetchContents()
}, [itemSearchString])
- useEffect(() => {
- // Load user preferences (view, sort, sortBy)
- loadExplorerPreferences()
- }, [ref])
-
useEffect(() => {
openBucket(bucket)
}, [bucket])
@@ -143,7 +138,7 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
event.persist()
const items = event.target.files || event.dataTransfer.items
const isDrop = !isEmpty(get(event, ['dataTransfer', 'items'], []))
- await uploadFiles(items, columnIndex, isDrop)
+ await uploadFiles({ files: items, columnIndex, isDrop })
event.target.value = ''
}
@@ -161,11 +156,11 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
await deleteFolder(itemToDelete)
break
case STORAGE_ROW_TYPES.FILE:
- await deleteFiles([itemToDelete])
+ await deleteFiles({ files: [itemToDelete] })
break
}
} else {
- await deleteFiles(selectedItemsToDelete)
+ await deleteFiles({ files: selectedItemsToDelete })
}
}
@@ -173,17 +168,14 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
const onSelectColumnEmptySpace = (columnIndex: number) => {
popColumnAtIndex(columnIndex)
popOpenedFoldersAtIndex(columnIndex - 1)
- closeFilePreview()
+ setSelectedFilePreview(undefined)
clearSelectedItems()
}
return (
<div
ref={storageExplorerRef}
- className="
- bg-studio border rounded-md
- border-overlay flex
- h-full w-full flex-col"
+ className="bg-studio border rounded-md border-overlay flex h-full w-full flex-col"
>
{selectedItems.length === 0 ? (
<FileExplorerHeader
@@ -204,7 +196,7 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
onSelectAllItemsInColumn={onSelectAllItemsInColumn}
onSelectColumnEmptySpace={onSelectColumnEmptySpace}
onColumnLoadMore={(index, column) =>
- fetchMoreFolderContents(index, column, itemSearchString)
+ fetchMoreFolderContents({ index, column, searchString: itemSearchString })
}
/>
<PreviewPane />
@@ -212,14 +204,14 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
<ConfirmDeleteModal
visible={selectedItemsToDelete.length > 0}
selectedItemsToDelete={selectedItemsToDelete}
- onSelectCancel={clearSelectedItemsToDelete}
+ onSelectCancel={() => setSelectedItemsToDelete([])}
onSelectDelete={onDeleteSelectedFiles}
/>
<MoveItemsModal
- bucketName={currentBucketName}
+ bucketName={selectedBucket.name}
visible={selectedItemsToMove.length > 0}
selectedItemsToMove={selectedItemsToMove}
- onSelectCancel={clearSelectedItemsToMove}
+ onSelectCancel={() => setSelectedItemsToMove([])}
onSelectMove={onMoveSelectedFiles}
/>
<CustomExpiryModal />
@@ -228,4 +220,4 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
}
StorageExplorer.displayName = 'StorageExplorer'
-export default observer(StorageExplorer)
+export default StorageExplorer
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.tsx
index 3d8dbf518ad..f2f2d01d609 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.tsx
@@ -1,8 +1,21 @@
import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
+import { StorageObject } from 'data/storage/bucket-objects-list-mutation'
import { copyToClipboard } from 'lib/helpers'
import { toast } from 'sonner'
import { SONNER_DEFAULT_DURATION } from 'ui'
-import { StorageItem, StorageItemWithColumn } from '../Storage.types'
+import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES } from '../Storage.constants'
+import { StorageItem, StorageItemMetadata, StorageItemWithColumn } from '../Storage.types'
+
+type UploadProgress = {
+ percentage: number
+ elapsed: number
+ uploadSpeed: number
+ remainingBytes: number
+ remainingTime: number
+}
+
+const CORRUPTED_THRESHOLD_MS = 15 * 60 * 1000 // 15 minutes
+export const EMPTY_FOLDER_PLACEHOLDER_FILE_NAME = '.emptyFolderPlaceholder'
export const copyPathToFolder = (openedFolders: StorageItem[], item: StorageItemWithColumn) => {
const folders = openedFolders.slice(0, item.columnIndex).map((folder) => folder.name)
@@ -85,3 +98,118 @@ export const downloadFile = async ({
return false
}
}
+
+export const calculateTotalRemainingTime = (progresses: UploadProgress[]) => {
+ let totalRemainingTime = 0
+ let totalRemainingBytes = 0
+
+ progresses.forEach((progress) => {
+ totalRemainingBytes += progress.remainingBytes
+ if (totalRemainingBytes === 0) {
+ return
+ }
+ const weight = progress.remainingBytes / totalRemainingBytes
+ totalRemainingTime += weight * progress.remainingTime
+ })
+
+ return totalRemainingTime
+}
+
+export const formatFolderItems = (items: StorageObject[] = [], prefix?: string): StorageItem[] => {
+ const formattedItems =
+ (items ?? [])
+ ?.filter((item) => item.name !== EMPTY_FOLDER_PLACEHOLDER_FILE_NAME)
+ .map((item) => {
+ const type = item.id ? STORAGE_ROW_TYPES.FILE : STORAGE_ROW_TYPES.FOLDER
+
+ const durationSinceCreated = Number(new Date()) - Number(new Date(item.created_at))
+ const isCorrupted =
+ type === STORAGE_ROW_TYPES.FILE &&
+ !item.metadata &&
+ durationSinceCreated >= CORRUPTED_THRESHOLD_MS
+
+ const status =
+ type === STORAGE_ROW_TYPES.FILE &&
+ !item.metadata &&
+ durationSinceCreated <= CORRUPTED_THRESHOLD_MS
+ ? STORAGE_ROW_STATUS.LOADING
+ : STORAGE_ROW_STATUS.READY
+
+ const itemObj = {
+ ...item,
+ metadata: item.metadata as any as StorageItemMetadata,
+ type,
+ status,
+ isCorrupted,
+ path: !!prefix ? `${prefix}/${item.name}` : item.name,
+ }
+ return itemObj
+ }) ?? []
+ return formattedItems
+}
+
+export const getFile = async (fileEntry: FileSystemFileEntry): Promise<File | undefined> => {
+ try {
+ return await new Promise((resolve, reject) => fileEntry.file(resolve, reject))
+ } catch (err) {
+ console.error('getFile error:', err)
+ return undefined
+ }
+}
+
+// Referenced from: // https://stackoverflow.com/a/53058574
+export const getFilesDataTransferItems = async (items: DataTransferItemList) => {
+ const toastId = toast('Retrieving items to upload...')
+ const files: (File & { path: string })[] = []
+ const queue: FileSystemEntry[] = []
+ for (const item of items) {
+ const entry = item.webkitGetAsEntry()
+ if (entry) {
+ queue.push(entry)
+ }
+ }
+ while (queue.length > 0) {
+ const entry = queue.shift()
+ if (entry && entry.isFile) {
+ const fileEntry = entry as FileSystemFileEntry
+ const file = await getFile(fileEntry)
+ if (file !== undefined) {
+ ;(file as any).path = fileEntry.fullPath.slice(1)
+ files.push(file as File & { path: string })
+ }
+ } else if (entry && entry.isDirectory) {
+ const dirEntry = entry as FileSystemDirectoryEntry
+ queue.push(...(await readAllDirectoryEntries(dirEntry.createReader())))
+ }
+ }
+ toast.dismiss(toastId)
+ return files
+}
+
+/**
+ * Get all the entries (files or sub-directories) in a directory by calling readEntries until it returns empty array
+ */
+const readAllDirectoryEntries = async (directoryReader: FileSystemDirectoryReader) => {
+ const entries = []
+ let readEntries = await readEntriesPromise(directoryReader)
+ while (readEntries && readEntries.length > 0) {
+ entries.push(...readEntries)
+ readEntries = await readEntriesPromise(directoryReader)
+ }
+ return entries
+}
+
+/**
+ * Wrap readEntries in a promise to make working with readEntries easier
+ * readEntries will return only some of the entries in a directory
+ * e.g. Chrome returns at most 100 entries at a time
+ */
+const readEntriesPromise = async (directoryReader: FileSystemDirectoryReader) => {
+ try {
+ return await new Promise<FileSystemEntry[]>((resolve, reject) => {
+ directoryReader.readEntries(resolve, reject)
+ })
+ } catch (err) {
+ console.error('readEntriesPromise error:', err)
+ }
+}
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx
index 16eed0c7f2a..e31ae431a0f 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useCopyUrl.tsx
@@ -4,12 +4,13 @@ import { toast } from 'sonner'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import { copyToClipboard } from 'lib/helpers'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { URL_EXPIRY_DURATION } from '../Storage.constants'
import { fetchFileUrl } from './useFetchFileUrlQuery'
export const useCopyUrl = () => {
- const { projectRef, selectedBucket, getPathAlongOpenedFolders } = useStorageStore()
+ const { projectRef, selectedBucket, getPathAlongOpenedFolders } =
+ useStorageExplorerStateSnapshot()
const { data: customDomainData } = useCustomDomainsQuery({ projectRef: projectRef })
const { data: settings } = useProjectSettingsV2Query({ projectRef: projectRef })
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useFetchFileUrlQuery.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
index 19b5d043d3d..3647f90009d 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
@@ -2,7 +2,7 @@ import { UseQueryOptions, useQuery } from '@tanstack/react-query'
import { getPublicUrlForBucketObject } from 'data/storage/bucket-object-get-public-url-mutation'
import { signBucketObject } from 'data/storage/bucket-object-sign-mutation'
import { Bucket } from 'data/storage/buckets-query'
-import { useStorageStore } from 'localStores/storageExplorer/StorageExplorerStore'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { ResponseError } from 'types'
import { StorageItem } from '../Storage.types'
@@ -43,7 +43,7 @@ export const useFetchFileUrlQuery = (
{ file, projectRef, bucket }: UseFileUrlQueryVariables,
{ ...options }: UseQueryOptions<string, ResponseError> = {}
) => {
- const { getPathAlongOpenedFolders } = useStorageStore()
+ const { getPathAlongOpenedFolders } = useStorageExplorerStateSnapshot()
const pathToFile = getPathAlongOpenedFolders(false)
const formattedPathToFile = [pathToFile, file?.name].join('/')
diff --git a/apps/studio/localStores/README.md b/apps/studio/localStores/README.md
deleted file mode 100644
index a2f5b09c2cc..00000000000
--- a/apps/studio/localStores/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Local stores
-
-Note: We are looking to deprecate this folder. Do not add any files here
diff --git a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
deleted file mode 100644
index 82db7df68a5..00000000000
--- a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
+++ /dev/null
@@ -1,1790 +0,0 @@
-import { SupabaseClient, createClient } from '@supabase/supabase-js'
-import { BlobReader, BlobWriter, ZipWriter } from '@zip.js/zip.js'
-import {
- capitalize,
- chunk,
- compact,
- find,
- findIndex,
- has,
- isEqual,
- isObject,
- uniq,
- uniqBy,
-} from 'lodash'
-import { makeAutoObservable } from 'mobx'
-import { toast } from 'sonner'
-import * as tus from 'tus-js-client'
-
-import {
- STORAGE_ROW_STATUS,
- STORAGE_ROW_TYPES,
- STORAGE_SORT_BY,
- STORAGE_SORT_BY_ORDER,
- STORAGE_VIEWS,
-} from 'components/to-be-cleaned/Storage/Storage.constants'
-import {
- StorageColumn,
- StorageItem,
- StorageItemMetadata,
- StorageItemWithColumn,
-} from 'components/to-be-cleaned/Storage/Storage.types'
-import {
- downloadFile,
- formatTime,
-} from 'components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils'
-import { convertFromBytes } from 'components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils'
-import { configKeys } from 'data/config/keys'
-import { ProjectStorageConfigResponse } from 'data/config/project-storage-config-query'
-import { getQueryClient } from 'data/query-client'
-import { deleteBucketObject } from 'data/storage/bucket-object-delete-mutation'
-import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
-import { StorageObject, listBucketObjects } from 'data/storage/bucket-objects-list-mutation'
-import { Bucket } from 'data/storage/buckets-query'
-import { moveStorageObject } from 'data/storage/object-move-mutation'
-import { IS_PLATFORM } from 'lib/constants'
-import { tryParseJson } from 'lib/helpers'
-import { lookupMime } from 'lib/mime'
-import Link from 'next/link'
-import { Button, SONNER_DEFAULT_DURATION, SonnerProgress } from 'ui'
-import { LOCAL_STORAGE_KEYS } from 'common'
-
-type CachedFile = { id: string; fetchedAt: number; expiresIn: number; url: string }
-
-type UploadProgress = {
- percentage: number
- elapsed: number
- uploadSpeed: number
- remainingBytes: number
- remainingTime: number
-}
-
-/**
- * This is a preferred method rather than React Context and useStorageExplorerStore().
- * If we can switch to this method, we can remove the implementation below, and we don't need compose() within the react components
- */
-let store: StorageExplorerStore | null = null
-export function useStorageStore() {
- if (store === null) store = new StorageExplorerStore()
- return store
-}
-
-const CORRUPTED_THRESHOLD_MS = 15 * 60 * 1000 // 15 minutes
-const LIMIT = 200
-const OFFSET = 0
-const BATCH_SIZE = 2
-const EMPTY_FOLDER_PLACEHOLDER_FILE_NAME = '.emptyFolderPlaceholder'
-const STORAGE_PROGRESS_INFO_TEXT = "Do not close the browser until it's completed"
-
-class StorageExplorerStore {
- projectRef: string = ''
- sortBy: STORAGE_SORT_BY = STORAGE_SORT_BY.NAME
- sortByOrder: STORAGE_SORT_BY_ORDER = STORAGE_SORT_BY_ORDER.ASC
- // selectedBucket will get initialized with a bucket before using
- selectedBucket: Bucket = {} as Bucket
- columns: StorageColumn[] = []
- openedFolders: StorageItem[] = []
- selectedItems: StorageItemWithColumn[] = []
- selectedItemsToDelete: StorageItemWithColumn[] = []
- selectedItemsToMove: StorageItemWithColumn[] = []
- selectedFilePreview: StorageItemWithColumn | null = null
- selectedFileCustomExpiry: StorageItem | undefined = undefined
-
- private DEFAULT_OPTIONS = {
- limit: LIMIT,
- offset: OFFSET,
- sortBy: { column: this.sortBy, order: this.sortByOrder },
- }
-
- private resumableUploadUrl: string = ''
- private serviceKey: string = ''
-
- /* Supabase client, will get initialized immediately after constructing the instance */
- supabaseClient: SupabaseClient<any, 'public', any> = null as any as SupabaseClient<
- any,
- 'public',
- any
- >
-
- /* For file uploads, from 0 to 1 */
- private uploadProgresses: UploadProgress[] = []
-
- /* Controllers to abort API calls */
- private abortController: AbortController | null = null
-
- private abortUploadCallbacks: {
- [key: string]: (() => void)[]
- } = {}
-
- constructor() {
- makeAutoObservable(this, { supabaseClient: false })
-
- // ignore when in a non-browser environment
- if (typeof window !== 'undefined') {
- this.abortController = new AbortController()
- }
- }
-
- initStore(projectRef: string, url: string, serviceKey: string, protocol: string) {
- this.projectRef = projectRef
- this.resumableUploadUrl = `${IS_PLATFORM ? 'https' : protocol}://${url}/storage/v1/upload/resumable`
- this.serviceKey = serviceKey
- if (serviceKey !== undefined) this.initializeSupabaseClient(serviceKey, url, protocol)
- }
-
- /* Methods which are commonly used + For better readability */
-
- private initializeSupabaseClient = (
- serviceKey: string,
- serviceEndpoint: string,
- protocol: string
- ) => {
- this.supabaseClient = createClient(
- `${IS_PLATFORM ? 'https' : protocol}://${serviceEndpoint}`,
- serviceKey,
- {
- auth: {
- persistSession: false,
- autoRefreshToken: false,
- detectSessionInUrl: false,
- storage: {
- getItem: (key) => {
- return null
- },
- setItem: (key, value) => {},
- removeItem: (key) => {},
- },
- },
- }
- )
- }
-
- private getLocalStorageKey = () => {
- return LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(this.projectRef)
- }
-
- private getLatestColumnIndex = () => {
- return this.columns.length - 1
- }
-
- // Probably refactor this to ignore bucket by default
- getPathAlongOpenedFolders = (includeBucket = true) => {
- if (includeBucket) {
- return this.openedFolders.length > 0
- ? `${this.selectedBucket.name}/${this.openedFolders.map((folder) => folder.name).join('/')}`
- : this.selectedBucket.name
- }
- return this.openedFolders.map((folder) => folder.name).join('/')
- }
-
- private abortApiCalls = () => {
- this.abortController?.abort()
- this.abortController = new AbortController()
- }
-
- get currentBucketName() {
- return this.selectedBucket.name
- }
-
- /* UI specific methods */
-
- private setSelectedBucket = (bucket: Bucket) => {
- this.selectedBucket = bucket
- this.clearOpenedFolders()
- this.closeFilePreview()
- this.clearSelectedItems()
- }
-
- setSortBy = async (sortBy: STORAGE_SORT_BY) => {
- this.sortBy = sortBy
- this.closeFilePreview()
- this.updateExplorerPreferences()
- await this.refetchAllOpenedFolders()
- }
-
- setSortByOrder = async (sortByOrder: STORAGE_SORT_BY_ORDER) => {
- this.sortByOrder = sortByOrder
- this.closeFilePreview()
- this.updateExplorerPreferences()
- await this.refetchAllOpenedFolders()
- }
-
- private pushColumnAtIndex = (column: StorageColumn, index: number) => {
- this.columns = this.columns.slice(0, index + 1).concat([column])
- }
-
- popColumn = () => {
- this.abortApiCalls()
- this.columns = this.columns.slice(0, this.getLatestColumnIndex())
- }
-
- popColumnAtIndex = (index: number) => {
- this.columns = this.columns.slice(0, index + 1)
- }
-
- private setColumnIsLoadingMore = (index: number, isLoadingMoreItems: boolean = true) => {
- this.columns = this.columns.map((col, idx) => {
- return idx === index ? { ...col, isLoadingMoreItems } : col
- })
- }
-
- pushOpenedFolderAtIndex = (folder: StorageItem, index: number) => {
- this.openedFolders = this.openedFolders.slice(0, index).concat(folder)
- }
-
- popOpenedFolders = () => {
- this.openedFolders = this.openedFolders.slice(0, this.openedFolders.length - 1)
- }
-
- popOpenedFoldersAtIndex = (index: number) => {
- this.openedFolders = this.openedFolders.slice(0, index + 1)
- }
- clearOpenedFolders = () => {
- this.openedFolders = []
- }
-
- setSelectedItems = (items: StorageItemWithColumn[]) => {
- this.selectedItems = items
- }
-
- clearSelectedItems = (columnIndex?: number) => {
- if (columnIndex !== undefined) {
- this.selectedItems = this.selectedItems.filter((item) => item.columnIndex !== columnIndex)
- } else {
- this.selectedItems = []
- }
- }
-
- setSelectedItemsToDelete = (items: StorageItemWithColumn[]) => {
- this.selectedItemsToDelete = items
- }
-
- clearSelectedItemsToDelete = () => {
- this.selectedItemsToDelete = []
- }
-
- setSelectedItemsToMove = (items: StorageItemWithColumn[]) => {
- this.selectedItemsToMove = items
- }
-
- clearSelectedItemsToMove = () => {
- this.selectedItemsToMove = []
- }
-
- setSelectedFileCustomExpiry = (item: StorageItem | undefined) => {
- this.selectedFileCustomExpiry = item
- }
-
- addNewFolderPlaceholder = (columnIndex: number) => {
- const isPrepend = true
- const folderName = 'Untitled folder'
- const folderType = STORAGE_ROW_TYPES.FOLDER
- const columnIdx = columnIndex === -1 ? this.getLatestColumnIndex() : columnIndex
- this.addTempRow(folderType, folderName, STORAGE_ROW_STATUS.EDITING, columnIdx, null, isPrepend)
- }
-
- addNewFolder = async (folderName: string, columnIndex: number) => {
- const autofix = false
- const formattedName = this.sanitizeNameForDuplicateInColumn(folderName, autofix, columnIndex)
- if (formattedName === null) return
-
- if (!/^[a-zA-Z0-9_-\s]*$/.test(formattedName)) {
- return toast.error('Folder name contains invalid special characters')
- }
-
- if (formattedName.length === 0) {
- return this.removeTempRows(columnIndex)
- }
-
- this.updateFolderAfterEdit(formattedName, columnIndex)
-
- const emptyPlaceholderFile = `${formattedName}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`
- const pathToFolder = this.openedFolders
- .slice(0, columnIndex)
- .map((folder) => folder.name)
- .join('/')
- const formattedPathToEmptyPlaceholderFile =
- pathToFolder.length > 0 ? `${pathToFolder}/${emptyPlaceholderFile}` : emptyPlaceholderFile
-
- await this.supabaseClient.storage
- .from(this.selectedBucket.name)
- .upload(formattedPathToEmptyPlaceholderFile, new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME))
-
- if (pathToFolder.length > 0) {
- await deleteBucketObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- paths: [`${pathToFolder}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`],
- })
- }
- }
-
- setFilePreview = async (file: StorageItemWithColumn) => {
- this.selectedFilePreview = file
- }
-
- closeFilePreview = () => {
- this.selectedFilePreview = null
- }
-
- /* Methods that involve the storage client library */
- /* Bucket CRUD */
- openBucket = async (bucket: Bucket) => {
- const { id, name } = bucket
- const columnIndex = -1
- if (!isEqual(this.selectedBucket, bucket)) {
- this.setSelectedBucket(bucket)
- await this.fetchFolderContents(id, name, columnIndex)
- }
- }
-
- /* Files CRUD */
-
- private getFile = async (fileEntry: FileSystemFileEntry): Promise<File | undefined> => {
- try {
- return await new Promise((resolve, reject) => fileEntry.file(resolve, reject))
- } catch (err) {
- console.error('getFile error:', err)
- return undefined
- }
- }
-
- // https://stackoverflow.com/a/53058574
- private getFilesDataTransferItems = async (items: DataTransferItemList) => {
- const toastId = toast('Retrieving items to upload...')
- const files: (File & { path: string })[] = []
- const queue: FileSystemEntry[] = []
- for (const item of items) {
- const entry = item.webkitGetAsEntry()
- if (entry) {
- queue.push(entry)
- }
- }
- while (queue.length > 0) {
- const entry = queue.shift()
- if (entry && entry.isFile) {
- const fileEntry = entry as FileSystemFileEntry
- const file = await this.getFile(fileEntry)
- if (file !== undefined) {
- ;(file as any).path = fileEntry.fullPath.slice(1)
- files.push(file as File & { path: string })
- }
- } else if (entry && entry.isDirectory) {
- const dirEntry = entry as FileSystemDirectoryEntry
- queue.push(...(await this.readAllDirectoryEntries(dirEntry.createReader())))
- }
- }
- toast.dismiss(toastId)
- return files
- }
-
- // Get all the entries (files or sub-directories) in a directory
- // by calling readEntries until it returns empty array
- private readAllDirectoryEntries = async (directoryReader: FileSystemDirectoryReader) => {
- const entries = []
- let readEntries = await this.readEntriesPromise(directoryReader)
- while (readEntries && readEntries.length > 0) {
- entries.push(...readEntries)
- readEntries = await this.readEntriesPromise(directoryReader)
- }
- return entries
- }
-
- // Wrap readEntries in a promise to make working with readEntries easier
- // readEntries will return only some of the entries in a directory
- // e.g. Chrome returns at most 100 entries at a time
- private readEntriesPromise = async (directoryReader: FileSystemDirectoryReader) => {
- try {
- return await new Promise<FileSystemEntry[]>((resolve, reject) => {
- directoryReader.readEntries(resolve, reject)
- })
- } catch (err) {
- console.error('readEntriesPromise error:', err)
- }
- }
-
- onUploadProgress(toastId?: string | number) {
- const totalFiles = this.uploadProgresses.length
- const progress =
- (this.uploadProgresses.reduce((acc, { percentage }) => acc + percentage, 0) / totalFiles) *
- 100
- const remainingTime = this.calculateTotalRemainingTime(this.uploadProgresses)
-
- return toast(
- <SonnerProgress
- progress={progress}
- message={`Uploading ${totalFiles} file${totalFiles > 1 ? 's' : ''}...`}
- progressPrefix={`${remainingTime && !isNaN(remainingTime) && isFinite(remainingTime) && remainingTime !== 0 ? `${formatTime(remainingTime)} remaining – ` : ''}`}
- action={
- toastId && (
- <Button
- type="default"
- size="tiny"
- className="ml-6"
- onClick={() => this.abortUploads(toastId)}
- >
- Cancel
- </Button>
- )
- }
- />,
- { id: toastId, closeButton: false, position: 'bottom-right' }
- )
- }
-
- uploadFiles = async (
- files: FileList | DataTransferItemList,
- columnIndex: number,
- isDrop: boolean = false
- ) => {
- const queryClient = getQueryClient()
- const storageConfiguration = queryClient
- .getQueryCache()
- .find(configKeys.storage(this.projectRef))?.state.data as
- | ProjectStorageConfigResponse
- | undefined
- const fileSizeLimit = storageConfiguration?.fileSizeLimit
-
- const t1 = new Date()
-
- const autofix = true
- // We filter out any folders which are just '#' until we can properly encode such characters in the URL
- const filesToUpload: (File & { path?: string })[] = isDrop
- ? (await this.getFilesDataTransferItems(files as DataTransferItemList)).filter(
- (file) => !file.path.includes('#/')
- )
- : Array.from(files as FileList)
- const derivedColumnIndex = columnIndex === -1 ? this.getLatestColumnIndex() : columnIndex
-
- const filesWithinUploadLimit =
- fileSizeLimit !== undefined
- ? filesToUpload.filter((file) => file.size <= fileSizeLimit)
- : filesToUpload
-
- if (filesWithinUploadLimit.length < filesToUpload.length) {
- const numberOfFilesRejected = filesToUpload.length - filesWithinUploadLimit.length
- const { value, unit } = convertFromBytes(fileSizeLimit as number)
-
- toast.error(
- <div className="flex flex-col gap-y-1">
- <p className="text-foreground">
- Failed to upload {numberOfFilesRejected} file{numberOfFilesRejected > 1 ? 's' : ''} as{' '}
- {numberOfFilesRejected > 1 ? 'their' : 'its'} size
- {numberOfFilesRejected > 1 ? 's are' : ' is'} beyond the global upload limit of {value}
- {unit}.
- </p>
- <p className="text-foreground-light">
- You can change the global file size upload limit in{' '}
- <Link
- className="underline"
- href={`/project/${this.projectRef}/settings/storage`}
- target="_blank"
- >
- Storage settings
- </Link>
- .
- </p>
- </div>,
- { duration: 8000 }
- )
-
- if (numberOfFilesRejected === filesToUpload.length) return
- }
-
- const filesWithNonZeroSize = filesWithinUploadLimit.filter((file) => file.size > 0)
- if (filesWithNonZeroSize.length < filesWithinUploadLimit.length) {
- const numberOfFilesRejected = filesWithinUploadLimit.length - filesWithNonZeroSize.length
- toast.error(
- <div className="flex flex-col gap-y-1">
- <p className="text-foreground">
- Failed to upload {numberOfFilesRejected} file{numberOfFilesRejected > 1 ? 's' : ''} as{' '}
- {numberOfFilesRejected > 1 ? 'their' : 'its'} size
- {numberOfFilesRejected > 1 ? 's are' : ' is'} 0.
- </p>
- </div>
- )
-
- if (numberOfFilesRejected === filesWithinUploadLimit.length) return
- }
-
- // If we're uploading a folder which name already exists in the same folder that we're uploading to
- // We sanitize the folder name and let all file uploads through. (This is only via drag drop)
- const topLevelFolders: string[] = (this.columns?.[derivedColumnIndex]?.items ?? [])
- .filter((item) => !item.id)
- .map((item) => item.name)
- const formattedFilesToUpload = filesWithinUploadLimit
- .filter((file) => file.name !== '.DS_Store')
- .map((file) => {
- // If the files are from clicking "Upload button", just take them as they are since users cannot
- // upload folders from clicking that button, only via drag drop
- if (!file.path) return file
-
- const path = file.path.split('/')
- const topLevelFolder = path.length > 1 ? path[0] : null
- if (topLevelFolders.includes(topLevelFolder as string)) {
- const newTopLevelFolder = this.sanitizeNameForDuplicateInColumn(
- topLevelFolder as string,
- autofix,
- columnIndex
- )
- path[0] = newTopLevelFolder as string
- file.path = path.join('/')
- }
- return file
- })
-
- this.uploadProgresses = new Array(formattedFilesToUpload.length).fill({
- percentage: 0,
- elapsed: 0,
- uploadSpeed: 0,
- remainingBytes: 0,
- remainingTime: 0,
- })
- const uploadedTopLevelFolders: string[] = []
- const numberOfFilesToUpload = formattedFilesToUpload.length
- let numberOfFilesUploadedSuccess = 0
- let numberOfFilesUploadedFail = 0
-
- const pathToFile = this.openedFolders
- .slice(0, derivedColumnIndex)
- .map((folder) => folder.name)
- .join('/')
-
- const toastId = this.onUploadProgress()
-
- // Upload files in batches
- const promises = formattedFilesToUpload.map((file, index) => {
- const extension = file.name.split('.').pop()
- const metadata = {
- mimetype: (file.type || lookupMime(extension)) ?? '',
- size: file.size,
- } as StorageItemMetadata
- const fileOptions = { cacheControl: '3600', contentType: metadata.mimetype }
-
- const isWithinFolder = (file?.path ?? '').split('/').length > 1
- const fileName = !isWithinFolder
- ? this.sanitizeNameForDuplicateInColumn(file.name, autofix)
- : file.name
- const unsanitizedFormattedFileName =
- has(file, ['path']) && isWithinFolder ? file.path : fileName
- /**
- * Storage maintains a list of allowed characters, which excludes
- * characters such as the narrow no-break space used in Mac screenshots.
- * [Joshen] Am limiting to just replacing nbsp with a blank space instead of
- * all non-word characters per before
- * */
- const formattedFileName = (unsanitizedFormattedFileName ?? 'unknown').replaceAll(
- /\u{202F}/gu,
- ' '
- )
- const formattedPathToFile =
- pathToFile.length > 0 ? `${pathToFile}/${formattedFileName}` : (formattedFileName as string)
-
- if (isWithinFolder) {
- const topLevelFolder = file.path?.split('/')[0] || ''
- if (!uploadedTopLevelFolders.includes(topLevelFolder)) {
- this.addTempRow(
- STORAGE_ROW_TYPES.FOLDER,
- topLevelFolder,
- STORAGE_ROW_STATUS.LOADING,
- derivedColumnIndex,
- metadata
- )
- uploadedTopLevelFolders.push(topLevelFolder)
- }
- } else {
- this.addTempRow(
- STORAGE_ROW_TYPES.FILE,
- fileName!,
- STORAGE_ROW_STATUS.LOADING,
- derivedColumnIndex,
- metadata
- )
- }
-
- let startingBytes = 0
- const bucketName = this.selectedBucket.name
-
- return () => {
- return new Promise<void>(async (resolve, reject) => {
- const fileSizeInMB = file.size / (1024 * 1024)
- const startTime = Date.now()
-
- let chunkSize: number
-
- if (fileSizeInMB < 30) {
- chunkSize = 6 * 1024 * 1024
- } else if (fileSizeInMB < 100) {
- chunkSize = Math.floor(file.size / 8)
- } else if (fileSizeInMB < 500) {
- chunkSize = Math.floor(file.size / 10)
- } else if (fileSizeInMB < 1024) {
- chunkSize = Math.floor(file.size / 20)
- } else if (fileSizeInMB < 10 * 1024) {
- chunkSize = Math.floor(file.size / 30)
- } else {
- chunkSize = Math.floor(file.size / 50)
- }
-
- // Max chunk size is 500MB
- chunkSize = Math.min(chunkSize, 500 * 1024 * 1024)
- const uploadDataDuringCreation = file.size <= chunkSize
-
- const upload = new tus.Upload(file, {
- endpoint: this.resumableUploadUrl,
- retryDelays: [0, 200, 500, 1500, 3000, 5000],
- headers: {
- authorization: `Bearer ${this.serviceKey}`,
- 'x-source': 'supabase-dashboard',
- },
- uploadDataDuringCreation: uploadDataDuringCreation,
- removeFingerprintOnSuccess: true,
- metadata: {
- bucketName,
- objectName: formattedPathToFile,
- ...fileOptions,
- },
- chunkSize,
- onShouldRetry(error) {
- const status = error.originalResponse ? error.originalResponse.getStatus() : 0
- const doNotRetryStatuses = [400, 403, 404, 409, 413, 415, 429]
-
- return !doNotRetryStatuses.includes(status)
- },
- onError: (error) => {
- numberOfFilesUploadedFail += 1
- if (error instanceof tus.DetailedError) {
- const status = error.originalResponse?.getStatus()
- if (status === 415) {
- // Unsupported mime type
- toast.error(
- capitalize(
- error?.originalResponse?.getBody() ||
- `Failed to upload ${file.name}: ${metadata.mimetype} is not allowed`
- ),
- {
- description: `Allowed MIME types: ${this.selectedBucket.allowed_mime_types?.join(', ')}`,
- }
- )
- } else if (status === 413) {
- // Payload too large
- toast.error(
- `Failed to upload ${file.name}: File size exceeds the bucket upload limit.`
- )
- }
- } else {
- toast.error(`Failed to upload ${file.name}: ${error.message}`)
- }
- reject(error)
- },
- onProgress: (bytesSent, bytesTotal) => {
- if (startingBytes === 0 && bytesSent > chunkSize) {
- startingBytes = bytesSent
- }
-
- const percentage = bytesTotal === 0 ? 0 : bytesSent / bytesTotal
- const realBytesSent = bytesSent - startingBytes
- const elapsed = (Date.now() - startTime) / 1000 // in seconds
- const uploadSpeed = realBytesSent / elapsed // in bytes per second
- const remainingBytes = bytesTotal - realBytesSent
- const remainingTime = remainingBytes / uploadSpeed // in seconds
-
- this.uploadProgresses[index] = {
- percentage,
- elapsed,
- uploadSpeed,
- remainingBytes,
- remainingTime,
- }
- this.onUploadProgress(toastId)
- },
- onSuccess() {
- numberOfFilesUploadedSuccess += 1
- resolve()
- },
- })
-
- if (!Array.isArray(this.abortUploadCallbacks[toastId])) {
- this.abortUploadCallbacks[toastId] = []
- }
- this.abortUploadCallbacks[toastId].push(() => {
- try {
- upload.abort(true)
- } catch (error) {
- // Ignore error
- }
- reject(new Error('Upload aborted by user'))
- })
-
- // Check if there are any previous uploads to continue.
- return upload.findPreviousUploads().then((previousUploads) => {
- // Found previous uploads so we select the first one.
- if (previousUploads.length) {
- upload.resumeFromPreviousUpload(previousUploads[0])
- }
-
- upload.start()
- })
- })
- }
- })
-
- // For file uploads specifically, we have to lower the batch size for now as the client side
- // is just unable to handle such volumes of transfer
- // [Joshen] I realised this can be simplified with just a vanilla for loop, no need for reduce
- // Just take note, but if it's working fine, then it's okay
- const batchedPromises = chunk(promises, 10)
- try {
- await batchedPromises.reduce(async (previousPromise, nextBatch) => {
- await previousPromise
- await Promise.allSettled(nextBatch.map((batch) => batch()))
- this.onUploadProgress(toastId)
- }, Promise.resolve())
-
- if (numberOfFilesUploadedSuccess > 0) {
- await deleteBucketObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- paths: [`${pathToFile}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`],
- })
- }
-
- await this.refetchAllOpenedFolders()
-
- if (
- numberOfFilesToUpload === 0 ||
- (numberOfFilesUploadedSuccess === 0 && numberOfFilesUploadedFail === 0)
- ) {
- toast.dismiss(toastId)
- } else if (numberOfFilesUploadedFail === numberOfFilesToUpload) {
- toast.error(
- `Failed to upload ${numberOfFilesToUpload} file${numberOfFilesToUpload > 1 ? 's' : ''}!`,
- { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
- )
- } else if (numberOfFilesUploadedSuccess === numberOfFilesToUpload) {
- toast.success(
- `Successfully uploaded ${numberOfFilesToUpload} file${
- numberOfFilesToUpload > 1 ? 's' : ''
- }!`,
- { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
- )
- } else {
- toast.success(
- `Successfully uploaded ${numberOfFilesUploadedSuccess} out of ${numberOfFilesToUpload} file${
- numberOfFilesToUpload > 1 ? 's' : ''
- }!`,
- { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
- )
- }
- } catch (e) {
- toast.error('Failed to upload files', {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
-
- const t2 = new Date()
- console.log(
- `Total time taken for ${formattedFilesToUpload.length} files: ${((t2 as any) - (t1 as any)) / 1000} seconds`
- )
- }
-
- abortUploads = (toastId: string | number) => {
- this.abortUploadCallbacks[toastId].forEach((callback) => callback())
- this.abortUploadCallbacks[toastId] = []
- }
-
- moveFiles = async (newPathToFile: string) => {
- const newPaths = compact(newPathToFile.split('/'))
- const formattedNewPathToFile = newPaths.join('/')
- let numberOfFilesMovedFail = 0
- this.clearSelectedItems()
-
- const toastId = toast(STORAGE_PROGRESS_INFO_TEXT, {
- duration: Infinity,
- })
-
- await Promise.all(
- this.selectedItemsToMove.map(async (item) => {
- const pathToFile = this.openedFolders
- .slice(0, item.columnIndex)
- .map((folder) => folder.name)
- .join('/')
-
- const fromPath = pathToFile.length > 0 ? `${pathToFile}/${item.name}` : item.name
- const toPath =
- newPathToFile.length > 0 ? `${formattedNewPathToFile}/${item.name}` : item.name
-
- try {
- await moveStorageObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- from: fromPath,
- to: toPath,
- })
- } catch (error: any) {
- numberOfFilesMovedFail += 1
- toast.error(error.message)
- }
- })
- )
-
- if (numberOfFilesMovedFail === this.selectedItemsToMove.length) {
- toast.error('Failed to move files')
- } else {
- toast(
- `Successfully moved ${
- this.selectedItemsToMove.length - numberOfFilesMovedFail
- } files to ${formattedNewPathToFile.length > 0 ? formattedNewPathToFile : 'the root of your bucket'}`
- )
- }
-
- toast.dismiss(toastId)
-
- // TODO: invalidate the file preview cache when moving files
- await this.refetchAllOpenedFolders()
- this.clearSelectedItemsToMove()
- }
-
- // the method accepts either files with column index or with prefix.
- deleteFiles = async (
- files: (StorageItemWithColumn & { prefix?: string })[],
- isDeleteFolder = false
- ) => {
- this.closeFilePreview()
- let progress = 0
-
- // If every file has the 'prefix' property, then just construct the prefix
- // directly (from delete folder). Otherwise go by the opened folders.
- const prefixes = !files.some((f) => f.prefix)
- ? files.map((file) => {
- const { name, columnIndex } = file
- const pathToFile = this.openedFolders
- .slice(0, columnIndex)
- .map((folder) => folder.name)
- .join('/')
- this.updateRowStatus(name, STORAGE_ROW_STATUS.LOADING, columnIndex)
- return pathToFile.length > 0 ? `${pathToFile}/${name}` : name
- })
- : files.map((file) => `${file.prefix}/${file.name}`)
-
- this.clearSelectedItems()
-
- const toastId = toast(
- <SonnerProgress progress={0} message={`Deleting ${prefixes.length} file(s)...`} />,
- { closeButton: false, position: 'bottom-right' }
- )
-
- // batch BATCH_SIZE prefixes per request
- const batches = chunk(prefixes, BATCH_SIZE).map((batch) => () => {
- progress = progress + batch.length / prefixes.length
- return deleteBucketObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- paths: batch as string[],
- })
- })
-
- // make BATCH_SIZE requests at the same time
- await chunk(batches, BATCH_SIZE).reduce(async (previousPromise, nextBatch) => {
- await previousPromise
- await Promise.all(nextBatch.map((batch) => batch()))
- toast(
- <SonnerProgress
- progress={progress * 100}
- message={`Deleting ${prefixes.length} file(s)...`}
- />,
- { id: toastId, closeButton: false, position: 'bottom-right' }
- )
- }, Promise.resolve())
-
- if (!isDeleteFolder) {
- // If parent folders are empty, reinstate .emptyFolderPlaceholder to persist them
- const parentFolderPrefixes = uniq(
- prefixes.map((prefix) => {
- const segments = prefix.split('/')
- return segments.slice(0, segments.length - 1).join('/')
- })
- )
- await Promise.all(
- parentFolderPrefixes.map((prefix) => this.validateParentFolderEmpty(prefix))
- )
-
- toast.success(`Successfully deleted ${prefixes.length} file(s)`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- await this.refetchAllOpenedFolders()
- this.clearSelectedItemsToDelete()
- } else {
- toast.dismiss(toastId)
- }
- }
-
- downloadFolder = async (folder: StorageItemWithColumn) => {
- let progress = 0
- const toastId = toast.loading('Retrieving files from folder...')
-
- try {
- const files = await this.getAllItemsAlongFolder(folder)
-
- toast(
- <SonnerProgress
- progress={0}
- message={`Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`}
- />,
- { id: toastId, closeButton: false, position: 'bottom-right' }
- )
-
- const promises = files.map((file) => {
- const fileMimeType = (file.metadata?.mimetype as string) ?? null
- return () => {
- return new Promise<
- | {
- name: string
- prefix: string
- blob: Blob
- }
- | boolean
- >(async (resolve) => {
- try {
- const data = await downloadBucketObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: `${file.prefix}/${file.name}`,
- })
- progress = progress + 1 / files.length
-
- const blob = await data.blob()
- resolve({
- name: file.name,
- prefix: file.prefix,
- blob: new Blob([blob], { type: fileMimeType }),
- })
- } catch (error) {
- console.error('Failed to download file', `${file.prefix}/${file.name}`)
- resolve(false)
- }
- })
- }
- })
-
- const batchedPromises = chunk(promises, 10)
- const downloadedFiles = await batchedPromises.reduce(
- async (previousPromise, nextBatch) => {
- const previousResults = await previousPromise
- const batchResults = await Promise.allSettled(nextBatch.map((batch) => batch()))
- toast(
- <SonnerProgress
- progress={progress * 100}
- message={`Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`}
- />,
- { id: toastId, closeButton: false, position: 'bottom-right' }
- )
- return previousResults.concat(batchResults.map((x: any) => x.value).filter(Boolean))
- },
- Promise.resolve<
- {
- name: string
- prefix: string
- blob: Blob
- }[]
- >([])
- )
-
- const zipFileWriter = new BlobWriter('application/zip')
- const zipWriter = new ZipWriter(zipFileWriter, { bufferedWrite: true })
-
- if (downloadedFiles.length === 0) {
- toast.error(`Failed to download files from "${folder.name}"`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
-
- downloadedFiles.forEach((file) => {
- if (file.blob) zipWriter.add(`${file.prefix}/${file.name}`, new BlobReader(file.blob))
- })
-
- const blobURL = URL.createObjectURL(await zipWriter.close())
- const link = document.createElement('a')
- link.href = blobURL
- link.setAttribute('download', `${folder.name}.zip`)
- document.body.appendChild(link)
- link.click()
- link.parentNode?.removeChild(link)
-
- toast.success(
- downloadedFiles.length === files.length
- ? `Successfully downloaded folder "${folder.name}"`
- : `Downloaded folder "${folder.name}". However, ${
- files.length - downloadedFiles.length
- } files did not download successfully.`,
- { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
- )
- } catch (error: any) {
- toast.error(`Failed to download folder: ${error.message}`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
- }
-
- downloadSelectedFiles = async (files: StorageItemWithColumn[]) => {
- const lowestColumnIndex = Math.min(...files.map((file) => file.columnIndex))
-
- const formattedFilesWithPrefix: any[] = files.map((file) => {
- const { name, columnIndex } = file
- const pathToFile = this.openedFolders
- .slice(lowestColumnIndex, columnIndex)
- .map((folder) => folder.name)
- .join('/')
- const formattedPathToFile = pathToFile.length > 0 ? `${pathToFile}/${name}` : name
- return { ...file, formattedPathToFile }
- })
-
- let progress = 0
- const returnBlob = true
- const showIndividualToast = false
- const toastId = toast.loading(
- `Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`
- )
-
- const promises = formattedFilesWithPrefix.map((file) => {
- return () => {
- return new Promise<{ name: string; blob: Blob } | boolean>(async (resolve) => {
- const data = await downloadFile({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- file,
- returnBlob,
- })
- progress = progress + 1 / formattedFilesWithPrefix.length
- if (isObject(data)) {
- resolve({ ...data, name: file.formattedPathToFile })
- }
- resolve(false)
- })
- }
- })
-
- const batchedPromises = chunk(promises, 10)
- const downloadedFiles = await batchedPromises.reduce(async (previousPromise, nextBatch) => {
- const previousResults = await previousPromise
- const batchResults = await Promise.allSettled(nextBatch.map((batch) => batch()))
- toast(
- <SonnerProgress
- progress={progress * 100}
- message={`Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`}
- />,
- { id: toastId, closeButton: false, position: 'bottom-right' }
- )
- return previousResults.concat(batchResults.map((x: any) => x.value).filter(Boolean))
- }, Promise.resolve<{ name: string; blob: Blob }[]>([]))
-
- const zipFileWriter = new BlobWriter('application/zip')
- const zipWriter = new ZipWriter(zipFileWriter, { bufferedWrite: true })
- downloadedFiles.forEach((file) => {
- zipWriter.add(file.name, new BlobReader(file.blob))
- })
-
- const blobURL = URL.createObjectURL(await zipWriter.close())
- const link = document.createElement('a')
- link.href = blobURL
- link.setAttribute('download', `supabase-files.zip`)
- document.body.appendChild(link)
- link.click()
- link.parentNode?.removeChild(link)
-
- toast.success(`Successfully downloaded ${downloadedFiles.length} files`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
-
- renameFile = async (file: StorageItem, newName: string, columnIndex: number) => {
- const originalName = file.name
- if (originalName === newName || newName.length === 0) {
- this.updateRowStatus(originalName, STORAGE_ROW_STATUS.READY, columnIndex)
- } else {
- this.updateRowStatus(originalName, STORAGE_ROW_STATUS.LOADING, columnIndex, newName)
- const includeBucket = false
- const pathToFile = this.getPathAlongOpenedFolders(includeBucket)
-
- const fromPath = pathToFile.length > 0 ? `${pathToFile}/${originalName}` : originalName
- const toPath = pathToFile.length > 0 ? `${pathToFile}/${newName}` : newName
-
- try {
- const data = await moveStorageObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- from: fromPath,
- to: toPath,
- })
-
- toast.success(`Successfully renamed "${originalName}" to "${newName}"`)
-
- // TODO: Should we invalidate the file preview cache when renaming files?
-
- if (this.selectedFilePreview?.name === originalName) {
- const { previewUrl, ...fileData } = file as any
- this.setFilePreview({ ...fileData, name: newName })
- }
-
- await this.refetchAllOpenedFolders()
- } catch (error: any) {
- toast.error(`Failed to rename file: ${error.message}`)
- }
- }
- }
-
- /* Folders CRUD */
-
- fetchFolderContents = async (
- folderId: string | null,
- folderName: string,
- index: number,
- searchString: string = ''
- ) => {
- if (this.selectedBucket.id === undefined) return
-
- this.abortApiCalls()
-
- this.updateRowStatus(folderName, STORAGE_ROW_STATUS.LOADING, index)
- this.pushColumnAtIndex(
- { id: folderId, name: folderName, status: STORAGE_ROW_STATUS.LOADING, items: [] },
- index
- )
-
- const prefix = this.openedFolders
- .slice(0, index + 1)
- .map((folder) => folder.name)
- .join('/')
- const options = {
- limit: LIMIT,
- offset: OFFSET,
- search: searchString,
- sortBy: { column: this.sortBy, order: this.sortByOrder },
- }
-
- try {
- const data = await listBucketObjects(
- {
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: prefix,
- options,
- },
- this.abortController?.signal
- )
-
- this.updateRowStatus(folderName, STORAGE_ROW_STATUS.READY, index)
-
- const formattedItems = this.formatFolderItems(data, prefix)
- this.pushColumnAtIndex(
- {
- id: folderId || folderName,
- name: folderName,
- status: STORAGE_ROW_STATUS.READY,
- items: formattedItems,
- hasMoreItems: formattedItems.length === LIMIT,
- isLoadingMoreItems: false,
- },
- index
- )
- } catch (error: any) {
- if (error.name === 'AbortError') {
- this.updateRowStatus(folderName, STORAGE_ROW_STATUS.READY, index)
- } else {
- toast.error(`Failed to retrieve folder contents from "${folderName}": ${error.message}`)
- }
- }
- }
-
- fetchMoreFolderContents = async (
- index: number,
- column: StorageColumn,
- searchString: string = ''
- ) => {
- this.setColumnIsLoadingMore(index)
-
- const prefix = this.openedFolders.map((folder) => folder.name).join('/')
- const options = {
- limit: LIMIT,
- offset: column.items.length,
- search: searchString,
- sortBy: { column: this.sortBy, order: this.sortByOrder },
- }
-
- try {
- const data = await listBucketObjects(
- { projectRef: this.projectRef, bucketId: this.selectedBucket.id, path: prefix, options },
- this.abortController?.signal
- )
-
- // Add items to column
- const formattedItems = this.formatFolderItems(data)
- this.columns = this.columns.map((col, idx) => {
- if (idx === index) {
- return {
- ...col,
- items: col.items.concat(formattedItems),
- isLoadingMoreItems: false,
- hasMoreItems: data.length === LIMIT,
- }
- }
- return col
- })
- } catch (error: any) {
- if (!error.message.includes('aborted')) {
- toast.error(`Failed to retrieve more folder contents: ${error.message}`)
- }
- }
- }
-
- refetchAllOpenedFolders = async () => {
- const paths = this.openedFolders.map((folder) => folder.name)
- await this.fetchFoldersByPath(paths)
- }
-
- fetchFoldersByPath = async (
- paths: string[],
- searchString: string = '',
- showLoading: boolean = false
- ) => {
- if (this.selectedBucket.id === undefined) return
-
- const pathsWithEmptyPrefix = [''].concat(paths)
-
- if (showLoading) {
- this.columns = [this.selectedBucket.name].concat(paths).map((path) => {
- return { id: path, name: path, status: STORAGE_ROW_STATUS.LOADING, items: [] }
- })
- }
-
- const foldersItems = await Promise.all(
- pathsWithEmptyPrefix.map(async (path, idx) => {
- const prefix = paths.slice(0, idx).join('/')
- const options = {
- limit: LIMIT,
- offset: OFFSET,
- search: searchString,
- sortBy: { column: this.sortBy, order: this.sortByOrder },
- }
-
- try {
- const data = await listBucketObjects({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: prefix,
- options,
- })
- return data
- } catch (error: any) {
- toast.error(`Failed to fetch folders: ${error.message}`)
- return []
- }
- })
- )
-
- const formattedFolders = foldersItems.map((folderItems, idx) => {
- const formattedItems = this.formatFolderItems(folderItems)
- return {
- id: null,
- status: STORAGE_ROW_STATUS.READY,
- name: idx === 0 ? this.selectedBucket.name : pathsWithEmptyPrefix[idx],
- items: formattedItems,
- hasMoreItems: formattedItems.length === LIMIT,
- isLoadingMoreItems: false,
- }
- })
-
- // Package into columns and update this.columns
- this.columns = formattedFolders
-
- // Update openedFolders as well
- const updatedOpenedFolders: StorageItem[] = paths.map((path, idx) => {
- const folderInfo = find(formattedFolders[idx].items, { name: path })
- // Folder doesnt exist, FE just scaffolds a "fake" folder
- if (!folderInfo) {
- return {
- id: null,
- name: path,
- type: STORAGE_ROW_TYPES.FOLDER,
- status: STORAGE_ROW_STATUS.READY,
- metadata: null,
- isCorrupted: false,
- created_at: null,
- updated_at: null,
- last_accessed_at: null,
- }
- }
- return folderInfo
- })
- this.openedFolders = updatedOpenedFolders
- }
-
- // Check parent folder if its empty, if yes, reinstate .emptyFolderPlaceholder
- // Used when deleting folder or deleting files
- private validateParentFolderEmpty = async (parentFolderPrefix: string) => {
- try {
- const data = await listBucketObjects({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: parentFolderPrefix,
- options: this.DEFAULT_OPTIONS,
- })
-
- if (data.length === 0) {
- const prefixToPlaceholder = `${parentFolderPrefix}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`
- await this.supabaseClient.storage
- .from(this.selectedBucket.name)
- .upload(prefixToPlaceholder, new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME))
- }
- } catch (error) {}
- }
-
- deleteFolder = async (folder: StorageItemWithColumn) => {
- try {
- const isDeleteFolder = true
- const files = await this.getAllItemsAlongFolder(folder)
- await this.deleteFiles(files as any[], isDeleteFolder)
-
- this.popColumnAtIndex(folder.columnIndex)
- this.popOpenedFoldersAtIndex(folder.columnIndex - 1)
-
- if (folder.columnIndex > 0) {
- const parentFolderPrefix = this.openedFolders
- .slice(0, folder.columnIndex)
- .map((folder) => folder.name)
- .join('/')
- if (parentFolderPrefix.length > 0) await this.validateParentFolderEmpty(parentFolderPrefix)
- }
-
- await this.refetchAllOpenedFolders()
- this.clearSelectedItemsToDelete()
-
- toast.success(`Successfully deleted ${folder.name}`)
- } catch (error: any) {
- toast.error(`Failed to delete folder: ${error.message}`)
- }
- }
-
- renameFolder = async (folder: StorageItemWithColumn, newName: string, columnIndex: number) => {
- const originalName = folder.name
- if (originalName === newName) {
- return this.updateRowStatus(originalName, STORAGE_ROW_STATUS.READY, columnIndex)
- }
-
- const toastId = toast(
- <SonnerProgress progress={0} message={`Renaming folder to ${newName}`} />,
- { closeButton: false, position: 'bottom-right' }
- )
-
- try {
- /**
- * Catch any folder names that contain slash or backslash
- *
- * this is because slashes are used to denote
- * children/parent relationships in bucket
- *
- * todo: move this to a util file, as createFolder() uses same logic
- */
- if (newName.includes('/') || newName.includes('\\')) {
- return toast.error(`Folder name cannot contain forward or back slashes.`)
- }
-
- this.updateRowStatus(originalName, STORAGE_ROW_STATUS.LOADING, columnIndex, newName)
- const files = await this.getAllItemsAlongFolder(folder)
-
- let progress = 0
- let hasErrors = false
-
- // Make this batched promises into a reusable function for storage, i think this will be super helpful
- const promises = files.map((file) => {
- const fromPath = `${file.prefix}/${file.name}`
- const pathSegments = fromPath.split('/')
- const toPath = pathSegments
- .slice(0, columnIndex)
- .concat(newName)
- .concat(pathSegments.slice(columnIndex + 1))
- .join('/')
- return () => {
- return new Promise<void>(async (resolve) => {
- progress = progress + 1 / files.length
- try {
- await moveStorageObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- from: fromPath,
- to: toPath,
- })
- } catch (error) {
- hasErrors = true
- toast.error(`Failed to move ${fromPath} to the new folder`)
- }
- resolve()
- })
- }
- })
-
- const batchedPromises = chunk(promises, BATCH_SIZE)
- // [Joshen] I realised this can be simplified with just a vanilla for loop, no need for reduce
- // Just take note, but if it's working fine, then it's okay
-
- await batchedPromises.reduce(async (previousPromise, nextBatch) => {
- await previousPromise
- await Promise.all(nextBatch.map((batch) => batch()))
- toast(
- <SonnerProgress progress={progress * 100} message={`Renaming folder to ${newName}`} />,
- { id: toastId, closeButton: false, position: 'bottom-right' }
- )
- }, Promise.resolve())
-
- if (!hasErrors) {
- toast.success(`Successfully renamed folder to ${newName}`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- } else {
- toast.error(`Renamed folder to ${newName} with some errors`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
- await this.refetchAllOpenedFolders()
-
- // TODO: Should we invalidate the file preview cache when renaming folders?
- } catch (e: any) {
- toast.error(`Failed to rename folder to ${newName}: ${e.message}`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
- }
-
- /*
- Recursively returns a list of items along every directory within the specified base folder
- Each item has an extra property 'prefix' which has the prefix that leads to the item
- Used specifically for any operation that deals with every file along the folder
- e.g Delete folder, rename folder
- */
- private getAllItemsAlongFolder = async (folder: {
- name: string
- columnIndex: number
- prefix?: string
- }): Promise<(StorageObject & { prefix: string })[]> => {
- const items: (StorageObject & { prefix: string })[] = []
-
- let hasError = false
- let formattedPathToFolder = ''
- const { name, columnIndex, prefix } = folder
-
- if (prefix === undefined) {
- const pathToFolder = this.openedFolders
- .slice(0, columnIndex)
- .map((folder) => folder.name)
- .join('/')
- formattedPathToFolder = pathToFolder.length > 0 ? `${pathToFolder}/${name}` : name
- } else {
- formattedPathToFolder = `${prefix}/${name}`
- }
-
- // [Joshen] limit is set to 10k to optimize reduction of requests, we've done some experiments
- // that prove that the time to fetch all files in a folder reduces as the batch size increases
- // 10k however, is the hard limit at the API level.
- const options = {
- limit: 10000,
- offset: OFFSET,
- sortBy: { column: this.sortBy, order: this.sortByOrder },
- }
- let folderContents: StorageObject[] = []
-
- for (;;) {
- try {
- const data = await listBucketObjects({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: formattedPathToFolder,
- options,
- })
- folderContents = folderContents.concat(data)
- options.offset += options.limit
- if ((data || []).length < options.limit) {
- break
- }
- } catch (e) {
- hasError = true
- break
- }
- }
-
- if (hasError) {
- throw new Error('Failed to retrieve all files within folder')
- }
-
- const subfolders = folderContents?.filter((item) => item.id === null) ?? []
- const folderItems = folderContents?.filter((item) => item.id !== null) ?? []
-
- folderItems.forEach((item) => items.push({ ...item, prefix: formattedPathToFolder }))
-
- const subFolderContents = await Promise.all(
- subfolders.map((folder) =>
- this.getAllItemsAlongFolder({ ...folder, columnIndex: 0, prefix: formattedPathToFolder })
- )
- )
- subFolderContents.map((subfolderContent) => {
- subfolderContent.map((item) => items.push(item))
- })
-
- return items
- }
-
- /* UI Helper functions */
-
- private sanitizeNameForDuplicateInColumn = (
- name: string,
- autofix: boolean = false,
- columnIndex: number = this.getLatestColumnIndex()
- ) => {
- const currentColumn = this.columns[columnIndex]
- const currentColumnItems = currentColumn.items.filter(
- (item) => item.status !== STORAGE_ROW_STATUS.EDITING
- )
- const hasSameNameInColumn = currentColumnItems.filter((item) => item.name === name).length > 0
-
- if (hasSameNameInColumn) {
- if (autofix) {
- const [fileName, fileExt] = name.split('.')
- const dupeNameRegex = new RegExp(
- `${fileName} \\([-0-9]+\\)${fileExt ? '.' + fileExt : ''}$`
- )
- const itemsWithSameNameInColumn = currentColumnItems.filter((item) =>
- item.name.match(dupeNameRegex)
- )
-
- const updatedFileName = fileName + ` (${itemsWithSameNameInColumn.length + 1})`
- return fileExt ? `${updatedFileName}.${fileExt}` : updatedFileName
- } else {
- toast.error(
- `The name ${name} already exists in the current directory. Please use a different name.`
- )
- return null
- }
- }
-
- return name
- }
-
- private formatFolderItems = (items: StorageObject[] = [], prefix?: string): StorageItem[] => {
- const formattedItems =
- (items ?? [])
- ?.filter((item) => item.name !== EMPTY_FOLDER_PLACEHOLDER_FILE_NAME)
- .map((item) => {
- const type = item.id ? STORAGE_ROW_TYPES.FILE : STORAGE_ROW_TYPES.FOLDER
-
- const durationSinceCreated = Number(new Date()) - Number(new Date(item.created_at))
- const isCorrupted =
- type === STORAGE_ROW_TYPES.FILE &&
- !item.metadata &&
- durationSinceCreated >= CORRUPTED_THRESHOLD_MS
-
- const status =
- type === STORAGE_ROW_TYPES.FILE &&
- !item.metadata &&
- durationSinceCreated <= CORRUPTED_THRESHOLD_MS
- ? STORAGE_ROW_STATUS.LOADING
- : STORAGE_ROW_STATUS.READY
-
- const itemObj = {
- ...item,
- metadata: item.metadata as any as StorageItemMetadata,
- type,
- status,
- isCorrupted,
- path: !!prefix ? `${prefix}/${item.name}` : item.name,
- }
- return itemObj
- }) ?? []
- return formattedItems
- }
-
- private addTempRow = (
- type: STORAGE_ROW_TYPES,
- name: string,
- status: STORAGE_ROW_STATUS,
- columnIndex: number,
- metadata: StorageItemMetadata | null,
- isPrepend: boolean = false
- ) => {
- const updatedColumns = this.columns.map((column, idx) => {
- if (idx === columnIndex) {
- const tempRow = { type, name, status, metadata } as StorageItem
- const updatedItems = isPrepend
- ? [tempRow].concat(column.items)
- : column.items.concat([tempRow])
- return { ...column, items: updatedItems }
- }
- return column
- })
- this.columns = updatedColumns
- }
-
- private removeTempRows = (columnIndex: number) => {
- const updatedColumns = this.columns.map((column, idx) => {
- if (idx === columnIndex) {
- const updatedItems = column.items.filter((item) => has(item, 'id'))
- return { ...column, items: updatedItems }
- }
- return column
- })
- this.columns = updatedColumns
- }
-
- setSelectedItemToRename = (file: { name: string; columnIndex: number }) => {
- this.updateRowStatus(file.name, STORAGE_ROW_STATUS.EDITING, file.columnIndex)
- }
-
- private updateRowStatus = (
- name: string,
- status: STORAGE_ROW_STATUS,
- columnIndex: number = this.getLatestColumnIndex(),
- updatedName?: string
- ) => {
- const updatedColumns = this.columns.map((column, idx) => {
- if (idx === columnIndex) {
- const updatedColumnItems = column.items.map((item) => {
- if (item.name === name) {
- return {
- ...item,
- status,
- ...(updatedName && { name: updatedName }),
- }
- }
- return item
- })
- return { ...column, items: updatedColumnItems }
- }
- return column
- })
- this.columns = updatedColumns
- }
-
- private updateFolderAfterEdit = (
- folderName: string,
- columnIndex: number = this.getLatestColumnIndex(),
- status: STORAGE_ROW_STATUS = STORAGE_ROW_STATUS.READY
- ) => {
- const updatedColumns = this.columns.map((column, idx) => {
- if (idx === columnIndex) {
- const updatedItems = column.items.map((item) => {
- if (item.status === STORAGE_ROW_STATUS.EDITING) {
- const currentTime = new Date().toISOString()
- return {
- ...item,
- status,
- name: folderName,
- createdAt: currentTime,
- lastAccessedAt: currentTime,
- updatedAt: currentTime,
- metadata: null,
- id: null,
- }
- }
- return item
- })
- return { ...column, items: updatedItems }
- }
- return column
- })
- this.columns = updatedColumns
- }
-
- /* User Preferences */
-
- private updateExplorerPreferences = () => {
- const localStorageKey = this.getLocalStorageKey()
- const existingPreferences = tryParseJson(localStorage?.getItem(localStorageKey))
-
- if (this.projectRef) {
- localStorage.setItem(
- localStorageKey,
- JSON.stringify({
- sortBy: this.sortBy,
- sortByOrder: this.sortByOrder,
- view: existingPreferences?.view ?? STORAGE_VIEWS.COLUMNS,
- })
- )
- }
- }
-
- loadExplorerPreferences = () => {
- const localStorageKey = this.getLocalStorageKey()
- const preferences = localStorage?.getItem(localStorageKey) ?? undefined
- if (preferences !== undefined) {
- const { sortBy, sortByOrder } = JSON.parse(preferences)
- this.sortBy = sortBy
- this.sortByOrder = sortByOrder
- }
- }
-
- selectRangeItems = (columnIndex: number, toItemIndex: number) => {
- const columnItems = this.columns[columnIndex].items
- const toItem = columnItems[toItemIndex]
- const selectedItemIds = this.selectedItems.map((item) => item.id)
- const lastSelectedItemId = selectedItemIds[selectedItemIds.length - 1]
- const lastSelectedItemIndex = findIndex(columnItems, { id: lastSelectedItemId })
-
- // Get the start and end index of the range to select
- const start = Math.min(toItemIndex, lastSelectedItemIndex)
- const end = Math.max(toItemIndex, lastSelectedItemIndex)
-
- // Get the range to select and reverse the order if necessary
- const rangeToSelect = columnItems
- .slice(start, end + 1)
- // we need `columnIndex` in all item of `selectedItems`
- .map((item) => ({ ...item, columnIndex }))
- if (toItemIndex < lastSelectedItemIndex) {
- rangeToSelect.reverse()
- }
-
- if (selectedItemIds.includes(toItem.id)) {
- const rangeToDeselectIds = rangeToSelect.map((item) => item.id)
- // Deselect all items within the selection range
- this.setSelectedItems(
- this.selectedItems.filter(
- (item) => item.id === toItem.id || !rangeToDeselectIds.includes(item.id)
- )
- )
- } else {
- // Select items within the range
- this.setSelectedItems(uniqBy(this.selectedItems.concat(rangeToSelect), 'id'))
- }
- }
-
- private calculateTotalRemainingTime(progresses: UploadProgress[]) {
- let totalRemainingTime = 0
- let totalRemainingBytes = 0
-
- progresses.forEach((progress) => {
- totalRemainingBytes += progress.remainingBytes
- if (totalRemainingBytes === 0) {
- return
- }
- const weight = progress.remainingBytes / totalRemainingBytes
- totalRemainingTime += weight * progress.remainingTime
- })
-
- return totalRemainingTime
- }
-}
-
-export default StorageExplorerStore
diff --git a/apps/studio/package.json b/apps/studio/package.json
index 74474b2d40f..a08a52f91a5 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -80,8 +80,6 @@
"markdown-table": "^3.0.3",
"memoize-one": "^5.0.1",
"mime-db": "^1.53.0",
- "mobx": "^6.10.2",
- "mobx-react-lite": "^4.0.5",
"monaco-editor": "0.52.2",
"next": "~15.3.0",
"next-themes": "^0.3.0",
diff --git a/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx b/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
index 20f1c7a3b54..6537c2f4b3b 100644
--- a/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
+++ b/apps/studio/pages/project/[ref]/storage/buckets/[bucketId].tsx
@@ -1,23 +1,25 @@
import { useParams } from 'common'
import { find } from 'lodash'
+import DefaultLayout from 'components/layouts/DefaultLayout'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import StorageBucketsError from 'components/layouts/StorageLayout/StorageBucketsError'
import StorageLayout from 'components/layouts/StorageLayout/StorageLayout'
-import DefaultLayout from 'components/layouts/DefaultLayout'
import { StorageExplorer } from 'components/to-be-cleaned/Storage'
import { useBucketsQuery } from 'data/storage/buckets-query'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import type { NextPageWithLayout } from 'types'
const PageLayout: NextPageWithLayout = () => {
const { ref, bucketId } = useParams()
const { project } = useProjectContext()
+ const { projectRef } = useStorageExplorerStateSnapshot()
const { data, isSuccess, isError, error } = useBucketsQuery({ projectRef: ref })
const buckets = data ?? []
const bucket = find(buckets, { id: bucketId })
- if (!project) return null
+ if (!project || !projectRef) return null
return (
<div className="storage-container flex flex-grow p-4">
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index a4dfab69d5a..484c974d71a 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -1,23 +1,86 @@
+import { capitalize, chunk, compact, find, findIndex, has, isObject, uniq, uniqBy } from 'lodash'
import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
import { useLatest } from 'react-use'
+import { toast } from 'sonner'
+import * as tus from 'tus-js-client'
import { proxy, snapshot, useSnapshot } from 'valtio'
+import { createClient, SupabaseClient } from '@supabase/supabase-js'
+import { BlobReader, BlobWriter, ZipWriter } from '@zip.js/zip.js'
+import { LOCAL_STORAGE_KEYS } from 'common'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import {
+ STORAGE_ROW_STATUS,
+ STORAGE_ROW_TYPES,
STORAGE_SORT_BY,
STORAGE_SORT_BY_ORDER,
STORAGE_VIEWS,
} from 'components/to-be-cleaned/Storage/Storage.constants'
-import { LOCAL_STORAGE_KEYS } from 'common'
+import {
+ StorageColumn,
+ StorageItem,
+ StorageItemMetadata,
+ StorageItemWithColumn,
+} from 'components/to-be-cleaned/Storage/Storage.types'
+import {
+ calculateTotalRemainingTime,
+ downloadFile,
+ EMPTY_FOLDER_PLACEHOLDER_FILE_NAME,
+ formatFolderItems,
+ formatTime,
+ getFilesDataTransferItems,
+} from 'components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils'
+import { convertFromBytes } from 'components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils'
+import { InlineLink } from 'components/ui/InlineLink'
+import { configKeys } from 'data/config/keys'
+import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { ProjectStorageConfigResponse } from 'data/config/project-storage-config-query'
+import { getQueryClient } from 'data/query-client'
+import { deleteBucketObject } from 'data/storage/bucket-object-delete-mutation'
+import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
+import { listBucketObjects, StorageObject } from 'data/storage/bucket-objects-list-mutation'
+import { Bucket } from 'data/storage/buckets-query'
+import { moveStorageObject } from 'data/storage/object-move-mutation'
+import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'
import { tryParseJson } from 'lib/helpers'
+import { lookupMime } from 'lib/mime'
+import { Button, SONNER_DEFAULT_DURATION, SonnerProgress } from 'ui'
+
+type UploadProgress = {
+ percentage: number
+ elapsed: number
+ uploadSpeed: number
+ remainingBytes: number
+ remainingTime: number
+}
+
+const LIMIT = 200
+const OFFSET = 0
+const BATCH_SIZE = 2
const DEFAULT_PREFERENCES = {
view: STORAGE_VIEWS.COLUMNS,
sortBy: STORAGE_SORT_BY.NAME,
sortByOrder: STORAGE_SORT_BY_ORDER.ASC,
}
+const STORAGE_PROGRESS_INFO_TEXT = "Do not close the browser until it's completed"
-function createStorageExplorerState({ projectRef }: { projectRef: string }) {
+let abortController: any
+if (typeof window !== 'undefined') {
+ abortController = new AbortController()
+}
+
+function createStorageExplorerState({
+ projectRef,
+ resumableUploadUrl,
+ serviceKey,
+ supabaseClient,
+}: {
+ projectRef: string
+ resumableUploadUrl: string
+ serviceKey: string
+ supabaseClient?: SupabaseClient<any, 'public', any>
+}) {
const localStorageKey = LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(projectRef)
const { view, sortBy, sortByOrder } =
(typeof window !== 'undefined' && tryParseJson(localStorage?.getItem(localStorageKey))) ||
@@ -25,31 +88,1605 @@ function createStorageExplorerState({ projectRef }: { projectRef: string }) {
const state = proxy({
projectRef,
+ supabaseClient,
+ resumableUploadUrl,
+ serviceKey,
+ uploadProgresses: [] as UploadProgress[],
- view,
- sortBy,
- sortByOrder,
- isSearching: false,
+ // abortController,
+ abortApiCalls: () => {
+ if (abortController) {
+ abortController.abort()
+ abortController = new AbortController()
+ }
+ },
+
+ abortUploadCallbacks: {} as { [key: string]: (() => void)[] },
+ abortUploads: (toastId: string | number) => {
+ state.abortUploadCallbacks[toastId].forEach((callback) => callback())
+ state.abortUploadCallbacks[toastId] = []
+ },
+
+ columns: [] as StorageColumn[],
+ popColumn: () => {
+ state.abortApiCalls()
+ state.columns = state.columns.slice(0, state.getLatestColumnIndex())
+ },
+ popColumnAtIndex: (index: number) => {
+ state.columns = state.columns.slice(0, index + 1)
+ },
+ pushColumnAtIndex: (column: StorageColumn, index: number) => {
+ state.columns = state.columns.slice(0, index + 1).concat([column])
+ },
+
+ openedFolders: [] as StorageItem[],
+ pushOpenedFolderAtIndex: (folder: StorageItem, index: number) => {
+ state.openedFolders = state.openedFolders.slice(0, index).concat(folder)
+ },
+ popOpenedFolders: () => {
+ state.openedFolders = state.openedFolders.slice(0, state.openedFolders.length - 1)
+ },
+
+ popOpenedFoldersAtIndex: (index: number) => {
+ state.openedFolders = state.openedFolders.slice(0, index + 1)
+ },
+ clearOpenedFolders: () => {
+ state.openedFolders = []
+ },
+
+ selectedItems: [] as StorageItemWithColumn[],
+ setSelectedItems: (items: StorageItemWithColumn[]) => (state.selectedItems = items),
+ clearSelectedItems: (columnIndex?: number) => {
+ if (columnIndex !== undefined) {
+ state.selectedItems = state.selectedItems.filter((item) => item.columnIndex !== columnIndex)
+ } else {
+ state.selectedItems = []
+ }
+ },
+
+ selectedItemsToDelete: [] as StorageItemWithColumn[],
+ setSelectedItemsToDelete: (items: StorageItemWithColumn[]) => {
+ state.selectedItemsToDelete = items
+ },
+
+ selectedItemsToMove: [] as StorageItemWithColumn[],
+ setSelectedItemsToMove: (items: StorageItemWithColumn[]) => {
+ state.selectedItemsToMove = items
+ },
+
+ selectedBucket: {} as Bucket,
+ setSelectedBucket: (bucket: Bucket) => {
+ state.selectedBucket = bucket
+ state.setSelectedFilePreview(undefined)
+ state.clearOpenedFolders()
+ state.clearSelectedItems()
+ },
+
+ setSelectedItemToRename: (file: { name: string; columnIndex: number }) => {
+ state.updateRowStatus({
+ name: file.name,
+ status: STORAGE_ROW_STATUS.EDITING,
+ columnIndex: file.columnIndex,
+ })
+ },
+ view,
setView: (value: STORAGE_VIEWS) => {
state.view = value
state.updateExplorerPreference()
},
+
+ sortBy,
setSortBy: (value: STORAGE_SORT_BY) => {
state.sortBy = value
state.updateExplorerPreference()
+ state.setSelectedFilePreview(undefined)
},
+
+ sortByOrder,
setSortByOrder: (value: STORAGE_SORT_BY_ORDER) => {
state.sortByOrder = value
state.updateExplorerPreference()
+ state.setSelectedFilePreview(undefined)
},
+
+ isSearching: false,
setIsSearching: (value: boolean) => (state.isSearching = value),
+ selectedFilePreview: undefined as StorageItemWithColumn | undefined,
+ setSelectedFilePreview: (file?: StorageItemWithColumn) => (state.selectedFilePreview = file),
+
+ selectedFileCustomExpiry: undefined as StorageItem | undefined,
+ setSelectedFileCustomExpiry: (item?: StorageItem) => (state.selectedFileCustomExpiry = item),
+
updateExplorerPreference: () => {
const localStorageKey = LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(projectRef)
const { view, sortBy, sortByOrder } = state
localStorage.setItem(localStorageKey, JSON.stringify({ view, sortBy, sortByOrder }))
},
+
+ openBucket: async (bucket: Bucket) => {
+ const { id, name } = bucket
+ state.setSelectedBucket(bucket)
+ await state.fetchFolderContents({ folderId: id, folderName: name, index: -1 })
+ },
+
+ // Functions that manage the UI of the Storage Explorer
+
+ getLatestColumnIndex: () => {
+ return state.columns.length - 1
+ },
+
+ setColumnIsLoadingMore: (index: number, isLoadingMoreItems: boolean = true) => {
+ state.columns = state.columns.map((col, idx) => {
+ return idx === index ? { ...col, isLoadingMoreItems } : col
+ })
+ },
+
+ // ======== Folders CRUD ========
+
+ getPathAlongOpenedFolders: (includeBucket = true) => {
+ if (includeBucket) {
+ return state.openedFolders.length > 0
+ ? `${state.selectedBucket.name}/${state.openedFolders.map((folder) => folder.name).join('/')}`
+ : state.selectedBucket.name
+ }
+ return state.openedFolders.map((folder) => folder.name).join('/')
+ },
+
+ getPathAlongFoldersToIndex: (index: number) => {
+ return state.openedFolders
+ .slice(0, index)
+ .map((folder) => folder.name)
+ .join('/')
+ },
+
+ addNewFolderPlaceholder: (columnIndex: number) => {
+ const isPrepend = true
+ const folderName = 'Untitled folder'
+ const folderType = STORAGE_ROW_TYPES.FOLDER
+ const columnIdx = columnIndex === -1 ? state.getLatestColumnIndex() : columnIndex
+ state.addTempRow({
+ type: folderType,
+ name: folderName,
+ status: STORAGE_ROW_STATUS.EDITING,
+ columnIndex: columnIdx,
+ metadata: null,
+ isPrepend,
+ })
+ },
+
+ addNewFolder: async (folderName: string, columnIndex: number) => {
+ if (!state.supabaseClient) return console.error('Supabase Client is missing')
+
+ const autofix = false
+ const formattedName = state.sanitizeNameForDuplicateInColumn({
+ name: folderName,
+ autofix,
+ columnIndex,
+ })
+ if (formattedName === null) return
+
+ if (!/^[a-zA-Z0-9_-\s]*$/.test(formattedName)) {
+ return toast.error('Folder name contains invalid special characters')
+ }
+
+ if (formattedName.length === 0) {
+ return state.removeTempRows(columnIndex)
+ }
+
+ state.updateFolderAfterEdit({ folderName: formattedName, columnIndex })
+
+ const emptyPlaceholderFile = `${formattedName}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`
+ const pathToFolder = state.openedFolders
+ .slice(0, columnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+ const formattedPathToEmptyPlaceholderFile =
+ pathToFolder.length > 0 ? `${pathToFolder}/${emptyPlaceholderFile}` : emptyPlaceholderFile
+
+ await state.supabaseClient.storage
+ .from(state.selectedBucket.name)
+ .upload(
+ formattedPathToEmptyPlaceholderFile,
+ new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME)
+ )
+
+ if (pathToFolder.length > 0) {
+ await deleteBucketObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ paths: [`${pathToFolder}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`],
+ })
+ }
+ },
+
+ fetchFolderContents: async ({
+ folderId,
+ folderName,
+ index,
+ searchString,
+ }: {
+ folderId: string | null
+ folderName: string
+ index: number
+ searchString?: string
+ }) => {
+ state.abortApiCalls()
+ state.updateRowStatus({
+ name: folderName,
+ status: STORAGE_ROW_STATUS.LOADING,
+ columnIndex: index,
+ })
+ state.pushColumnAtIndex(
+ { id: folderId, name: folderName, status: STORAGE_ROW_STATUS.LOADING, items: [] },
+ index
+ )
+
+ const prefix = state.openedFolders
+ .slice(0, index + 1)
+ .map((folder) => folder.name)
+ .join('/')
+ const options = {
+ limit: LIMIT,
+ offset: OFFSET,
+ search: searchString,
+ sortBy: { column: state.sortBy, order: state.sortByOrder },
+ }
+
+ try {
+ const data = await listBucketObjects(
+ {
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ path: prefix,
+ options,
+ },
+ abortController?.signal
+ )
+
+ state.updateRowStatus({
+ name: folderName,
+ status: STORAGE_ROW_STATUS.READY,
+ columnIndex: index,
+ })
+ const formattedItems = formatFolderItems(data, prefix)
+ state.pushColumnAtIndex(
+ {
+ id: folderId || folderName,
+ name: folderName,
+ status: STORAGE_ROW_STATUS.READY,
+ items: formattedItems,
+ hasMoreItems: formattedItems.length === LIMIT,
+ isLoadingMoreItems: false,
+ },
+ index
+ )
+ } catch (error: any) {
+ if (error.name === 'AbortError') {
+ state.updateRowStatus({
+ name: folderName,
+ status: STORAGE_ROW_STATUS.READY,
+ columnIndex: index,
+ })
+ } else {
+ toast.error(`Failed to retrieve folder contents from "${folderName}": ${error.message}`)
+ }
+ }
+ },
+
+ fetchMoreFolderContents: async ({
+ index,
+ column,
+ searchString = '',
+ }: {
+ index: number
+ column: StorageColumn
+ searchString?: string
+ }) => {
+ state.setColumnIsLoadingMore(index)
+
+ const prefix = state.openedFolders.map((folder) => folder.name).join('/')
+ const options = {
+ limit: LIMIT,
+ offset: column.items.length,
+ search: searchString,
+ sortBy: { column: state.sortBy, order: state.sortByOrder },
+ }
+
+ try {
+ const data = await listBucketObjects(
+ {
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ path: prefix,
+ options,
+ },
+ abortController?.signal
+ )
+
+ // Add items to column
+ const formattedItems = formatFolderItems(data)
+ state.columns = state.columns.map((col, idx) => {
+ if (idx === index) {
+ return {
+ ...col,
+ items: col.items.concat(formattedItems),
+ isLoadingMoreItems: false,
+ hasMoreItems: data.length === LIMIT,
+ }
+ }
+ return col
+ })
+ } catch (error: any) {
+ if (!error.message.includes('aborted')) {
+ toast.error(`Failed to retrieve more folder contents: ${error.message}`)
+ }
+ }
+ },
+
+ refetchAllOpenedFolders: async () => {
+ const paths = state.openedFolders.map((folder) => folder.name)
+ await state.fetchFoldersByPath({ paths })
+ },
+
+ fetchFoldersByPath: async ({
+ paths,
+ searchString = '',
+ showLoading = false,
+ }: {
+ paths: string[]
+ searchString?: string
+ showLoading?: boolean
+ }) => {
+ if (state.selectedBucket.id === undefined) return
+
+ const pathsWithEmptyPrefix = [''].concat(paths)
+
+ if (showLoading) {
+ state.columns = [state.selectedBucket.name].concat(paths).map((path) => {
+ return { id: path, name: path, status: STORAGE_ROW_STATUS.LOADING, items: [] }
+ })
+ }
+
+ const foldersItems = await Promise.all(
+ pathsWithEmptyPrefix.map(async (path, idx) => {
+ const prefix = paths.slice(0, idx).join('/')
+ const options = {
+ limit: LIMIT,
+ offset: OFFSET,
+ search: searchString,
+ sortBy: { column: state.sortBy, order: state.sortByOrder },
+ }
+
+ try {
+ const data = await listBucketObjects({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ path: prefix,
+ options,
+ })
+ return data
+ } catch (error: any) {
+ toast.error(`Failed to fetch folders: ${error.message}`)
+ return []
+ }
+ })
+ )
+
+ const formattedFolders = foldersItems.map((folderItems, idx) => {
+ const formattedItems = formatFolderItems(folderItems)
+ return {
+ id: null,
+ status: STORAGE_ROW_STATUS.READY,
+ name: idx === 0 ? state.selectedBucket.name : pathsWithEmptyPrefix[idx],
+ items: formattedItems,
+ hasMoreItems: formattedItems.length === LIMIT,
+ isLoadingMoreItems: false,
+ }
+ })
+
+ // Package into columns and update this.columns
+ state.columns = formattedFolders
+
+ // Update openedFolders as well
+ const updatedOpenedFolders: StorageItem[] = paths.map((path, idx) => {
+ const folderInfo = find(formattedFolders[idx].items, { name: path })
+ // Folder doesnt exist, FE just scaffolds a "fake" folder
+ if (!folderInfo) {
+ return {
+ id: null,
+ name: path,
+ type: STORAGE_ROW_TYPES.FOLDER,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ isCorrupted: false,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ }
+ }
+ return folderInfo
+ })
+ state.openedFolders = updatedOpenedFolders
+ },
+
+ /**
+ * Check parent folder if its empty, if yes, reinstate .emptyFolderPlaceholder. Used when deleting folder or deleting files
+ */
+ validateParentFolderEmpty: async (parentFolderPrefix: string) => {
+ try {
+ const data = await listBucketObjects({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ path: parentFolderPrefix,
+ options: {
+ limit: LIMIT,
+ offset: OFFSET,
+ sortBy: { column: state.sortBy, order: state.sortByOrder },
+ },
+ })
+
+ if (data.length === 0) {
+ const prefixToPlaceholder = `${parentFolderPrefix}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`
+ await state.supabaseClient?.storage
+ .from(state.selectedBucket.name)
+ .upload(prefixToPlaceholder, new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME))
+ }
+ } catch (error) {}
+ },
+
+ deleteFolder: async (folder: StorageItemWithColumn) => {
+ try {
+ const isDeleteFolder = true
+ const files = await state.getAllItemsAlongFolder(folder)
+ await state.deleteFiles({ files: files as any[], isDeleteFolder })
+
+ state.popColumnAtIndex(folder.columnIndex)
+ state.popOpenedFoldersAtIndex(folder.columnIndex - 1)
+
+ if (folder.columnIndex > 0) {
+ const parentFolderPrefix = state.openedFolders
+ .slice(0, folder.columnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+ if (parentFolderPrefix.length > 0)
+ await state.validateParentFolderEmpty(parentFolderPrefix)
+ }
+
+ await state.refetchAllOpenedFolders()
+ state.setSelectedItemsToDelete([])
+
+ toast.success(`Successfully deleted ${folder.name}`)
+ } catch (error: any) {
+ toast.error(`Failed to delete folder: ${error.message}`)
+ }
+ },
+
+ renameFolder: async (folder: StorageItemWithColumn, newName: string, columnIndex: number) => {
+ const originalName = folder.name
+ if (originalName === newName) {
+ return state.updateRowStatus({
+ name: originalName,
+ status: STORAGE_ROW_STATUS.READY,
+ columnIndex,
+ })
+ }
+
+ const toastId = toast(
+ <SonnerProgress progress={0} message={`Renaming folder to ${newName}`} />,
+ { closeButton: false, position: 'top-right' }
+ )
+
+ try {
+ /**
+ * Catch any folder names that contain slash or backslash
+ *
+ * this is because slashes are used to denote
+ * children/parent relationships in bucket
+ *
+ * todo: move this to a util file, as createFolder() uses same logic
+ */
+ if (newName.includes('/') || newName.includes('\\')) {
+ return toast.error(`Folder name cannot contain forward or back slashes.`)
+ }
+
+ state.updateRowStatus({
+ name: originalName,
+ status: STORAGE_ROW_STATUS.LOADING,
+ columnIndex,
+ updatedName: newName,
+ })
+ const files = await state.getAllItemsAlongFolder(folder)
+
+ let progress = 0
+ let hasErrors = false
+
+ // Make this batched promises into a reusable function for storage, i think this will be super helpful
+ const promises = files.map((file) => {
+ const fromPath = `${file.prefix}/${file.name}`
+ const pathSegments = fromPath.split('/')
+ const toPath = pathSegments
+ .slice(0, columnIndex)
+ .concat(newName)
+ .concat(pathSegments.slice(columnIndex + 1))
+ .join('/')
+ return () => {
+ return new Promise<void>(async (resolve) => {
+ progress = progress + 1 / files.length
+ try {
+ await moveStorageObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ from: fromPath,
+ to: toPath,
+ })
+ } catch (error) {
+ hasErrors = true
+ toast.error(`Failed to move ${fromPath} to the new folder`)
+ }
+ resolve()
+ })
+ }
+ })
+
+ const batchedPromises = chunk(promises, BATCH_SIZE)
+ // [Joshen] I realised this can be simplified with just a vanilla for loop, no need for reduce
+ // Just take note, but if it's working fine, then it's okay
+
+ await batchedPromises.reduce(async (previousPromise, nextBatch) => {
+ await previousPromise
+ await Promise.all(nextBatch.map((batch) => batch()))
+ toast(
+ <SonnerProgress progress={progress * 100} message={`Renaming folder to ${newName}`} />,
+ { id: toastId, closeButton: false, position: 'top-right' }
+ )
+ }, Promise.resolve())
+
+ if (!hasErrors) {
+ toast.success(`Successfully renamed folder to ${newName}`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ } else {
+ toast.error(`Renamed folder to ${newName} with some errors`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+
+ if (state.openedFolders[columnIndex].name === folder.name) {
+ state.setSelectedFilePreview(undefined)
+ state.popOpenedFoldersAtIndex(columnIndex - 1)
+ }
+ await state.refetchAllOpenedFolders()
+
+ // TODO: Should we invalidate the file preview cache when renaming folders?
+ } catch (e: any) {
+ toast.error(`Failed to rename folder to ${newName}: ${e.message}`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+ },
+
+ updateFolderAfterEdit: ({
+ folderName,
+ columnIndex,
+ status = STORAGE_ROW_STATUS.READY,
+ }: {
+ folderName: string
+ columnIndex?: number
+ status?: STORAGE_ROW_STATUS
+ }) => {
+ const columnIndex_ = columnIndex !== undefined ? columnIndex : state.getLatestColumnIndex()
+ const updatedColumns = state.columns.map((column, idx) => {
+ if (idx === columnIndex_) {
+ const updatedItems = column.items.map((item) => {
+ if (item.status === STORAGE_ROW_STATUS.EDITING) {
+ const currentTime = new Date().toISOString()
+ return {
+ ...item,
+ status,
+ name: folderName,
+ createdAt: currentTime,
+ lastAccessedAt: currentTime,
+ updatedAt: currentTime,
+ metadata: null,
+ id: null,
+ }
+ }
+ return item
+ })
+ return { ...column, items: updatedItems }
+ }
+ return column
+ })
+ state.columns = updatedColumns
+ },
+
+ downloadFolder: async (folder: StorageItemWithColumn) => {
+ let progress = 0
+ const toastId = toast.loading('Retrieving files from folder...')
+
+ try {
+ const files = await state.getAllItemsAlongFolder(folder)
+
+ toast(
+ <SonnerProgress
+ progress={0}
+ message={`Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`}
+ />,
+ { id: toastId, closeButton: false, position: 'top-right' }
+ )
+
+ const promises = files.map((file) => {
+ const fileMimeType = (file.metadata?.mimetype as string) ?? null
+ return () => {
+ return new Promise<
+ | {
+ name: string
+ prefix: string
+ blob: Blob
+ }
+ | boolean
+ >(async (resolve) => {
+ try {
+ const data = await downloadBucketObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ path: `${file.prefix}/${file.name}`,
+ })
+ progress = progress + 1 / files.length
+
+ const blob = await data.blob()
+ resolve({
+ name: file.name,
+ prefix: file.prefix,
+ blob: new Blob([blob], { type: fileMimeType }),
+ })
+ } catch (error) {
+ console.error('Failed to download file', `${file.prefix}/${file.name}`)
+ resolve(false)
+ }
+ })
+ }
+ })
+
+ const batchedPromises = chunk(promises, 10)
+ const downloadedFiles = await batchedPromises.reduce(
+ async (previousPromise, nextBatch) => {
+ const previousResults = await previousPromise
+ const batchResults = await Promise.allSettled(nextBatch.map((batch) => batch()))
+ toast(
+ <SonnerProgress
+ progress={progress * 100}
+ message={`Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`}
+ />,
+ { id: toastId, closeButton: false, position: 'top-right' }
+ )
+ return previousResults.concat(batchResults.map((x: any) => x.value).filter(Boolean))
+ },
+ Promise.resolve<
+ {
+ name: string
+ prefix: string
+ blob: Blob
+ }[]
+ >([])
+ )
+
+ const zipFileWriter = new BlobWriter('application/zip')
+ const zipWriter = new ZipWriter(zipFileWriter, { bufferedWrite: true })
+
+ if (downloadedFiles.length === 0) {
+ toast.error(`Failed to download files from "${folder.name}"`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+
+ downloadedFiles.forEach((file) => {
+ if (file.blob) zipWriter.add(`${file.prefix}/${file.name}`, new BlobReader(file.blob))
+ })
+
+ const blobURL = URL.createObjectURL(await zipWriter.close())
+ const link = document.createElement('a')
+ link.href = blobURL
+ link.setAttribute('download', `${folder.name}.zip`)
+ document.body.appendChild(link)
+ link.click()
+ link.parentNode?.removeChild(link)
+
+ toast.success(
+ downloadedFiles.length === files.length
+ ? `Successfully downloaded folder "${folder.name}"`
+ : `Downloaded folder "${folder.name}". However, ${
+ files.length - downloadedFiles.length
+ } files did not download successfully.`,
+ { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
+ )
+ } catch (error: any) {
+ toast.error(`Failed to download folder: ${error.message}`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+ },
+
+ /**
+ * Recursively returns a list of items along every directory within the specified base folder
+ * Each item has an extra property 'prefix' which has the prefix that leads to the item
+ * Used specifically for any operation that deals with every file along the folder
+ * e.g Delete folder, rename folder
+ */
+ getAllItemsAlongFolder: async (folder: {
+ name: string
+ columnIndex: number
+ prefix?: string
+ }): Promise<(StorageObject & { prefix: string })[]> => {
+ const items: (StorageObject & { prefix: string })[] = []
+
+ let hasError = false
+ let formattedPathToFolder = ''
+ const { name, columnIndex, prefix } = folder
+
+ if (prefix === undefined) {
+ const pathToFolder = state.openedFolders
+ .slice(0, columnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+ formattedPathToFolder = pathToFolder.length > 0 ? `${pathToFolder}/${name}` : name
+ } else {
+ formattedPathToFolder = `${prefix}/${name}`
+ }
+
+ // [Joshen] limit is set to 10k to optimize reduction of requests, we've done some experiments
+ // that prove that the time to fetch all files in a folder reduces as the batch size increases
+ // 10k however, is the hard limit at the API level.
+ const options = {
+ limit: 10000,
+ offset: OFFSET,
+ sortBy: { column: state.sortBy, order: state.sortByOrder },
+ }
+ let folderContents: StorageObject[] = []
+
+ for (;;) {
+ try {
+ const data = await listBucketObjects({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ path: formattedPathToFolder,
+ options,
+ })
+ folderContents = folderContents.concat(data)
+ options.offset += options.limit
+ if ((data || []).length < options.limit) {
+ break
+ }
+ } catch (e) {
+ hasError = true
+ break
+ }
+ }
+
+ if (hasError) {
+ throw new Error('Failed to retrieve all files within folder')
+ }
+
+ const subfolders = folderContents?.filter((item) => item.id === null) ?? []
+ const folderItems = folderContents?.filter((item) => item.id !== null) ?? []
+
+ folderItems.forEach((item) => items.push({ ...item, prefix: formattedPathToFolder }))
+
+ const subFolderContents = await Promise.all(
+ subfolders.map((folder) =>
+ state.getAllItemsAlongFolder({ ...folder, columnIndex: 0, prefix: formattedPathToFolder })
+ )
+ )
+ subFolderContents.map((subfolderContent) => {
+ subfolderContent.map((item) => items.push(item))
+ })
+
+ return items
+ },
+
+ // ======== Files CRUD ========
+
+ uploadFiles: async ({
+ files,
+ columnIndex,
+ isDrop = false,
+ }: {
+ files: FileList | DataTransferItemList
+ columnIndex: number
+ isDrop?: boolean
+ }) => {
+ const queryClient = getQueryClient()
+ const storageConfiguration = queryClient
+ .getQueryCache()
+ .find(configKeys.storage(state.projectRef))?.state.data as
+ | ProjectStorageConfigResponse
+ | undefined
+ const fileSizeLimit = storageConfiguration?.fileSizeLimit
+
+ const t1 = new Date()
+
+ const autofix = true
+ // We filter out any folders which are just '#' until we can properly encode such characters in the URL
+ const filesToUpload: (File & { path?: string })[] = isDrop
+ ? (await getFilesDataTransferItems(files as DataTransferItemList)).filter(
+ (file) => !file.path.includes('#/')
+ )
+ : Array.from(files as FileList)
+ const derivedColumnIndex = columnIndex === -1 ? state.getLatestColumnIndex() : columnIndex
+
+ const filesWithinUploadLimit =
+ fileSizeLimit !== undefined
+ ? filesToUpload.filter((file) => file.size <= fileSizeLimit)
+ : filesToUpload
+
+ if (filesWithinUploadLimit.length < filesToUpload.length) {
+ const numberOfFilesRejected = filesToUpload.length - filesWithinUploadLimit.length
+ const { value, unit } = convertFromBytes(fileSizeLimit as number)
+
+ toast.error(
+ <div className="flex flex-col gap-y-1">
+ <p className="text-foreground">
+ Failed to upload {numberOfFilesRejected} file{numberOfFilesRejected > 1 ? 's' : ''} as{' '}
+ {numberOfFilesRejected > 1 ? 'their' : 'its'} size
+ {numberOfFilesRejected > 1 ? 's are' : ' is'} beyond the global upload limit of{' '}
+ {value}
+ {unit}.
+ </p>
+ <p className="text-foreground-light">
+ You can change the global file size upload limit in{' '}
+ <InlineLink href={`/project/${state.projectRef}/settings/storage`}>
+ Storage settings
+ </InlineLink>
+ .
+ </p>
+ </div>,
+ { duration: 8000 }
+ )
+
+ if (numberOfFilesRejected === filesToUpload.length) return
+ }
+
+ const filesWithNonZeroSize = filesWithinUploadLimit.filter((file) => file.size > 0)
+ if (filesWithNonZeroSize.length < filesWithinUploadLimit.length) {
+ const numberOfFilesRejected = filesWithinUploadLimit.length - filesWithNonZeroSize.length
+ toast.error(
+ <div className="flex flex-col gap-y-1">
+ <p className="text-foreground">
+ Failed to upload {numberOfFilesRejected} file{numberOfFilesRejected > 1 ? 's' : ''} as{' '}
+ {numberOfFilesRejected > 1 ? 'their' : 'its'} size
+ {numberOfFilesRejected > 1 ? 's are' : ' is'} 0.
+ </p>
+ </div>
+ )
+
+ if (numberOfFilesRejected === filesWithinUploadLimit.length) return
+ }
+
+ // If we're uploading a folder which name already exists in the same folder that we're uploading to
+ // We sanitize the folder name and let all file uploads through. (This is only via drag drop)
+ const topLevelFolders: string[] = (state.columns?.[derivedColumnIndex]?.items ?? [])
+ .filter((item) => !item.id)
+ .map((item) => item.name)
+ const formattedFilesToUpload = filesWithinUploadLimit
+ .filter((file) => file.name !== '.DS_Store')
+ .map((file) => {
+ // If the files are from clicking "Upload button", just take them as they are since users cannot
+ // upload folders from clicking that button, only via drag drop
+ if (!file.path) return file
+
+ const path = file.path.split('/')
+ const topLevelFolder = path.length > 1 ? path[0] : null
+ if (topLevelFolders.includes(topLevelFolder as string)) {
+ const newTopLevelFolder = state.sanitizeNameForDuplicateInColumn({
+ name: topLevelFolder as string,
+ autofix,
+ columnIndex,
+ })
+ path[0] = newTopLevelFolder as string
+ file.path = path.join('/')
+ }
+ return file
+ })
+
+ state.uploadProgresses = new Array(formattedFilesToUpload.length).fill({
+ percentage: 0,
+ elapsed: 0,
+ uploadSpeed: 0,
+ remainingBytes: 0,
+ remainingTime: 0,
+ })
+ const uploadedTopLevelFolders: string[] = []
+ const numberOfFilesToUpload = formattedFilesToUpload.length
+ let numberOfFilesUploadedSuccess = 0
+ let numberOfFilesUploadedFail = 0
+
+ const pathToFile = state.openedFolders
+ .slice(0, derivedColumnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+
+ const toastId = state.onUploadProgress()
+
+ // Upload files in batches
+ const promises = formattedFilesToUpload.map((file, index) => {
+ const extension = file.name.split('.').pop()
+ const metadata = {
+ mimetype: (file.type || lookupMime(extension)) ?? '',
+ size: file.size,
+ } as StorageItemMetadata
+ const fileOptions = { cacheControl: '3600', contentType: metadata.mimetype }
+
+ const isWithinFolder = (file?.path ?? '').split('/').length > 1
+ const fileName = !isWithinFolder
+ ? state.sanitizeNameForDuplicateInColumn({ name: file.name, autofix })
+ : file.name
+ const unsanitizedFormattedFileName =
+ has(file, ['path']) && isWithinFolder ? file.path : fileName
+ /**
+ * Storage maintains a list of allowed characters, which excludes
+ * characters such as the narrow no-break space used in Mac screenshots.
+ * [Joshen] Am limiting to just replacing nbsp with a blank space instead of
+ * all non-word characters per before
+ * */
+ const formattedFileName = (unsanitizedFormattedFileName ?? 'unknown').replaceAll(
+ /\u{202F}/gu,
+ ' '
+ )
+ const formattedPathToFile =
+ pathToFile.length > 0
+ ? `${pathToFile}/${formattedFileName}`
+ : (formattedFileName as string)
+
+ if (isWithinFolder) {
+ const topLevelFolder = file.path?.split('/')[0] || ''
+ if (!uploadedTopLevelFolders.includes(topLevelFolder)) {
+ state.addTempRow({
+ type: STORAGE_ROW_TYPES.FOLDER,
+ name: topLevelFolder,
+ status: STORAGE_ROW_STATUS.LOADING,
+ columnIndex: derivedColumnIndex,
+ metadata,
+ })
+ uploadedTopLevelFolders.push(topLevelFolder)
+ }
+ } else {
+ state.addTempRow({
+ type: STORAGE_ROW_TYPES.FILE,
+ name: fileName!,
+ status: STORAGE_ROW_STATUS.LOADING,
+ columnIndex: derivedColumnIndex,
+ metadata,
+ })
+ }
+
+ let startingBytes = 0
+ const bucketName = state.selectedBucket.name
+
+ return () => {
+ return new Promise<void>(async (resolve, reject) => {
+ const fileSizeInMB = file.size / (1024 * 1024)
+ const startTime = Date.now()
+
+ let chunkSize: number
+
+ if (fileSizeInMB < 30) {
+ chunkSize = 6 * 1024 * 1024
+ } else if (fileSizeInMB < 100) {
+ chunkSize = Math.floor(file.size / 8)
+ } else if (fileSizeInMB < 500) {
+ chunkSize = Math.floor(file.size / 10)
+ } else if (fileSizeInMB < 1024) {
+ chunkSize = Math.floor(file.size / 20)
+ } else if (fileSizeInMB < 10 * 1024) {
+ chunkSize = Math.floor(file.size / 30)
+ } else {
+ chunkSize = Math.floor(file.size / 50)
+ }
+
+ // Max chunk size is 500MB
+ chunkSize = Math.min(chunkSize, 500 * 1024 * 1024)
+ const uploadDataDuringCreation = file.size <= chunkSize
+
+ const upload = new tus.Upload(file, {
+ endpoint: state.resumableUploadUrl,
+ retryDelays: [0, 200, 500, 1500, 3000, 5000],
+ headers: {
+ authorization: `Bearer ${state.serviceKey}`,
+ 'x-source': 'supabase-dashboard',
+ },
+ uploadDataDuringCreation: uploadDataDuringCreation,
+ removeFingerprintOnSuccess: true,
+ metadata: {
+ bucketName,
+ objectName: formattedPathToFile,
+ ...fileOptions,
+ },
+ chunkSize,
+ onShouldRetry(error) {
+ const status = error.originalResponse ? error.originalResponse.getStatus() : 0
+ const doNotRetryStatuses = [400, 403, 404, 409, 413, 415, 429]
+
+ return !doNotRetryStatuses.includes(status)
+ },
+ onError: (error) => {
+ numberOfFilesUploadedFail += 1
+ if (error instanceof tus.DetailedError) {
+ const status = error.originalResponse?.getStatus()
+ if (status === 415) {
+ // Unsupported mime type
+ toast.error(
+ capitalize(
+ error?.originalResponse?.getBody() ||
+ `Failed to upload ${file.name}: ${metadata.mimetype} is not allowed`
+ ),
+ {
+ description: `Allowed MIME types: ${state.selectedBucket.allowed_mime_types?.join(', ')}`,
+ }
+ )
+ } else if (status === 413) {
+ // Payload too large
+ toast.error(
+ `Failed to upload ${file.name}: File size exceeds the bucket upload limit.`
+ )
+ }
+ } else {
+ toast.error(`Failed to upload ${file.name}: ${error.message}`)
+ }
+ reject(error)
+ },
+ onProgress: (bytesSent, bytesTotal) => {
+ if (startingBytes === 0 && bytesSent > chunkSize) {
+ startingBytes = bytesSent
+ }
+
+ const percentage = bytesTotal === 0 ? 0 : bytesSent / bytesTotal
+ const realBytesSent = bytesSent - startingBytes
+ const elapsed = (Date.now() - startTime) / 1000 // in seconds
+ const uploadSpeed = realBytesSent / elapsed // in bytes per second
+ const remainingBytes = bytesTotal - realBytesSent
+ const remainingTime = remainingBytes / uploadSpeed // in seconds
+
+ state.uploadProgresses[index] = {
+ percentage,
+ elapsed,
+ uploadSpeed,
+ remainingBytes,
+ remainingTime,
+ }
+ state.onUploadProgress(toastId)
+ },
+ onSuccess() {
+ numberOfFilesUploadedSuccess += 1
+ resolve()
+ },
+ })
+
+ if (!Array.isArray(state.abortUploadCallbacks[toastId])) {
+ state.abortUploadCallbacks[toastId] = []
+ }
+ state.abortUploadCallbacks[toastId].push(() => {
+ try {
+ upload.abort(true)
+ } catch (error) {
+ // Ignore error
+ }
+ reject(new Error('Upload aborted by user'))
+ })
+
+ // Check if there are any previous uploads to continue.
+ return upload.findPreviousUploads().then((previousUploads) => {
+ // Found previous uploads so we select the first one.
+ if (previousUploads.length) {
+ upload.resumeFromPreviousUpload(previousUploads[0])
+ }
+
+ upload.start()
+ })
+ })
+ }
+ })
+
+ // For file uploads specifically, we have to lower the batch size for now as the client side
+ // is just unable to handle such volumes of transfer
+ // [Joshen] I realised this can be simplified with just a vanilla for loop, no need for reduce
+ // Just take note, but if it's working fine, then it's okay
+ const batchedPromises = chunk(promises, 10)
+ try {
+ await batchedPromises.reduce(async (previousPromise, nextBatch) => {
+ await previousPromise
+ await Promise.allSettled(nextBatch.map((batch) => batch()))
+ state.onUploadProgress(toastId)
+ }, Promise.resolve())
+
+ if (numberOfFilesUploadedSuccess > 0) {
+ await deleteBucketObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ paths: [`${pathToFile}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`],
+ })
+ }
+
+ await state.refetchAllOpenedFolders()
+
+ if (
+ numberOfFilesToUpload === 0 ||
+ (numberOfFilesUploadedSuccess === 0 && numberOfFilesUploadedFail === 0)
+ ) {
+ toast.dismiss(toastId)
+ } else if (numberOfFilesUploadedFail === numberOfFilesToUpload) {
+ toast.error(
+ `Failed to upload ${numberOfFilesToUpload} file${numberOfFilesToUpload > 1 ? 's' : ''}!`,
+ { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
+ )
+ } else if (numberOfFilesUploadedSuccess === numberOfFilesToUpload) {
+ toast.success(
+ `Successfully uploaded ${numberOfFilesToUpload} file${
+ numberOfFilesToUpload > 1 ? 's' : ''
+ }!`,
+ { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
+ )
+ } else {
+ toast.success(
+ `Successfully uploaded ${numberOfFilesUploadedSuccess} out of ${numberOfFilesToUpload} file${
+ numberOfFilesToUpload > 1 ? 's' : ''
+ }!`,
+ { id: toastId, closeButton: true, duration: SONNER_DEFAULT_DURATION }
+ )
+ }
+ } catch (e) {
+ toast.error('Failed to upload files', {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+
+ const t2 = new Date()
+ console.log(
+ `Total time taken for ${formattedFilesToUpload.length} files: ${((t2 as any) - (t1 as any)) / 1000} seconds`
+ )
+ },
+
+ moveFiles: async (newPathToFile: string) => {
+ const newPaths = compact(newPathToFile.split('/'))
+ const formattedNewPathToFile = newPaths.join('/')
+ let numberOfFilesMovedFail = 0
+ state.clearSelectedItems()
+
+ const toastId = toast(
+ `Moving ${state.selectedItemsToMove.length} file${state.selectedItemsToMove.length > 1 ? 's' : ''}...`,
+ {
+ description: STORAGE_PROGRESS_INFO_TEXT,
+ duration: Infinity,
+ }
+ )
+
+ await Promise.all(
+ state.selectedItemsToMove.map(async (item) => {
+ const pathToFile = state.openedFolders
+ .slice(0, item.columnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+
+ const fromPath = pathToFile.length > 0 ? `${pathToFile}/${item.name}` : item.name
+ const toPath =
+ newPathToFile.length > 0 ? `${formattedNewPathToFile}/${item.name}` : item.name
+
+ try {
+ await moveStorageObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ from: fromPath,
+ to: toPath,
+ })
+ } catch (error: any) {
+ numberOfFilesMovedFail += 1
+ toast.error(error.message)
+ }
+ })
+ )
+
+ if (numberOfFilesMovedFail === state.selectedItemsToMove.length) {
+ toast.error('Failed to move files')
+ } else {
+ toast(
+ `Successfully moved ${
+ state.selectedItemsToMove.length - numberOfFilesMovedFail
+ } files to ${formattedNewPathToFile.length > 0 ? formattedNewPathToFile : 'the root of your bucket'}`
+ )
+ }
+
+ toast.dismiss(toastId)
+
+ // TODO: invalidate the file preview cache when moving files
+ await state.refetchAllOpenedFolders()
+ state.setSelectedItemsToMove([])
+ },
+
+ deleteFiles: async ({
+ files,
+ isDeleteFolder = false,
+ }: {
+ files: (StorageItemWithColumn & { prefix?: string })[]
+ isDeleteFolder?: boolean
+ }) => {
+ state.setSelectedFilePreview(undefined)
+ let progress = 0
+
+ // If every file has the 'prefix' property, then just construct the prefix
+ // directly (from delete folder). Otherwise go by the opened folders.
+ const prefixes = !files.some((f) => f.prefix)
+ ? files.map((file) => {
+ const { name, columnIndex } = file
+ const pathToFile = state.openedFolders
+ .slice(0, columnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+ state.updateRowStatus({ name, status: STORAGE_ROW_STATUS.LOADING, columnIndex })
+ return pathToFile.length > 0 ? `${pathToFile}/${name}` : name
+ })
+ : files.map((file) => `${file.prefix}/${file.name}`)
+
+ state.clearSelectedItems()
+
+ const toastId = toast(
+ <SonnerProgress progress={0} message={`Deleting ${prefixes.length} file(s)...`} />,
+ { closeButton: false, position: 'top-right' }
+ )
+
+ // batch BATCH_SIZE prefixes per request
+ const batches = chunk(prefixes, BATCH_SIZE).map((batch) => () => {
+ progress = progress + batch.length / prefixes.length
+ return deleteBucketObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ paths: batch as string[],
+ })
+ })
+
+ // make BATCH_SIZE requests at the same time
+ await chunk(batches, BATCH_SIZE).reduce(async (previousPromise, nextBatch) => {
+ await previousPromise
+ await Promise.all(nextBatch.map((batch) => batch()))
+ toast(
+ <SonnerProgress
+ progress={progress * 100}
+ message={`Deleting ${prefixes.length} file(s)...`}
+ />,
+ {
+ id: toastId,
+ closeButton: false,
+ position: 'top-right',
+ }
+ )
+ }, Promise.resolve())
+
+ if (!isDeleteFolder) {
+ // If parent folders are empty, reinstate .emptyFolderPlaceholder to persist them
+ const parentFolderPrefixes = uniq(
+ prefixes.map((prefix) => {
+ const segments = prefix.split('/')
+ return segments.slice(0, segments.length - 1).join('/')
+ })
+ )
+ await Promise.all(
+ parentFolderPrefixes.map((prefix) => state.validateParentFolderEmpty(prefix))
+ )
+
+ toast.success(`Successfully deleted ${prefixes.length} file(s)`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ description: undefined,
+ })
+ await state.refetchAllOpenedFolders()
+ state.setSelectedItemsToDelete([])
+ } else {
+ toast.dismiss(toastId)
+ }
+ },
+
+ downloadSelectedFiles: async (files: StorageItemWithColumn[]) => {
+ const lowestColumnIndex = Math.min(...files.map((file) => file.columnIndex))
+
+ const formattedFilesWithPrefix: any[] = files.map((file) => {
+ const { name, columnIndex } = file
+ const pathToFile = state.openedFolders
+ .slice(lowestColumnIndex, columnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+ const formattedPathToFile = pathToFile.length > 0 ? `${pathToFile}/${name}` : name
+ return { ...file, formattedPathToFile }
+ })
+
+ let progress = 0
+ const returnBlob = true
+ const toastId = toast.loading(
+ `Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`
+ )
+
+ const promises = formattedFilesWithPrefix.map((file) => {
+ return () => {
+ return new Promise<{ name: string; blob: Blob } | boolean>(async (resolve) => {
+ const data = await downloadFile({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ file,
+ returnBlob,
+ })
+ progress = progress + 1 / formattedFilesWithPrefix.length
+ if (isObject(data)) {
+ resolve({ ...data, name: file.formattedPathToFile })
+ }
+ resolve(false)
+ })
+ }
+ })
+
+ const batchedPromises = chunk(promises, 10)
+ const downloadedFiles = await batchedPromises.reduce(async (previousPromise, nextBatch) => {
+ const previousResults = await previousPromise
+ const batchResults = await Promise.allSettled(nextBatch.map((batch) => batch()))
+ toast(
+ <SonnerProgress
+ progress={progress * 100}
+ message={`Downloading ${files.length} file${files.length > 1 ? 's' : ''}...`}
+ />,
+ { id: toastId, closeButton: false, position: 'top-right' }
+ )
+ return previousResults.concat(batchResults.map((x: any) => x.value).filter(Boolean))
+ }, Promise.resolve<{ name: string; blob: Blob }[]>([]))
+
+ const zipFileWriter = new BlobWriter('application/zip')
+ const zipWriter = new ZipWriter(zipFileWriter, { bufferedWrite: true })
+ downloadedFiles.forEach((file) => {
+ zipWriter.add(file.name, new BlobReader(file.blob))
+ })
+
+ const blobURL = URL.createObjectURL(await zipWriter.close())
+ const link = document.createElement('a')
+ link.href = blobURL
+ link.setAttribute('download', `supabase-files.zip`)
+ document.body.appendChild(link)
+ link.click()
+ link.parentNode?.removeChild(link)
+
+ toast.success(`Successfully downloaded ${downloadedFiles.length} files`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ },
+
+ renameFile: async (file: StorageItem, newName: string, columnIndex: number) => {
+ const originalName = file.name
+ if (originalName === newName || newName.length === 0) {
+ state.updateRowStatus({ name: originalName, status: STORAGE_ROW_STATUS.READY, columnIndex })
+ } else {
+ state.updateRowStatus({
+ name: originalName,
+ status: STORAGE_ROW_STATUS.LOADING,
+ columnIndex,
+ updatedName: newName,
+ })
+ const pathToFile = state.getPathAlongFoldersToIndex(columnIndex)
+
+ const fromPath = pathToFile.length > 0 ? `${pathToFile}/${originalName}` : originalName
+ const toPath = pathToFile.length > 0 ? `${pathToFile}/${newName}` : newName
+
+ try {
+ await moveStorageObject({
+ projectRef: state.projectRef,
+ bucketId: state.selectedBucket.id,
+ from: fromPath,
+ to: toPath,
+ })
+
+ toast.success(`Successfully renamed "${originalName}" to "${newName}"`)
+
+ // TODO: Should we invalidate the file preview cache when renaming files?
+
+ if (state.selectedFilePreview?.name === originalName) {
+ const { previewUrl, ...fileData } = file as any
+ state.setSelectedFilePreview({ ...fileData, name: newName })
+ }
+
+ await state.refetchAllOpenedFolders()
+ } catch (error: any) {
+ toast.error(`Failed to rename file: ${error.message}`)
+ state.updateRowStatus({
+ name: originalName,
+ status: STORAGE_ROW_STATUS.READY,
+ columnIndex,
+ })
+ }
+ }
+ },
+
+ // ======== UI Helper functions ========
+
+ selectRangeItems: (columnIndex: number, toItemIndex: number) => {
+ const columnItems = state.columns[columnIndex].items
+ const toItem = columnItems[toItemIndex]
+ const selectedItemIds = state.selectedItems.map((item) => item.id)
+ const lastSelectedItemId = selectedItemIds[selectedItemIds.length - 1]
+ const lastSelectedItemIndex = findIndex(columnItems, { id: lastSelectedItemId })
+
+ // Get the start and end index of the range to select
+ const start = Math.min(toItemIndex, lastSelectedItemIndex)
+ const end = Math.max(toItemIndex, lastSelectedItemIndex)
+
+ // Get the range to select and reverse the order if necessary
+ const rangeToSelect = columnItems
+ .slice(start, end + 1)
+ // we need `columnIndex` in all item of `selectedItems`
+ .map((item) => ({ ...item, columnIndex }))
+ if (toItemIndex < lastSelectedItemIndex) {
+ rangeToSelect.reverse()
+ }
+
+ if (selectedItemIds.includes(toItem.id)) {
+ const rangeToDeselectIds = rangeToSelect.map((item) => item.id)
+ // Deselect all items within the selection range
+ state.setSelectedItems(
+ state.selectedItems.filter(
+ (item) => item.id === toItem.id || !rangeToDeselectIds.includes(item.id)
+ )
+ )
+ } else {
+ // Select items within the range
+ state.setSelectedItems(uniqBy(state.selectedItems.concat(rangeToSelect), 'id'))
+ }
+ },
+
+ sanitizeNameForDuplicateInColumn: ({
+ name,
+ columnIndex,
+ autofix = false,
+ }: {
+ name: string
+ columnIndex?: number
+ autofix?: boolean
+ }) => {
+ const columnIndex_ = columnIndex !== undefined ? columnIndex : state.getLatestColumnIndex()
+ const currentColumn = state.columns[columnIndex_]
+ const currentColumnItems = currentColumn.items.filter(
+ (item) => item.status !== STORAGE_ROW_STATUS.EDITING
+ )
+ const hasSameNameInColumn = currentColumnItems.filter((item) => item.name === name).length > 0
+
+ if (hasSameNameInColumn) {
+ if (autofix) {
+ const [fileName, fileExt] = name.split('.')
+ const dupeNameRegex = new RegExp(
+ `${fileName} \\([-0-9]+\\)${fileExt ? '.' + fileExt : ''}$`
+ )
+ const itemsWithSameNameInColumn = currentColumnItems.filter((item) =>
+ item.name.match(dupeNameRegex)
+ )
+
+ const updatedFileName = fileName + ` (${itemsWithSameNameInColumn.length + 1})`
+ return fileExt ? `${updatedFileName}.${fileExt}` : updatedFileName
+ } else {
+ toast.error(
+ `The name ${name} already exists in the current directory. Please use a different name.`
+ )
+ return null
+ }
+ }
+
+ return name
+ },
+
+ addTempRow: ({
+ type,
+ name,
+ status,
+ columnIndex,
+ metadata,
+ isPrepend = false,
+ }: {
+ type: STORAGE_ROW_TYPES
+ name: string
+ status: STORAGE_ROW_STATUS
+ columnIndex: number
+ metadata: StorageItemMetadata | null
+ isPrepend?: boolean
+ }) => {
+ const updatedColumns = state.columns.map((column, idx) => {
+ if (idx === columnIndex) {
+ const tempRow = { type, name, status, metadata } as StorageItem
+ const updatedItems = isPrepend
+ ? [tempRow].concat(column.items)
+ : column.items.concat([tempRow])
+ return { ...column, items: updatedItems }
+ }
+ return column
+ })
+ state.columns = updatedColumns
+ },
+
+ removeTempRows: (columnIndex: number) => {
+ const updatedColumns = state.columns.map((column, idx) => {
+ if (idx === columnIndex) {
+ const updatedItems = column.items.filter((item) => has(item, 'id'))
+ return { ...column, items: updatedItems }
+ }
+ return column
+ })
+ state.columns = updatedColumns
+ },
+
+ onUploadProgress: (toastId?: string | number) => {
+ const totalFiles = state.uploadProgresses.length
+ const progress =
+ (state.uploadProgresses.reduce((acc, { percentage }) => acc + percentage, 0) / totalFiles) *
+ 100
+ const remainingTime = calculateTotalRemainingTime(state.uploadProgresses)
+
+ return toast(
+ <SonnerProgress
+ progress={progress}
+ message={`Uploading ${totalFiles} file${totalFiles > 1 ? 's' : ''}...`}
+ progressPrefix={`${remainingTime && !isNaN(remainingTime) && isFinite(remainingTime) && remainingTime !== 0 ? `${formatTime(remainingTime)} remaining – ` : ''}`}
+ action={
+ toastId && (
+ <Button
+ size="tiny"
+ type="default"
+ className="ml-6"
+ onClick={() => state.abortUploads(toastId)}
+ >
+ Cancel
+ </Button>
+ )
+ }
+ />,
+ { id: toastId, closeButton: false, position: 'top-right' }
+ )
+ },
+
+ updateRowStatus: ({
+ name,
+ status,
+ columnIndex,
+ updatedName,
+ }: {
+ name: string
+ status: STORAGE_ROW_STATUS
+ columnIndex?: number
+ updatedName?: string
+ }) => {
+ const columnIndex_ = columnIndex !== undefined ? columnIndex : state.getLatestColumnIndex()
+ const updatedColumns = state.columns.map((column, idx) => {
+ if (idx === columnIndex_) {
+ const updatedColumnItems = column.items.map((item) => {
+ return item.name === name
+ ? {
+ ...item,
+ status,
+ ...(updatedName && { name: updatedName }),
+ }
+ : item
+ })
+ return { ...column, items: updatedColumnItems }
+ }
+ return column
+ })
+ state.columns = updatedColumns
+ },
})
return state
@@ -57,18 +1694,30 @@ function createStorageExplorerState({ projectRef }: { projectRef: string }) {
type StorageExplorerState = ReturnType<typeof createStorageExplorerState>
+const DEFAULT_STATE_CONFIG = {
+ projectRef: '',
+ resumableUploadUrl: '',
+ serviceKey: '',
+ supabaseClient: undefined,
+}
+
const StorageExplorerStateContext = createContext<StorageExplorerState>(
- createStorageExplorerState({ projectRef: '' })
+ createStorageExplorerState(DEFAULT_STATE_CONFIG)
)
export const StorageExplorerStateContextProvider = ({ children }: PropsWithChildren) => {
const { project } = useProjectContext()
- const [state, setState] = useState(() =>
- createStorageExplorerState({ projectRef: project?.ref ?? '' })
- )
+ const isPaused = project?.status === PROJECT_STATUS.INACTIVE
+ const [state, setState] = useState(() => createStorageExplorerState(DEFAULT_STATE_CONFIG))
const stateRef = useLatest(state)
+ const { data: settings } = useProjectSettingsV2Query({ projectRef: project?.ref })
+ const { serviceKey } = getAPIKeys(settings)
+ const protocol = settings?.app_config?.protocol ?? 'https'
+ const endpoint = settings?.app_config?.endpoint
+ const resumableUploadUrl = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}/storage/v1/upload/resumable`
+
// [Joshen] JFYI opting with the useEffect here as the storage explorer state was being loaded
// before the project details were ready, hence the store kept returning project ref as undefined
// Can be verified when we're saving the storage explorer preferences into local storage, that ref is undefined
@@ -79,10 +1728,33 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
const hasDataReady = !!project?.ref
const isDifferentProject = snap.projectRef !== project?.ref
- if (hasDataReady && isDifferentProject) {
- setState(createStorageExplorerState({ projectRef: project?.ref ?? '' }))
+ if (!isPaused && hasDataReady && isDifferentProject && serviceKey) {
+ const clientEndpoint = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}`
+ const supabaseClient = createClient(clientEndpoint, serviceKey.api_key, {
+ auth: {
+ persistSession: false,
+ autoRefreshToken: false,
+ detectSessionInUrl: false,
+ storage: {
+ getItem: (key) => {
+ return null
+ },
+ setItem: (key, value) => {},
+ removeItem: (key) => {},
+ },
+ },
+ })
+
+ setState(
+ createStorageExplorerState({
+ projectRef: project?.ref ?? '',
+ supabaseClient,
+ resumableUploadUrl,
+ serviceKey: serviceKey.api_key,
+ })
+ )
}
- }, [project?.ref, stateRef])
+ }, [project?.ref, stateRef, serviceKey, isPaused])
return (
<StorageExplorerStateContext.Provider value={state}>
@@ -93,5 +1765,5 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
export function useStorageExplorerStateSnapshot(options?: Parameters<typeof useSnapshot>[1]) {
const state = useContext(StorageExplorerStateContext)
- return useSnapshot(state, options)
+ return useSnapshot(state, options) as StorageExplorerState
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 551231267d9..fabafef1d83 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -742,12 +742,6 @@ importers:
mime-db:
specifier: ^1.53.0
version: 1.53.0
- mobx:
- specifier: ^6.10.2
- version: 6.11.0
- mobx-react-lite:
- specifier: ^4.0.5
monaco-editor:
specifier: 0.52.2
version: 0.52.2
@@ -11639,19 +11633,6 @@ packages:
resolution: {integrity: sha512-A/0v5Z59y63US00cRSLiloEIw3t5G+MiKz4BhX21FI+YBJXBOGW0ohFxTxO08dsOYlzxo87T7vGfZKYp2bcAWA==}
- resolution: {integrity: sha512-StfB2wxE8imKj1f6T8WWPf4lVMx3cYH9Iy60bbKXEs21+HQ4tvvfIBZfSmMXgQAefi8xYEwQIz4GN9s0d2h7dg==}
- peerDependencies:
- mobx: ^6.9.0
- react: ^16.8.0 || ^17 || ^18
- react-dom: '*'
- react-native: '*'
- peerDependenciesMeta:
- react-dom:
- optional: true
- react-native:
- optional: true
-
resolution: {integrity: sha512-QEP10dpHHBeQNv1pks3WnHRCem2Zp636lq54M2nKO2Sarr13pL4u6diQXf65yzXUn0mkk18SyIDCm9UOJYTi1w==}
peerDependencies:
@@ -25320,7 +25301,7 @@ snapshots:
dependencies:
- has-symbols: 1.0.3
+ has-symbols: 1.1.0
@@ -27816,14 +27797,6 @@ snapshots:
dependencies:
obliterator: 2.0.4
- dependencies:
- mobx: 6.11.0
- react: 18.3.1
- use-sync-external-store: 1.2.0([email protected])
- optionalDependencies:
- react-dom: 18.3.1([email protected])
-
dependencies:
mobx: 6.11.0
@@ -28792,7 +28765,7 @@ snapshots:
dependencies:
- '@types/estree': 1.0.5
+ '@types/estree': 1.0.7
estree-walker: 3.0.3
is-reference: 3.0.3