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 1 (#35271)

Joshen Lim70a8888b0a4f
diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx
index 819a3668a70..bf3a851352d 100644
--- a/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/ProjectContext.tsx
@@ -5,6 +5,7 @@ import { PROJECT_STATUS } from 'lib/constants'
import { AiAssistantStateContextProvider } from 'state/ai-assistant-state'
import { DatabaseSelectorStateContextProvider } from 'state/database-selector'
import { RoleImpersonationStateContextProvider } from 'state/role-impersonation-state'
+import { StorageExplorerStateContextProvider } from 'state/storage-explorer'
import { TableEditorStateContextProvider } from 'state/table-editor'
export interface ProjectContextType {
@@ -45,11 +46,13 @@ export const ProjectContextProvider = ({
key={`ai-assistant-state-${projectRef}`}
projectRef={projectRef}
>
- <DatabaseSelectorStateContextProvider key={`database-selector-state-${projectRef}`}>
- <RoleImpersonationStateContextProvider key={`role-impersonation-state-${projectRef}`}>
- {children}
- </RoleImpersonationStateContextProvider>
- </DatabaseSelectorStateContextProvider>
+ <StorageExplorerStateContextProvider key={`storage-explorer-state-${projectRef}`}>
+ <DatabaseSelectorStateContextProvider key={`database-selector-state-${projectRef}`}>
+ <RoleImpersonationStateContextProvider key={`role-impersonation-state-${projectRef}`}>
+ {children}
+ </RoleImpersonationStateContextProvider>
+ </DatabaseSelectorStateContextProvider>
+ </StorageExplorerStateContextProvider>
</AiAssistantStateContextProvider>
</TableEditorStateContextProvider>
</ProjectContext.Provider>
diff --git a/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx b/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx
index afd788fd3af..a91a4f3de24 100644
--- a/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx
+++ b/apps/studio/components/layouts/StorageLayout/StorageMenu.tsx
@@ -51,8 +51,13 @@ const StorageMenu = () => {
| 'usage'
| 'logs'
- const { data, error, isLoading, isError, isSuccess } = useBucketsQuery({ projectRef: ref })
- const buckets = data ?? []
+ const {
+ data: buckets = [],
+ error,
+ isLoading,
+ isError,
+ isSuccess,
+ } = useBucketsQuery({ projectRef: ref })
const sortedBuckets =
sort === 'alphabetical'
? buckets.sort((a, b) =>
diff --git a/apps/studio/components/to-be-cleaned/Storage/Storage.types.ts b/apps/studio/components/to-be-cleaned/Storage/Storage.types.ts
index e52f7011b57..b29ce672669 100644
--- a/apps/studio/components/to-be-cleaned/Storage/Storage.types.ts
+++ b/apps/studio/components/to-be-cleaned/Storage/Storage.types.ts
@@ -15,10 +15,12 @@ export interface StorageItem {
type: STORAGE_ROW_TYPES
status: STORAGE_ROW_STATUS
metadata: StorageItemMetadata | null
- isCorrupted: boolean
created_at: string | null
updated_at: string | null
last_accessed_at: string | null
+ // UI specific properties, not from API
+ isCorrupted: boolean
+ path?: string
}
export type StorageItemWithColumn = StorageItem & { columnIndex: number }
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 3cfb338bee8..3fa51bfcdfd 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ColumnContextMenu.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ColumnContextMenu.tsx
@@ -6,6 +6,7 @@ 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 {
STORAGE_ROW_TYPES,
STORAGE_SORT_BY,
@@ -24,12 +25,13 @@ const ColumnContextMenu = ({ id = '' }: ColumnContextMenuProps) => {
columns,
selectedItems,
setSelectedItems,
- setView,
setSortBy,
setSortByOrder,
addNewFolderPlaceholder,
} = storageExplorerStore
+ const snap = useStorageExplorerStateSnapshot()
+
const onSelectCreateFolder = (columnIndex = -1) => {
addNewFolderPlaceholder(columnIndex)
}
@@ -80,10 +82,10 @@ const ColumnContextMenu = ({ id = '' }: ColumnContextMenuProps) => {
}
arrow={<ChevronRight size="14" strokeWidth={1} />}
>
- <Item onClick={() => setView(STORAGE_VIEWS.COLUMNS)}>
+ <Item onClick={() => snap.setView(STORAGE_VIEWS.COLUMNS)}>
<span className="ml-2 text-xs">As columns</span>
</Item>
- <Item onClick={() => setView(STORAGE_VIEWS.LIST)}>
+ <Item onClick={() => snap.setView(STORAGE_VIEWS.LIST)}>
<span className="ml-2 text-xs">As list</span>
</Item>
</Submenu>
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 9d6612288a4..dfbd8a9bc1c 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorer.tsx
@@ -2,6 +2,7 @@ import { noop } from 'lodash'
import { observer } from 'mobx-react-lite'
import { useEffect, useRef } from 'react'
+import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { cn } from 'ui'
import { CONTEXT_MENU_KEYS, STORAGE_VIEWS } from '../Storage.constants'
import type { StorageColumn, StorageItem, StorageItemWithColumn } from '../Storage.types'
@@ -11,7 +12,6 @@ import FolderContextMenu from './FolderContextMenu'
import ItemContextMenu from './ItemContextMenu'
export interface FileExplorerProps {
- view: string
columns: StorageColumn[]
openedFolders: StorageItem[]
selectedItems: StorageItemWithColumn[]
@@ -23,7 +23,6 @@ export interface FileExplorerProps {
}
const FileExplorer = ({
- view = STORAGE_VIEWS.COLUMNS,
columns = [],
openedFolders = [],
selectedItems = [],
@@ -34,6 +33,7 @@ const FileExplorer = ({
onColumnLoadMore = noop,
}: FileExplorerProps) => {
const fileExplorerRef = useRef<any>(null)
+ const snap = useStorageExplorerStateSnapshot()
useEffect(() => {
if (fileExplorerRef) {
@@ -49,19 +49,18 @@ const FileExplorer = ({
ref={fileExplorerRef}
className={cn(
'file-explorer flex flex-grow overflow-x-auto justify-between h-full w-full relative',
- view === STORAGE_VIEWS.LIST && 'flex-col'
+ snap.view === STORAGE_VIEWS.LIST && 'flex-col'
)}
>
<ColumnContextMenu id={CONTEXT_MENU_KEYS.STORAGE_COLUMN} />
<ItemContextMenu id={CONTEXT_MENU_KEYS.STORAGE_ITEM} />
<FolderContextMenu id={CONTEXT_MENU_KEYS.STORAGE_FOLDER} />
- {view === STORAGE_VIEWS.COLUMNS ? (
+ {snap.view === STORAGE_VIEWS.COLUMNS ? (
<div className="flex">
{columns.map((column, index) => (
<FileExplorerColumn
key={`column-${index}`}
index={index}
- view={view}
column={column}
openedFolders={openedFolders}
selectedItems={selectedItems}
@@ -73,13 +72,12 @@ const FileExplorer = ({
/>
))}
</div>
- ) : view === STORAGE_VIEWS.LIST ? (
+ ) : snap.view === STORAGE_VIEWS.LIST ? (
<>
{columns.length > 0 && (
<FileExplorerColumn
fullWidth
index={columns.length - 1}
- view={view}
column={columns[columns.length - 1]}
selectedItems={selectedItems}
itemSearchString={itemSearchString}
@@ -91,7 +89,7 @@ const FileExplorer = ({
)}
</>
) : (
- <div>Unknown view: {view}</div>
+ <div>Unknown view: {snap.view}</div>
)}
</div>
)
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx
index 95ccbb7455f..7d768653923 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerColumn.tsx
@@ -55,7 +55,6 @@ const DragOverOverlay = ({ isOpen, onDragLeave, onDrop, folderIsEmpty }: any) =>
export interface FileExplorerColumnProps {
index: number
- view: STORAGE_VIEWS
column: StorageColumn
fullWidth?: boolean
openedFolders?: StorageItem[]
@@ -69,7 +68,6 @@ export interface FileExplorerColumnProps {
const FileExplorerColumn = ({
index = 0,
- view = STORAGE_VIEWS.COLUMNS,
column,
fullWidth = false,
openedFolders = [],
@@ -146,7 +144,7 @@ const FileExplorerColumn = ({
ref={fileExplorerColumnRef}
className={cn(
fullWidth ? 'w-full' : 'w-64 border-r border-overlay',
- view === STORAGE_VIEWS.LIST && 'h-full',
+ snap.view === STORAGE_VIEWS.LIST && 'h-full',
'hide-scrollbar relative flex flex-shrink-0 flex-col overflow-auto'
)}
onContextMenu={displayMenu}
@@ -159,7 +157,7 @@ const FileExplorerColumn = ({
}}
>
{/* Checkbox selection for select all */}
- {view === STORAGE_VIEWS.COLUMNS && (
+ {snap.view === STORAGE_VIEWS.COLUMNS && (
<div
className={cn(
'sticky top-0 z-10 mb-0 flex items-center bg-table-header-light px-2.5 [[data-theme*=dark]_&]:bg-table-header-dark',
@@ -180,7 +178,7 @@ const FileExplorerColumn = ({
)}
{/* List Interface Header */}
- {view === STORAGE_VIEWS.LIST && (
+ {snap.view === STORAGE_VIEWS.LIST && (
<div className="sticky top-0 py-2 z-10 flex min-w-min items-center border-b border-overlay bg-surface-100 px-2.5">
<div className="flex w-[40%] min-w-[250px] items-center">
<SelectAllCheckbox />
@@ -211,7 +209,7 @@ const FileExplorerColumn = ({
<InfiniteList
items={columnItems}
itemProps={{
- view,
+ view: snap.view,
columnIndex: index,
selectedItems,
openedFolders,
@@ -261,7 +259,7 @@ const FileExplorerColumn = ({
/>
{/* List interface footer */}
- {view === STORAGE_VIEWS.LIST && (
+ {snap.view === STORAGE_VIEWS.LIST && (
<div className="shrink-0 rounded-b-md z-10 flex min-w-min items-center bg-panel-footer-light px-2.5 py-2 [[data-theme*=dark]_&]:bg-panel-footer-dark w-full">
<p className="text-sm">
{formatBytes(columnItemsSize)} for {columnItems.length} items
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 e9b7bf980c9..2574c9f862b 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeader.tsx
@@ -162,8 +162,6 @@ const FileExplorerHeader = ({
const storageExplorerStore = useStorageStore()
const {
- view,
- setView,
columns,
sortBy,
setSortBy,
@@ -333,7 +331,7 @@ const FileExplorerHeader = ({
]}
/>
</form>
- ) : view === STORAGE_VIEWS.COLUMNS ? (
+ ) : snap.view === STORAGE_VIEWS.COLUMNS ? (
<HeaderPathEdit
loading={loading}
isSearching={snap.isSearching}
@@ -368,7 +366,7 @@ const FileExplorerHeader = ({
<Button
type="text"
icon={
- view === 'LIST' ? (
+ snap.view === 'LIST' ? (
<List size={16} strokeWidth={2} />
) : (
<Columns size={16} strokeWidth={2} />
@@ -380,10 +378,10 @@ const FileExplorerHeader = ({
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40 min-w-0">
{VIEW_OPTIONS.map((option) => (
- <DropdownMenuItem key={option.key} onClick={() => setView(option.key)}>
+ <DropdownMenuItem key={option.key} onClick={() => snap.setView(option.key)}>
<div className="flex items-center justify-between w-full">
<p>{option.name}</p>
- {view === option.key && <Check className="text-brand" strokeWidth={2} />}
+ {snap.view === option.key && <Check className="text-brand" strokeWidth={2} />}
</div>
</DropdownMenuItem>
))}
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 8b6daad9cf2..b69bafc6ac6 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
@@ -1,17 +1,19 @@
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 { 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,
- downloadFile,
downloadSelectedFiles,
clearSelectedItems,
setSelectedItemsToDelete,
@@ -35,7 +37,7 @@ const FileExplorerHeaderSelection = () => {
type="primary"
onClick={async () => {
if (selectedItems.length === 1) {
- await downloadFile(selectedItems[0])
+ await downloadFile({ projectRef, bucketId, file: selectedItems[0] })
} else {
await downloadSelectedFiles(selectedItems)
}
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 92bb5ff9f4f..d1df99ba571 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/FileExplorerRow.tsx
@@ -17,6 +17,7 @@ import {
import { useContextMenu } from 'react-contexify'
import SVG from 'react-inlinesvg'
+import { useParams } from 'common'
import type { ItemRenderer } from 'components/ui/InfiniteList'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { BASE_PATH } from 'lib/constants'
@@ -46,7 +47,7 @@ import {
} from '../Storage.constants'
import { StorageItem, StorageItemWithColumn } from '../Storage.types'
import FileExplorerRowEditing from './FileExplorerRowEditing'
-import { copyPathToFolder } from './StorageExplorer.utils'
+import { copyPathToFolder, downloadFile } from './StorageExplorer.utils'
import { useCopyUrl } from './useCopyUrl'
export const RowIcon = ({
@@ -111,6 +112,7 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
selectedItems = [],
openedFolders = [],
}) => {
+ const { ref: projectRef, bucketId } = useParams()
const storageExplorerStore = useStorageStore()
const {
popColumnAtIndex,
@@ -126,7 +128,6 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
setSelectedItemsToMove,
setSelectedFileCustomExpiry,
fetchFolderContents,
- downloadFile,
downloadFolder,
selectRangeItems,
selectedFilePreview,
@@ -260,7 +261,13 @@ const FileExplorerRow: ItemRenderer<StorageItem, FileExplorerRowProps> = ({
{
name: 'Download',
icon: <Download size={14} strokeWidth={1} />,
- onClick: async () => await downloadFile(itemWithColumnIndex),
+ onClick: async () => {
+ await downloadFile({
+ projectRef,
+ bucketId,
+ file: itemWithColumnIndex,
+ })
+ },
},
{ name: 'Separator', icon: undefined, onClick: undefined },
]
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 084290a93e1..b52a350b802 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/ItemContextMenu.tsx
@@ -4,10 +4,12 @@ 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 { URL_EXPIRY_DURATION } from '../Storage.constants'
import { StorageItemWithColumn } from '../Storage.types'
+import { downloadFile } from './StorageExplorer.utils'
import { useCopyUrl } from './useCopyUrl'
interface ItemContextMenuProps {
@@ -15,9 +17,9 @@ interface ItemContextMenuProps {
}
const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
+ const { ref: projectRef, bucketId } = useParams()
const storageExplorerStore = useStorageStore()
const {
- downloadFile,
selectedBucket,
setSelectedItemsToDelete,
setSelectedItemToRename,
@@ -39,7 +41,7 @@ const ItemContextMenu = ({ id = '' }: ItemContextMenuProps) => {
case 'move':
return setSelectedItemsToMove([item])
case 'download':
- return await downloadFile(item)
+ return await downloadFile({ projectRef, bucketId, file: item })
default:
break
}
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 0f89945c81c..1374b522a66 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/PreviewPane.tsx
@@ -4,6 +4,7 @@ import { isEmpty } from 'lodash'
import { AlertCircle, ChevronDown, Clipboard, Download, Loader, Trash2, X } from 'lucide-react'
import SVG from 'react-inlinesvg'
+import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { BASE_PATH } from 'lib/constants'
@@ -18,6 +19,7 @@ import {
} from 'ui'
import { URL_EXPIRY_DURATION } from '../Storage.constants'
import { StorageItem } from '../Storage.types'
+import { downloadFile } from './StorageExplorer.utils'
import { useCopyUrl } from './useCopyUrl'
import { useFetchFileUrlQuery } from './useFetchFileUrlQuery'
@@ -115,9 +117,9 @@ const PreviewFile = ({ item }: { item: StorageItem }) => {
}
const PreviewPane = () => {
+ const { ref: projectRef, bucketId } = useParams()
const storageExplorerStore = useStorageStore()
const {
- downloadFile,
selectedBucket,
selectedFilePreview: file,
closeFilePreview,
@@ -128,9 +130,7 @@ const PreviewPane = () => {
const canUpdateFiles = useCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
- if (!file) {
- return null
- }
+ if (!file) return null
const width = 450
const isOpen = !isEmpty(file)
@@ -211,7 +211,7 @@ const PreviewPane = () => {
type="default"
icon={<Download size={16} strokeWidth={2} />}
disabled={file.isCorrupted}
- onClick={async () => await downloadFile(file)}
+ onClick={async () => await downloadFile({ projectRef, bucketId, file })}
>
Download
</Button>
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 bc34848e6eb..a6d131379d2 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.tsx
@@ -7,6 +7,7 @@ import { useProjectStorageConfigQuery } from 'data/config/project-storage-config
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'
import CustomExpiryModal from './CustomExpiryModal'
@@ -35,7 +36,6 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
popOpenedFoldersAtIndex,
selectedItemsToMove,
clearSelectedItemsToMove,
- view,
currentBucketName,
openBucket,
@@ -49,9 +49,9 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
moveFiles,
} = storageExplorerStore
- const storageExplorerRef = useRef(null)
-
const { ref } = useParams()
+ const storageExplorerRef = useRef(null)
+ const snap = 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
@@ -68,7 +68,7 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => {
const fetchContents = async () => {
- if (view === STORAGE_VIEWS.LIST) {
+ if (snap.view === STORAGE_VIEWS.LIST) {
const currentFolderIdx = openedFolders.length - 1
const currentFolder = openedFolders[currentFolderIdx]
@@ -92,7 +92,7 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
await fetchFolderContents(currentFolder.id, currentFolder.name, currentFolderIdx)
}
}
- } else if (view === STORAGE_VIEWS.COLUMNS) {
+ } else if (snap.view === STORAGE_VIEWS.COLUMNS) {
const paths = openedFolders.map((folder) => folder.name)
fetchFoldersByPath(paths, itemSearchString, true)
}
@@ -102,9 +102,9 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
}, [itemSearchString])
useEffect(() => {
- // Load user preferences (view and sort)
+ // Load user preferences (view, sort, sortBy)
loadExplorerPreferences()
- }, [])
+ }, [ref])
useEffect(() => {
openBucket(bucket)
@@ -196,7 +196,6 @@ const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
)}
<div className="flex h-full" style={{ height: fileExplorerHeight }}>
<FileExplorer
- view={view}
columns={columns}
openedFolders={openedFolders}
selectedItems={selectedItems}
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.ts b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.ts
deleted file mode 100644
index 18df10a550d..00000000000
--- a/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { copyToClipboard } from 'lib/helpers'
-import { toast } from 'sonner'
-import { StorageItem, StorageItemWithColumn } from '../Storage.types'
-
-export const copyPathToFolder = (openedFolders: StorageItem[], item: StorageItemWithColumn) => {
- const folders = openedFolders.slice(0, item.columnIndex).map((folder) => folder.name)
- const path = folders.length > 0 ? `${folders.join('/')}/${item.name}` : item.name
- copyToClipboard(path)
- toast.success(`Copied path to folder "${item.name}"`)
-}
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
new file mode 100644
index 00000000000..3d8dbf518ad
--- /dev/null
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageExplorer/StorageExplorer.utils.tsx
@@ -0,0 +1,87 @@
+import { downloadBucketObject } from 'data/storage/bucket-object-download-mutation'
+import { copyToClipboard } from 'lib/helpers'
+import { toast } from 'sonner'
+import { SONNER_DEFAULT_DURATION } from 'ui'
+import { StorageItem, StorageItemWithColumn } from '../Storage.types'
+
+export const copyPathToFolder = (openedFolders: StorageItem[], item: StorageItemWithColumn) => {
+ const folders = openedFolders.slice(0, item.columnIndex).map((folder) => folder.name)
+ const path = folders.length > 0 ? `${folders.join('/')}/${item.name}` : item.name
+ copyToClipboard(path)
+ toast.success(`Copied path to folder "${item.name}"`)
+}
+
+export const formatTime = (seconds: number) => {
+ const days = Math.floor(seconds / (24 * 3600))
+ seconds %= 24 * 3600
+ const hours = Math.floor(seconds / 3600)
+ seconds %= 3600
+ const minutes = Math.floor(seconds / 60)
+ seconds = Math.floor(seconds % 60)
+
+ if (days > 0) return `${days}d `
+ if (hours > 0) return `${hours}h `
+ if (minutes > 0) return `${minutes}m `
+ return `${seconds}s`
+}
+
+export const downloadFile = async ({
+ projectRef,
+ bucketId,
+ file,
+ showToast = true,
+ returnBlob = false,
+}: {
+ projectRef?: string
+ bucketId?: string
+ file: StorageItemWithColumn
+ showToast?: boolean
+ returnBlob?: boolean
+}) => {
+ if (!projectRef) return toast.error('Failed to download: Project ref is required')
+ if (!bucketId) return toast.error('Failed to download: Bucket ID is required')
+ if (!file.path) return toast.error('Failed to download: Unable to find path to file')
+
+ const fileName: string = file.name
+ const fileMimeType = file?.metadata?.mimetype ?? undefined
+
+ const toastId = showToast ? toast.loading(`Retrieving ${fileName}...`) : undefined
+
+ try {
+ const data = await downloadBucketObject({
+ projectRef,
+ bucketId,
+ path: file.path,
+ })
+
+ const blob = await data.blob()
+ const newBlob = new Blob([blob], { type: fileMimeType })
+ if (returnBlob) return { name: fileName, blob: newBlob }
+
+ const blobUrl = window.URL.createObjectURL(newBlob)
+ const link = document.createElement('a')
+ link.href = blobUrl
+ link.setAttribute('download', `${fileName}`)
+ document.body.appendChild(link)
+ link.click()
+ link.parentNode?.removeChild(link)
+ window.URL.revokeObjectURL(blob)
+ if (toastId) {
+ toast.success(`Downloading ${fileName}`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+ return true
+ } catch (err) {
+ if (toastId) {
+ toast.error(`Failed to download ${fileName}`, {
+ id: toastId,
+ closeButton: true,
+ duration: SONNER_DEFAULT_DURATION,
+ })
+ }
+ return false
+ }
+}
diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.ts
index 3ca7d99257d..942be406eb5 100644
--- a/apps/studio/lib/constants/index.ts
+++ b/apps/studio/lib/constants/index.ts
@@ -48,14 +48,13 @@ export const LOCAL_STORAGE_KEYS = {
UI_PREVIEW_CLS: 'supabase-ui-cls',
UI_PREVIEW_INLINE_EDITOR: 'supabase-ui-preview-inline-editor',
UI_ONBOARDING_NEW_PAGE_SHOWN: 'supabase-ui-onboarding-new-page-shown',
-
UI_TABLE_EDITOR_TABS: 'supabase-ui-table-editor-tabs',
UI_SQL_EDITOR_TABS: 'supabase-ui-sql-editor-tabs',
UI_NEW_LAYOUT_PREVIEW: 'supabase-ui-new-layout-preview',
-
NEW_LAYOUT_NOTICE_ACKNOWLEDGED: 'new-layout-notice-acknowledge',
DASHBOARD_HISTORY: (ref: string) => `dashboard-history-${ref}`,
+ STORAGE_PREFERENCE: (ref: string) => `storage-explorer-${ref}`,
SQL_EDITOR_INTELLISENSE: 'supabase_sql-editor-intellisense-enabled',
SQL_EDITOR_SPLIT_SIZE: 'supabase_sql-editor-split-size',
diff --git a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
index 69ba342545c..63fb40418ea 100644
--- a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
+++ b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
@@ -29,6 +29,10 @@ import {
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'
@@ -38,7 +42,8 @@ import { downloadBucketObject } from 'data/storage/bucket-object-download-mutati
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 { IS_PLATFORM, LOCAL_STORAGE_KEYS } 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'
@@ -72,7 +77,6 @@ const STORAGE_PROGRESS_INFO_TEXT = "Do not close the browser until it's complete
class StorageExplorerStore {
projectRef: string = ''
- view: STORAGE_VIEWS = STORAGE_VIEWS.COLUMNS
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
@@ -155,7 +159,7 @@ class StorageExplorerStore {
}
private getLocalStorageKey = () => {
- return `supabase-storage-${this.projectRef}`
+ return LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(this.projectRef)
}
private getLatestColumnIndex = () => {
@@ -190,12 +194,6 @@ class StorageExplorerStore {
this.clearSelectedItems()
}
- setView = (view: STORAGE_VIEWS) => {
- this.view = view
- this.closeFilePreview()
- this.updateExplorerPreferences()
- }
-
setSortBy = async (sortBy: STORAGE_SORT_BY) => {
this.sortBy = sortBy
this.closeFilePreview()
@@ -415,7 +413,7 @@ class StorageExplorerStore {
<SonnerProgress
progress={progress}
message={`Uploading ${totalFiles} file${totalFiles > 1 ? 's' : ''}...`}
- progressPrefix={`${remainingTime && !isNaN(remainingTime) && isFinite(remainingTime) && remainingTime !== 0 ? `${this.formatTime(remainingTime)} remaining – ` : ''}`}
+ progressPrefix={`${remainingTime && !isNaN(remainingTime) && isFinite(remainingTime) && remainingTime !== 0 ? `${formatTime(remainingTime)} remaining – ` : ''}`}
action={
toastId && (
<Button
@@ -1058,7 +1056,12 @@ class StorageExplorerStore {
const promises = formattedFilesWithPrefix.map((file) => {
return () => {
return new Promise<{ name: string; blob: Blob } | boolean>(async (resolve) => {
- const data = await this.downloadFile(file, showIndividualToast, returnBlob)
+ 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 })
@@ -1103,57 +1106,6 @@ class StorageExplorerStore {
})
}
- downloadFile = async (file: StorageItemWithColumn, showToast = true, returnBlob = false) => {
- const fileName: string = file.name
- const fileMimeType = file?.metadata?.mimetype ?? undefined
-
- const toastId = showToast ? toast.loading(`Retrieving ${fileName}...`) : undefined
-
- const pathToFile = this.openedFolders
- .slice(0, file.columnIndex)
- .map((folder) => folder.name)
- .join('/')
- const formattedPathToFile = pathToFile.length > 0 ? `${pathToFile}/${fileName}` : fileName
- try {
- const data = await downloadBucketObject({
- projectRef: this.projectRef,
- bucketId: this.selectedBucket.id,
- path: formattedPathToFile,
- })
-
- const blob = await data.blob()
- const newBlob = new Blob([blob], { type: fileMimeType })
-
- if (returnBlob) return { name: fileName, blob: newBlob }
-
- const blobUrl = window.URL.createObjectURL(newBlob)
- const link = document.createElement('a')
- link.href = blobUrl
- link.setAttribute('download', `${fileName}`)
- document.body.appendChild(link)
- link.click()
- link.parentNode?.removeChild(link)
- window.URL.revokeObjectURL(blob)
- if (toastId) {
- toast.success(`Downloading ${fileName}`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
- return true
- } catch {
- if (toastId) {
- toast.error(`Failed to download ${fileName}`, {
- id: toastId,
- closeButton: true,
- duration: SONNER_DEFAULT_DURATION,
- })
- }
- return false
- }
- }
-
renameFile = async (file: StorageItem, newName: string, columnIndex: number) => {
const originalName = file.name
if (originalName === newName || newName.length === 0) {
@@ -1232,7 +1184,7 @@ class StorageExplorerStore {
this.updateRowStatus(folderName, STORAGE_ROW_STATUS.READY, index)
- const formattedItems = this.formatFolderItems(data)
+ const formattedItems = this.formatFolderItems(data, prefix)
this.pushColumnAtIndex(
{
id: folderId || folderName,
@@ -1631,7 +1583,7 @@ class StorageExplorerStore {
return name
}
- private formatFolderItems = (items: StorageObject[] = []): StorageItem[] => {
+ private formatFolderItems = (items: StorageObject[] = [], prefix?: string): StorageItem[] => {
const formattedItems =
(items ?? [])
?.filter((item) => item.name !== EMPTY_FOLDER_PLACEHOLDER_FILE_NAME)
@@ -1657,6 +1609,7 @@ class StorageExplorerStore {
type,
status,
isCorrupted,
+ path: !!prefix ? `${prefix}/${item.name}` : item.name,
}
return itemObj
}) ?? []
@@ -1758,26 +1711,25 @@ class StorageExplorerStore {
private updateExplorerPreferences = () => {
const localStorageKey = this.getLocalStorageKey()
- const preferences = {
- view: this.view,
- sortBy: this.sortBy,
- sortByOrder: this.sortByOrder,
+ 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,
+ })
+ )
}
- localStorage.setItem(localStorageKey, JSON.stringify(preferences))
- return preferences
}
loadExplorerPreferences = () => {
const localStorageKey = this.getLocalStorageKey()
const preferences = localStorage?.getItem(localStorageKey) ?? undefined
if (preferences !== undefined) {
- const { view, sortBy, sortByOrder } = JSON.parse(preferences)
- this.view = view
- this.sortBy = sortBy
- this.sortByOrder = sortByOrder
- } else {
- const { view, sortBy, sortByOrder } = this.updateExplorerPreferences()
- this.view = view
+ const { sortBy, sortByOrder } = JSON.parse(preferences)
this.sortBy = sortBy
this.sortByOrder = sortByOrder
}
@@ -1832,20 +1784,6 @@ class StorageExplorerStore {
return totalRemainingTime
}
-
- private formatTime(seconds: number) {
- const days = Math.floor(seconds / (24 * 3600))
- seconds %= 24 * 3600
- const hours = Math.floor(seconds / 3600)
- seconds %= 3600
- const minutes = Math.floor(seconds / 60)
- seconds = Math.floor(seconds % 60)
-
- if (days > 0) return `${days}d `
- if (hours > 0) return `${hours}h `
- if (minutes > 0) return `${minutes}m `
- return `${seconds}s`
- }
}
export default StorageExplorerStore
diff --git a/apps/studio/state/storage-explorer.ts b/apps/studio/state/storage-explorer.ts
deleted file mode 100644
index ae0a905b52e..00000000000
--- a/apps/studio/state/storage-explorer.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { proxy, snapshot, useSnapshot } from 'valtio'
-
-export const storageExplorerState = proxy({
- isSearching: false,
- setIsSearching: (bool: boolean) => {
- storageExplorerState.isSearching = bool
- },
-})
-
-export const getStorageExplorerStateSnapshot = () => snapshot(storageExplorerState)
-
-export const useStorageExplorerStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
- useSnapshot(storageExplorerState, options)
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
new file mode 100644
index 00000000000..886e8eeae19
--- /dev/null
+++ b/apps/studio/state/storage-explorer.tsx
@@ -0,0 +1,97 @@
+import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
+import { useLatest } from 'react-use'
+import { proxy, snapshot, useSnapshot } from 'valtio'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import {
+ STORAGE_SORT_BY,
+ STORAGE_SORT_BY_ORDER,
+ STORAGE_VIEWS,
+} from 'components/to-be-cleaned/Storage/Storage.constants'
+import { LOCAL_STORAGE_KEYS } from 'lib/constants'
+import { tryParseJson } from 'lib/helpers'
+
+const DEFAULT_PREFERENCES = {
+ view: STORAGE_VIEWS.COLUMNS,
+ sortBy: STORAGE_SORT_BY.NAME,
+ sortByOrder: STORAGE_SORT_BY_ORDER.ASC,
+}
+
+function createStorageExplorerState({ projectRef }: { projectRef: string }) {
+ const localStorageKey = LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(projectRef)
+ const { view, sortBy, sortByOrder } =
+ (typeof window !== 'undefined' && tryParseJson(localStorage?.getItem(localStorageKey))) ||
+ DEFAULT_PREFERENCES
+
+ const state = proxy({
+ projectRef,
+
+ view,
+ sortBy,
+ sortByOrder,
+ isSearching: false,
+
+ setView: (value: STORAGE_VIEWS) => {
+ state.view = value
+ state.updateExplorerPreference()
+ },
+ setSortBy: (value: STORAGE_SORT_BY) => {
+ state.sortBy = value
+ state.updateExplorerPreference()
+ },
+ setSortByOrder: (value: STORAGE_SORT_BY_ORDER) => {
+ state.sortByOrder = value
+ state.updateExplorerPreference()
+ },
+ setIsSearching: (value: boolean) => (state.isSearching = value),
+
+ updateExplorerPreference: () => {
+ const localStorageKey = LOCAL_STORAGE_KEYS.STORAGE_PREFERENCE(projectRef)
+ const { view, sortBy, sortByOrder } = state
+ localStorage.setItem(localStorageKey, JSON.stringify({ view, sortBy, sortByOrder }))
+ },
+ })
+
+ return state
+}
+
+type StorageExplorerState = ReturnType<typeof createStorageExplorerState>
+
+const StorageExplorerStateContext = createContext<StorageExplorerState>(
+ createStorageExplorerState({ projectRef: '' })
+)
+
+export const StorageExplorerStateContextProvider = ({ children }: PropsWithChildren) => {
+ const { project } = useProjectContext()
+ const [state, setState] = useState(() =>
+ createStorageExplorerState({ projectRef: project?.ref ?? '' })
+ )
+
+ const stateRef = useLatest(state)
+
+ // [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
+ // So the useEffect here is to make sure that the project ref is loaded into the state properly
+ // Although I'd be keen to re-investigate this to see if we can remove this
+ useEffect(() => {
+ const snap = snapshot(stateRef.current)
+ const hasDataReady = !!project?.ref
+ const isDifferentProject = snap.projectRef !== project?.ref
+
+ if (hasDataReady && isDifferentProject) {
+ setState(createStorageExplorerState({ projectRef: project?.ref ?? '' }))
+ }
+ }, [project?.ref, stateRef])
+
+ return (
+ <StorageExplorerStateContext.Provider value={state}>
+ {children}
+ </StorageExplorerStateContext.Provider>
+ )
+}
+
+export function useStorageExplorerStateSnapshot(options?: Parameters<typeof useSnapshot>[1]) {
+ const state = useContext(StorageExplorerStateContext)
+ return useSnapshot(state, options)
+}