Skip to content

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

Improve time to FCP for storage files explorer (#40514)

Joshen Limb164da439255
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx
index 2c3f7893e44..cc44179f529 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx
@@ -3,7 +3,7 @@ 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 { CONTEXT_MENU_KEYS, STORAGE_ROW_STATUS, STORAGE_VIEWS } from '../Storage.constants'
import type { StorageColumn, StorageItemWithColumn } from '../Storage.types'
import { ColumnContextMenu } from './ColumnContextMenu'
import { FileExplorerColumn } from './FileExplorerColumn'
@@ -32,6 +32,9 @@ export const FileExplorer = ({
const fileExplorerRef = useRef<any>(null)
const snap = useStorageExplorerStateSnapshot()
+ // [Joshen] StorageExplorer will always have at least 1 column once data is loaded
+ const hasLoaded = columns.length > 0
+
useEffect(() => {
if (fileExplorerRef) {
const { scrollWidth, clientWidth } = fileExplorerRef.current
@@ -52,7 +55,12 @@ export const FileExplorer = ({
<ColumnContextMenu id={CONTEXT_MENU_KEYS.STORAGE_COLUMN} />
<ItemContextMenu id={CONTEXT_MENU_KEYS.STORAGE_ITEM} />
<FolderContextMenu id={CONTEXT_MENU_KEYS.STORAGE_FOLDER} />
- {snap.view === STORAGE_VIEWS.COLUMNS ? (
+
+ {!hasLoaded ? (
+ <FileExplorerColumn
+ column={{ id: '', name: '', items: [], status: STORAGE_ROW_STATUS.LOADING }}
+ />
+ ) : snap.view === STORAGE_VIEWS.COLUMNS ? (
<div className="flex">
{columns.map((column, index) => (
<FileExplorerColumn
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerColumn.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerColumn.tsx
index 0434db1514a..233e8b7142f 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerColumn.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerColumn.tsx
@@ -57,15 +57,15 @@ const DragOverOverlay = ({ isOpen, onDragLeave, onDrop, folderIsEmpty }: any) =>
}
export interface FileExplorerColumnProps {
- index: number
+ index?: number
column: StorageColumn
fullWidth?: boolean
- selectedItems: StorageItemWithColumn[]
- itemSearchString: string
- onFilesUpload: (event: any, index: number) => void
- onSelectAllItemsInColumn: (index: number) => void
- onSelectColumnEmptySpace: (index: number) => void
- onColumnLoadMore: (index: number, column: StorageColumn) => void
+ selectedItems?: StorageItemWithColumn[]
+ itemSearchString?: string
+ onFilesUpload?: (event: any, index: number) => void
+ onSelectAllItemsInColumn?: (index: number) => void
+ onSelectColumnEmptySpace?: (index: number) => void
+ onColumnLoadMore?: (index: number, column: StorageColumn) => void
}
export const FileExplorerColumn = ({
@@ -73,7 +73,7 @@ export const FileExplorerColumn = ({
column,
fullWidth = false,
selectedItems = [],
- itemSearchString,
+ itemSearchString = '',
onFilesUpload = noop,
onSelectAllItemsInColumn = noop,
onSelectColumnEmptySpace = noop,
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx
index abfc34bbbf4..8948e8dd512 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx
@@ -1,5 +1,5 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { compact, debounce, isEqual, noop } from 'lodash'
+import { compact, isEqual, noop } from 'lodash'
import {
Check,
ChevronLeft,
@@ -14,7 +14,7 @@ import {
Upload,
X,
} from 'lucide-react'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { APIDocsButton } from 'components/ui/APIDocsButton'
@@ -146,12 +146,10 @@ export const FileExplorerHeader = ({
setItemSearchString = noop,
onFilesUpload = noop,
}: FileExplorerHeader) => {
- const debounceDuration = 300
const snap = useStorageExplorerStateSnapshot()
const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
const [pathString, setPathString] = useState('')
- const [searchString, setSearchString] = useState('')
const [loading, setLoading] = useState({ isLoading: false, message: '' })
const [isEditingPath, setIsEditingPath] = useState(false)
@@ -182,10 +180,6 @@ export const FileExplorerHeader = ({
const backDisabled = columns.length <= 1
const { can: canUpdateStorage } = useAsyncCheckPermissions(PermissionAction.STORAGE_WRITE, '*')
- useEffect(() => {
- if (itemSearchString) setSearchString(itemSearchString)
- }, [])
-
useEffect(() => {
// [Joshen] Somehow toggle search triggers this despite breadcrumbs
// being unchanged. Manually doing a prop check to fix this
@@ -195,13 +189,6 @@ export const FileExplorerHeader = ({
}
}, [breadcrumbs])
- const searchInputHandler = useCallback(debounce(setItemSearchString, debounceDuration), [])
- const onSearchInputUpdate = (event: any) => {
- setSearchString(event.target.value)
- // @ts-ignore
- searchInputHandler(event.target.value)
- }
-
const onSelectBack = () => {
popColumn()
popOpenedFolders()
@@ -260,7 +247,6 @@ export const FileExplorerHeader = ({
}
const onCancelSearch = () => {
- setSearchString('')
snap.setIsSearching(false)
setItemSearchString('')
}
@@ -480,8 +466,8 @@ export const FileExplorerHeader = ({
]}
placeholder="Search for a file or folder"
type="text"
- value={searchString}
- onChange={onSearchInputUpdate}
+ value={itemSearchString}
+ onChange={(event) => setItemSearchString(event.target.value)}
/>
) : (
<Button
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
index c6471fd9174..f6afa9635b7 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
@@ -1,11 +1,14 @@
import { compact, get, isEmpty, uniqBy } from 'lodash'
import { useEffect, useRef, useState } from 'react'
+import { useDebounce } from '@uidotdev/usehooks'
import { useParams } from 'common'
import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'
import type { Bucket } from 'data/storage/buckets-query'
+import useLatest from 'hooks/misc/useLatest'
import { IS_PLATFORM } from 'lib/constants'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
+import { useSelectedBucket } from '../FilesBuckets/useSelectedBucket'
import { STORAGE_ROW_TYPES, STORAGE_VIEWS } from '../Storage.constants'
import { ConfirmDeleteModal } from './ConfirmDeleteModal'
import { CustomExpiryModal } from './CustomExpiryModal'
@@ -15,14 +18,11 @@ import { FileExplorerHeaderSelection } from './FileExplorerHeaderSelection'
import { MoveItemsModal } from './MoveItemsModal'
import { PreviewPane } from './PreviewPane'
-interface StorageExplorerProps {
- bucket: Bucket
-}
-
-export const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
+export const StorageExplorer = () => {
const { ref } = useParams()
const storageExplorerRef = useRef(null)
const {
+ projectRef,
view,
columns,
selectedItems,
@@ -48,50 +48,69 @@ export const StorageExplorer = ({ bucket }: StorageExplorerProps) => {
} = useStorageExplorerStateSnapshot()
useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })
+ const { data: bucket } = useSelectedBucket()
// This state exists outside of the header because FileExplorerColumn needs to listen to these as well
// Things like showing results from a search filter is "temporary", hence we use react state to manage
const [itemSearchString, setItemSearchString] = useState('')
+ const debouncedSearchString = useDebounce(itemSearchString, 500)
+ const fetchFoldersByPathRef = useLatest(fetchFoldersByPath)
+ const fetchFolderContentsRef = useLatest(fetchFolderContents)
+ const viewRef = useLatest(view)
+ const openedFoldersRef = useLatest(openedFolders)
useEffect(() => {
- const fetchContents = async () => {
- if (view === STORAGE_VIEWS.LIST) {
- const currentFolderIdx = openedFolders.length - 1
- const currentFolder = openedFolders[currentFolderIdx]
+ const fetchContents = async (bucket: Bucket) => {
+ if (viewRef.current === STORAGE_VIEWS.LIST) {
+ const currentFolderIdx = openedFoldersRef.current.length - 1
+ const currentFolder = openedFoldersRef.current[currentFolderIdx]
const folderId = !currentFolder ? bucket.id : currentFolder.id
const folderName = !currentFolder ? bucket.name : currentFolder.name
const index = !currentFolder ? -1 : currentFolderIdx
- await fetchFolderContents({
+ await fetchFolderContentsRef.current({
bucketId: bucket.id,
folderId,
folderName,
index,
- searchString: itemSearchString,
+ searchString: debouncedSearchString,
})
- } else if (view === STORAGE_VIEWS.COLUMNS) {
- if (openedFolders.length > 0) {
- const paths = openedFolders.map((folder) => folder.name)
- fetchFoldersByPath({ paths, searchString: itemSearchString, showLoading: true })
+ } else if (viewRef.current === STORAGE_VIEWS.COLUMNS) {
+ if (openedFoldersRef.current.length > 0) {
+ const paths = openedFoldersRef.current.map((folder) => folder.name)
+ fetchFoldersByPathRef.current({
+ paths,
+ searchString: debouncedSearchString,
+ showLoading: true,
+ })
} else {
- await fetchFolderContents({
+ await fetchFolderContentsRef.current({
bucketId: bucket.id,
folderId: bucket.id,
folderName: bucket.name,
index: -1,
- searchString: itemSearchString,
+ searchString: debouncedSearchString,
})
}
}
}
- fetchContents()
- }, [itemSearchString])
-
+ if (bucket && !!projectRef) fetchContents(bucket)
+ }, [
+ bucket,
+ projectRef,
+ debouncedSearchString,
+ viewRef,
+ openedFoldersRef,
+ fetchFolderContentsRef,
+ fetchFoldersByPathRef,
+ ])
+
+ const openBucketRef = useLatest(openBucket)
useEffect(() => {
- openBucket(bucket)
- }, [bucket])
+ if (bucket && !!projectRef) openBucketRef.current(bucket)
+ }, [bucket, projectRef, openBucketRef])
/** Checkbox selection methods */
/** [Joshen] We'll only support checkbox selection for files ONLY */
diff --git a/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsx b/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsx
index e3777f15808..50c27db6ef8 100644
--- a/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsx
+++ b/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsx
@@ -15,10 +15,8 @@ import DefaultLayout from 'components/layouts/DefaultLayout'
import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
import StorageLayout from 'components/layouts/StorageLayout/StorageLayout'
import { Bucket } from 'data/storage/buckets-query'
-import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useStoragePolicyCounts } from 'hooks/storage/useStoragePolicyCounts'
import { Bucket as BucketIcon } from 'icons'
-import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import type { NextPageWithLayout } from 'types'
import {
Badge,
@@ -33,8 +31,6 @@ import {
const BucketPage: NextPageWithLayout = () => {
const router = useRouter()
const { bucketId, ref } = useParams()
- const { data: project } = useSelectedProjectQuery()
- const { projectRef } = useStorageExplorerStateSnapshot()
const { data: bucket, error, isSuccess, isError } = useSelectedBucket()
const [modal, setModal] = useState<'edit' | 'empty' | 'delete' | null>(null)
@@ -49,9 +45,6 @@ const BucketPage: NextPageWithLayout = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isSuccess])
- // [Joshen] Checking against projectRef from storage explorer to check if the store has initialized
- if (!project || !projectRef || !isSuccess) return null
-
if (isError) {
return <StorageBucketsError error={error as any} />
}
@@ -140,11 +133,9 @@ const BucketPage: NextPageWithLayout = () => {
</>
}
>
- {!!bucket && (
- <div className="flex-1 min-h-0 px-6 pb-6">
- <StorageExplorer bucket={bucket} />
- </div>
- )}
+ <div className="flex-1 min-h-0 px-6 pb-6">
+ <StorageExplorer />
+ </div>
</PageLayout>
{bucket && (
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index 08004705897..1e2a58ee330 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -268,14 +268,7 @@ function createStorageExplorerState({
},
openBucket: async (bucket: Bucket) => {
- const { id, name } = bucket
state.setSelectedBucket(bucket)
- await state.fetchFolderContents({
- bucketId: bucket.id,
- folderId: id,
- folderName: name,
- index: -1,
- })
},
// ======== Folders CRUD ========
@@ -1281,6 +1274,10 @@ function createStorageExplorerState({
// Resource already exists
toast.error(`Failed to upload ${file.name}: File name already exists.`)
break
+ case 400:
+ // Invalid key
+ toast.error(`Failed to upload ${file.name}: File name is invalid`)
+ break
}
} else {
toast.error(`Failed to upload ${file.name}: ${error.message}`)
@@ -1843,7 +1840,9 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
const [state, setState] = useState(() => createStorageExplorerState(DEFAULT_STATE_CONFIG))
const stateRef = useLatest(state)
- const { data: settings } = useProjectSettingsV2Query({ projectRef: project?.ref })
+ const { data: settings, isSuccess: isSuccessSettings } = useProjectSettingsV2Query({
+ projectRef: project?.ref,
+ })
const protocol = settings?.app_config?.protocol ?? 'https'
const endpoint = settings?.app_config?.endpoint
@@ -1856,8 +1855,9 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
// Although I'd be keen to re-investigate this to see if we can remove this
useEffect(() => {
const hasDataReady = !!project?.ref
+ const storeAlreadyLoaded = state.projectRef === project?.ref
- if (!isPaused && hasDataReady) {
+ if (!isPaused && hasDataReady && !storeAlreadyLoaded && isSuccessSettings) {
setState(
createStorageExplorerState({
projectRef: project?.ref ?? '',
@@ -1889,7 +1889,17 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
})
)
}
- }, [project?.ref, stateRef, isPaused, resumableUploadUrl, protocol, endpoint])
+ }, [
+ state.projectRef,
+ project?.ref,
+ project?.connectionString,
+ stateRef,
+ isPaused,
+ resumableUploadUrl,
+ protocol,
+ endpoint,
+ isSuccessSettings,
+ ])
return (
<StorageExplorerStateContext.Provider value={state}>