Skip to content

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

fix(studio): correct storage explorer listing pagination and column scroll (#50476)

Francesco Sansalvadorec8a9a7a63065
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.test.tsx
new file mode 100644
index 00000000000..5a3b472eab9
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.test.tsx
@@ -0,0 +1,129 @@
+import { act, render } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { STORAGE_ROW_STATUS, STORAGE_VIEWS } from '../Storage.constants'
+import type { StorageColumn } from '../Storage.types'
+import { FileExplorer } from './FileExplorer'
+
+const { mockUseStorageExplorerStateSnapshot, mockUseStoragePreference } = vi.hoisted(() => ({
+ mockUseStorageExplorerStateSnapshot: vi.fn(),
+ mockUseStoragePreference: vi.fn(),
+}))
+
+vi.mock('@/state/storage-explorer', () => ({
+ useStorageExplorerStateSnapshot: () => mockUseStorageExplorerStateSnapshot(),
+}))
+vi.mock('./useStoragePreference', () => ({
+ useStoragePreference: () => mockUseStoragePreference(),
+}))
+// The columns themselves are irrelevant here — only the scroll container's geometry is.
+vi.mock('./FileExplorerColumn', () => ({
+ FileExplorerColumn: () => <div data-testid="column" />,
+}))
+
+const COLUMN_WIDTH = 256
+const CONTAINER_WIDTH = 600
+const PREVIEW_PANE_WIDTH = 450
+
+function makeColumns(count: number): StorageColumn[] {
+ return Array.from({ length: count }, (_, index) => ({
+ id: `col-${index}`,
+ name: `col-${index}`,
+ path: '',
+ status: STORAGE_ROW_STATUS.READY,
+ items: [],
+ }))
+}
+
+/**
+ * jsdom reports every element as zero-sized, so the scroll container's geometry is
+ * defined by hand: total width grows with the column count, and the visible width
+ * shrinks while the preview pane is open.
+ */
+function applyLayout(
+ container: HTMLElement,
+ { columnCount, isPreviewOpen }: { columnCount: number; isPreviewOpen: boolean }
+) {
+ Object.defineProperty(container, 'scrollWidth', {
+ configurable: true,
+ get: () => columnCount * COLUMN_WIDTH,
+ })
+ Object.defineProperty(container, 'clientWidth', {
+ configurable: true,
+ get: () => CONTAINER_WIDTH - (isPreviewOpen ? PREVIEW_PANE_WIDTH : 0),
+ })
+}
+
+/** The callbacks have runtime defaults but are required by the prop type. */
+const noopProps = {
+ selectedItems: [],
+ itemSearchString: '',
+ onFilesUpload: vi.fn(),
+ onSelectAllItemsInColumn: vi.fn(),
+ onSelectColumnEmptySpace: vi.fn(),
+ onColumnLoadMore: vi.fn(),
+}
+
+function getScrollContainer() {
+ const container = document.querySelector('.file-explorer')
+ if (!(container instanceof HTMLElement)) throw new Error('scroll container not found')
+ return container
+}
+
+describe('FileExplorer horizontal scroll', () => {
+ beforeEach(() => {
+ mockUseStorageExplorerStateSnapshot.mockReset()
+ mockUseStoragePreference.mockReset()
+ mockUseStoragePreference.mockReturnValue({ view: STORAGE_VIEWS.COLUMNS })
+ mockUseStorageExplorerStateSnapshot.mockReturnValue({
+ projectRef: 'test-ref',
+ selectedFilePreview: undefined,
+ })
+ })
+
+ it('scrolls the deepest column into view', () => {
+ const columns = makeColumns(4)
+ const { rerender } = render(<FileExplorer columns={[]} {...noopProps} />)
+
+ const container = getScrollContainer()
+ applyLayout(container, { columnCount: 4, isPreviewOpen: false })
+ rerender(<FileExplorer columns={columns} {...noopProps} />)
+
+ expect(container.scrollLeft).toBe(4 * COLUMN_WIDTH - CONTAINER_WIDTH)
+ })
+
+ it('re-scrolls when the preview pane opens and takes width off the container', () => {
+ const columns = makeColumns(4)
+ const { rerender } = render(<FileExplorer columns={columns} {...noopProps} />)
+
+ const container = getScrollContainer()
+ applyLayout(container, { columnCount: 4, isPreviewOpen: false })
+ rerender(<FileExplorer columns={columns} {...noopProps} />)
+ const scrollBeforePreview = container.scrollLeft
+
+ // Deep-link restore opens the preview in a later commit, shrinking the viewport
+ act(() => {
+ mockUseStorageExplorerStateSnapshot.mockReturnValue({
+ projectRef: 'test-ref',
+ selectedFilePreview: { id: 'file-1', name: 'app icon-2.svg', columnIndex: 3 },
+ })
+ applyLayout(container, { columnCount: 4, isPreviewOpen: true })
+ })
+ rerender(<FileExplorer columns={columns} {...noopProps} />)
+
+ expect(container.scrollLeft).toBe(4 * COLUMN_WIDTH - (CONTAINER_WIDTH - PREVIEW_PANE_WIDTH))
+ expect(container.scrollLeft).toBeGreaterThan(scrollBeforePreview)
+ })
+
+ it('does not scroll in list view', () => {
+ mockUseStoragePreference.mockReturnValue({ view: STORAGE_VIEWS.LIST })
+ const columns = makeColumns(4)
+ const { rerender } = render(<FileExplorer columns={[]} {...noopProps} />)
+
+ const container = getScrollContainer()
+ applyLayout(container, { columnCount: 4, isPreviewOpen: false })
+ rerender(<FileExplorer columns={columns} {...noopProps} />)
+
+ expect(container.scrollLeft).toBe(0)
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx
index bf9abe11523..247ebf6c923 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx
@@ -29,18 +29,18 @@ export const FileExplorer = ({
onSelectColumnEmptySpace = noop,
onColumnLoadMore = noop,
}: FileExplorerProps) => {
- const fileExplorerRef = useRef<any>(null)
+ const fileExplorerRef = useRef<HTMLDivElement>(null)
const snap = useStorageExplorerStateSnapshot()
const { view } = useStoragePreference(snap.projectRef)
+ const isPreviewOpen = !!snap.selectedFilePreview
+ // Keep the deepest column in view. Also re-runs when the preview pane opens, since it
+ // takes 450px off the container and would otherwise hide the column it belongs to.
useEffect(() => {
- if (fileExplorerRef) {
- const { scrollWidth, clientWidth } = fileExplorerRef.current
- if (scrollWidth > clientWidth) {
- fileExplorerRef.current.scrollLeft += scrollWidth - clientWidth
- }
- }
- }, [columns])
+ const container = fileExplorerRef.current
+ if (!container || view !== STORAGE_VIEWS.COLUMNS) return
+ container.scrollLeft = container.scrollWidth - container.clientWidth
+ }, [columns.length, view, isPreviewOpen])
return (
<div
diff --git a/apps/studio/state/storage-explorer.test.ts b/apps/studio/state/storage-explorer.test.ts
new file mode 100644
index 00000000000..00536fc4c4e
--- /dev/null
+++ b/apps/studio/state/storage-explorer.test.ts
@@ -0,0 +1,109 @@
+import { HttpResponse } from 'msw'
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { createStorageExplorerState } from './storage-explorer'
+import type { StorageObject } from '@/data/storage/bucket-objects-list-mutation'
+import type { Bucket } from '@/data/storage/buckets-query'
+import { addAPIMock } from '@/tests/lib/msw'
+
+function makeBucket(id: string): Bucket {
+ return {
+ id,
+ name: id,
+ owner: 'owner',
+ public: false,
+ type: 'STANDARD',
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ } as Bucket
+}
+
+const BUCKET_A_LISTING: StorageObject[] = [
+ {
+ id: 'file-in-bucket-a',
+ name: 'only-in-bucket-a.png',
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ last_accessed_at: '2024-01-01T00:00:00Z',
+ metadata: { size: 1, mimetype: 'image/png' },
+ },
+]
+
+/** Objects with a null id are prefixes, i.e. folders. */
+const FOLDER_LISTING: StorageObject[] = [
+ {
+ id: null,
+ name: 'shared',
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ metadata: null,
+ },
+]
+
+function createState(bucket: Bucket) {
+ return createStorageExplorerState({
+ projectRef: 'test-ref',
+ connectionString: '',
+ bucket,
+ resumableUploadUrl: '',
+ clientEndpoint: '',
+ })
+}
+
+describe('fetchFoldersByPath', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ })
+
+ it('discards a restore that resolves after the bucket changed', async () => {
+ let releaseListing: (() => void) | undefined
+ const listingReleased = new Promise<void>((resolve) => {
+ releaseListing = resolve
+ })
+
+ addAPIMock({
+ method: 'post',
+ path: '/platform/storage/:ref/buckets/:id/objects/list',
+ response: async () => {
+ await listingReleased
+ // Belongs to bucket-a, the bucket the request was issued for
+ return HttpResponse.json<StorageObject[]>(BUCKET_A_LISTING)
+ },
+ })
+
+ const state = createState(makeBucket('bucket-a'))
+ const restore = state.fetchFoldersByPath({ paths: ['shared'], showLoading: true })
+
+ // The user switches buckets while the listing is still in flight. Same `?path`, so
+ // nothing about the requested location changes — only the bucket underneath it.
+ state.selectedBucket = makeBucket('bucket-b')
+
+ releaseListing?.()
+ const { missingPaths } = await restore
+
+ // bucket-a's contents must not be committed, and must not be relabelled as bucket-b
+ const allItems = state.columns.flatMap((column) => column.items)
+ expect(allItems).toHaveLength(0)
+ expect(state.columns[0]?.name).toBe('bucket-a')
+ expect(missingPaths).toEqual([])
+ })
+
+ it('commits the restore when the bucket is unchanged', async () => {
+ addAPIMock({
+ method: 'post',
+ path: '/platform/storage/:ref/buckets/:id/objects/list',
+ response: FOLDER_LISTING,
+ })
+
+ const state = createState(makeBucket('bucket-a'))
+ const { missingPaths } = await state.fetchFoldersByPath({
+ paths: ['shared'],
+ showLoading: true,
+ })
+
+ expect(missingPaths).toEqual([])
+ expect(state.columns[0]?.items.map((item) => item.name)).toEqual(['shared'])
+ expect(state.openedFolders.map((folder) => folder.name)).toEqual(['shared'])
+ })
+})
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index 5247b77b846..4d8cb3c12b3 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -70,7 +70,7 @@ if (typeof window !== 'undefined') {
abortController = new AbortController()
}
-function createStorageExplorerState({
+export function createStorageExplorerState({
projectRef,
connectionString,
bucket,
@@ -328,7 +328,10 @@ function createStorageExplorerState({
path: prefix,
status: STORAGE_ROW_STATUS.READY,
items: formattedItems,
- hasMoreItems: formattedItems.length === LIMIT,
+ // Compare the raw page, not the formatted one: formatFolderItems drops the
+ // .emptyFolderPlaceholder, so a full page can format to LIMIT - 1 and stop
+ // pagination a page early.
+ hasMoreItems: (data ?? []).length === LIMIT,
isLoadingMoreItems: false,
},
index
@@ -409,6 +412,10 @@ function createStorageExplorerState({
}
},
+ /**
+ * Rebuilds the column stack (and `openedFolders`) from an absolute folder path,
+ * returning the segments it could not find so a URL restore can recover.
+ */
fetchFoldersByPath: async ({
paths,
searchString = '',
@@ -417,8 +424,14 @@ function createStorageExplorerState({
paths: string[]
searchString?: string
showLoading?: boolean
- }) => {
- if (state.selectedBucket.id === undefined) return
+ }): Promise<{ missingPaths: string[] }> => {
+ if (state.selectedBucket.id === undefined) return { missingPaths: [] }
+
+ // The listings below are issued against this bucket. The provider is keyed per
+ // project rather than per bucket, so a bucket switch mid-flight would otherwise
+ // commit these items under the *new* bucket's name — and because columns[0].name
+ // would then match, nothing downstream would notice and refetch.
+ const bucketIdAtStart = state.selectedBucket.id
const pathsWithEmptyPrefix = [''].concat(paths)
@@ -445,36 +458,48 @@ function createStorageExplorerState({
path: prefix,
options,
})
- return data
+ return { items: data, isComplete: true }
} catch (error: any) {
toast.error(`Failed to fetch folders: ${error.message}`)
- return []
+ // Flagged so an empty listing isn't read as "the folder has nothing in it"
+ return { items: [], isComplete: false }
}
})
)
- const formattedFolders = foldersItems.map((folderItems, idx) => {
+ const formattedFolders = foldersItems.map(({ items }, idx) => {
const prefix = paths.slice(0, idx).join('/')
- const formattedItems = formatFolderItems(folderItems, prefix)
+ const formattedItems = formatFolderItems(items, prefix)
return {
id: null,
status: STORAGE_ROW_STATUS.READY,
name: idx === 0 ? state.selectedBucket.name : pathsWithEmptyPrefix[idx],
path: prefix,
items: formattedItems,
- hasMoreItems: formattedItems.length === LIMIT,
+ // Raw page length — see fetchFolderContents. Getting this wrong here also
+ // makes isParentListingExhaustive below claim a folder is missing.
+ hasMoreItems: items.length === LIMIT,
isLoadingMoreItems: false,
}
})
+ if (state.selectedBucket.id !== bucketIdAtStart) return { missingPaths: [] }
+
// Package into columns and update this.columns
state.columns = formattedFolders
// Update openedFolders as well
+ const missingPaths: string[] = []
const updatedOpenedFolders: StorageItem[] = paths.map((path, idx) => {
- const folderInfo = find(formattedFolders[idx].items, { name: path })
+ const parentColumn = formattedFolders[idx]
+ const folderInfo = find(parentColumn.items, { name: path })
// Folder doesnt exist, FE just scaffolds a "fake" folder
if (!folderInfo) {
+ // Only report a missing segment when the parent listing proves it: a failed
+ // request, a search filter, or a LIMIT cap can all drop a folder that exists.
+ const isParentListingExhaustive =
+ foldersItems[idx].isComplete && !searchString && !parentColumn.hasMoreItems
+ if (isParentListingExhaustive) missingPaths.push(path)
return {
id: null,
name: path,
@@ -490,6 +515,8 @@ function createStorageExplorerState({
return folderInfo
})
state.openedFolders = updatedOpenedFolders
+
+ return { missingPaths }
},
/**