Skip to content

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

feat: update storage move UI (#50346)

Francesco Sansalvadore92fdb1d3c5df
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPicker.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPicker.tsx
new file mode 100644
index 00000000000..2520ee8638d
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPicker.tsx
@@ -0,0 +1,266 @@
+import { useQuery } from '@tanstack/react-query'
+import { useDebounce } from '@uidotdev/usehooks'
+import { ArrowLeft, Search, X } from 'lucide-react'
+import { useMemo, useState } from 'react'
+import { Button } from 'ui'
+import { Input } from 'ui-patterns/DataInputs/Input'
+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
+
+import { STORAGE_SORT_BY, STORAGE_SORT_BY_ORDER } from '../Storage.constants'
+import { MoveItemsFolderPickerBreadcrumb } from './MoveItemsFolderPickerBreadcrumb'
+import { FolderPickerRow } from './MoveItemsFolderPickerRow'
+import { filterFoldersBySearch, getDestinationLabel, toFolders } from './MoveItemsModal.utils'
+import { AlertError } from '@/components/ui/AlertError'
+import { InfiniteListDefault, LoaderForIconMenuItems } from '@/components/ui/InfiniteList'
+import { bucketFoldersQueryOptions } from '@/data/storage/bucket-folders-query'
+import { useBucketObjectsInfiniteQuery } from '@/data/storage/bucket-objects-infinite-query'
+import { onSearchInputEscape } from '@/lib/keyboard'
+
+const ROW_HEIGHT = 37
+
+interface MoveItemsFolderPickerProps {
+ projectRef: string
+ bucketId: string
+ bucketName: string
+ pathSegments: string[]
+ onChangePath: (pathSegments: string[]) => void
+}
+
+/**
+ * A file explorer scoped down to picking a destination folder
+ */
+export const MoveItemsFolderPicker = ({
+ projectRef,
+ bucketId,
+ bucketName,
+ pathSegments,
+ onChangePath,
+}: MoveItemsFolderPickerProps) => {
+ const [searchString, setSearchString] = useState('')
+ const debouncedSearchString = useDebounce(searchString, 300)
+ const isSearching = debouncedSearchString.trim().length > 0
+
+ const path = pathSegments.join('/')
+
+ const {
+ data: objectsData,
+ isPending: isPendingObjects,
+ isFetching: isFetchingObjects,
+ isError: isErrorObjects,
+ error: objectsError,
+ hasNextPage,
+ fetchNextPage,
+ refetch: refetchObjects,
+ } = useBucketObjectsInfiniteQuery({
+ projectRef,
+ bucketId,
+ path,
+ options: {
+ sortBy: { column: STORAGE_SORT_BY.NAME, order: STORAGE_SORT_BY_ORDER.ASC },
+ },
+ })
+
+ const {
+ data: foldersData,
+ isPending: isPendingFolders,
+ isError: isErrorFolders,
+ error: foldersError,
+ refetch: refetchFolders,
+ } = useQuery({
+ ...bucketFoldersQueryOptions({ projectRef, bucketId }),
+ enabled: isSearching,
+ })
+
+ const folders = useMemo(
+ () => toFolders(objectsData?.pages.flat() ?? [], path),
+ [objectsData, path]
+ )
+
+ const searchResults = useMemo(
+ () => filterFoldersBySearch(foldersData?.folders ?? [], debouncedSearchString),
+ [foldersData, debouncedSearchString]
+ )
+
+ const isRoot = pathSegments.length === 0
+ const currentFolderName = isRoot ? bucketName : pathSegments[pathSegments.length - 1]
+ // A page of pure files leaves nothing to render yet
+ const isDrainingPages = folders.length === 0 && hasNextPage
+
+ // Navigating always leaves search mode
+ const handleNavigate = (segments: string[]) => {
+ setSearchString('')
+ onChangePath(segments)
+ }
+
+ const handleSelectFolder = (folderPath: string) => handleNavigate(folderPath.split('/'))
+
+ return (
+ <div className="flex h-[360px] flex-col overflow-hidden rounded-md border border-overlay bg-studio">
+ <div className="flex shrink-0 items-center gap-x-2 border-b border-overlay bg-surface-100 px-2.5 py-2">
+ <Button
+ size="tiny"
+ variant="outline"
+ aria-label="Go up one level"
+ className="w-7 shrink-0 px-1"
+ icon={<ArrowLeft size={14} />}
+ disabled={isRoot}
+ onClick={() => handleNavigate(pathSegments.slice(0, -1))}
+ />
+ <Input
+ size="tiny"
+ className="w-52 shrink-0"
+ icon={<Search />}
+ placeholder={`Search folders in ${bucketName}...`}
+ type="text"
+ value={searchString}
+ onChange={(event) => setSearchString(event.target.value)}
+ onKeyDown={onSearchInputEscape(searchString, setSearchString)}
+ actions={
+ searchString.length > 0
+ ? [
+ <Button
+ key="clear"
+ size="tiny"
+ variant="text"
+ aria-label="Clear search"
+ icon={<X />}
+ className="h-5 w-5 p-0"
+ onClick={() => setSearchString('')}
+ />,
+ ]
+ : undefined
+ }
+ />
+ <MoveItemsFolderPickerBreadcrumb
+ bucketName={bucketName}
+ pathSegments={pathSegments}
+ onNavigate={handleNavigate}
+ />
+ </div>
+
+ <div className="flex shrink-0 items-center border-b border-default bg-surface-75 px-2.5 py-2">
+ <p className="min-w-0 truncate text-xs text-foreground-light">
+ Moving to{' '}
+ <span className="font-mono text-foreground">
+ {getDestinationLabel(bucketName, pathSegments)}
+ </span>
+ </p>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-hidden">
+ {isSearching && isPendingFolders && (
+ <div className="flex flex-col gap-y-2 p-2.5">
+ <ShimmeringLoader />
+ <ShimmeringLoader />
+ <ShimmeringLoader />
+ </div>
+ )}
+
+ {isSearching && isErrorFolders && (
+ <div className="flex h-full items-center justify-center p-2.5">
+ <AlertError
+ error={foldersError}
+ subject="Failed to search folders"
+ additionalActions={
+ <Button size="tiny" variant="outline" onClick={() => refetchFolders()}>
+ Try again
+ </Button>
+ }
+ />
+ </div>
+ )}
+
+ {isSearching && !isPendingFolders && !isErrorFolders && searchResults.length === 0 && (
+ <div className="flex h-full flex-col items-center justify-center gap-y-1 px-6">
+ <p className="text-sm text-foreground">No folders match "{debouncedSearchString}"</p>
+ <p className="text-center text-sm text-foreground-light">
+ Clear the search to browse {bucketName} instead.
+ </p>
+ </div>
+ )}
+
+ {isSearching && !isErrorFolders && searchResults.length > 0 && (
+ <InfiniteListDefault
+ className="h-full"
+ items={searchResults}
+ itemProps={{
+ selectedPath: path,
+ showLocation: true,
+ bucketName,
+ onSelectFolder: handleSelectFolder,
+ }}
+ getItemKey={(index) => searchResults[index]?.path ?? `folder-${index}`}
+ getItemSize={() => ROW_HEIGHT}
+ ItemComponent={FolderPickerRow}
+ LoaderComponent={LoaderForIconMenuItems}
+ />
+ )}
+
+ {!isSearching && isPendingObjects && (
+ <div className="flex flex-col gap-y-2 p-2.5">
+ <ShimmeringLoader />
+ <ShimmeringLoader />
+ <ShimmeringLoader />
+ </div>
+ )}
+
+ {!isSearching && isErrorObjects && (
+ <div className="flex h-full items-center justify-center p-2.5">
+ <AlertError
+ error={objectsError}
+ subject="Failed to load folder contents"
+ additionalActions={
+ <Button size="tiny" variant="outline" onClick={() => refetchObjects()}>
+ Try again
+ </Button>
+ }
+ />
+ </div>
+ )}
+
+ {!isSearching &&
+ !isPendingObjects &&
+ !isErrorObjects &&
+ folders.length === 0 &&
+ !isDrainingPages && (
+ <div className="flex h-full flex-col items-center justify-center gap-y-1 px-6">
+ <p className="text-sm text-foreground">No folders in {currentFolderName}</p>
+ <p className="text-center text-sm text-foreground-light">
+ Move the files here, or go back to choose another folder.
+ </p>
+ </div>
+ )}
+
+ {!isSearching &&
+ !isPendingObjects &&
+ !isErrorObjects &&
+ (folders.length > 0 || isDrainingPages) && (
+ <InfiniteListDefault
+ className="h-full"
+ items={folders}
+ itemProps={{
+ selectedPath: path,
+ showLocation: false,
+ bucketName,
+ onSelectFolder: handleSelectFolder,
+ }}
+ getItemKey={(index) => folders[index]?.path ?? `folder-${index}`}
+ getItemSize={() => ROW_HEIGHT}
+ ItemComponent={FolderPickerRow}
+ LoaderComponent={LoaderForIconMenuItems}
+ hasNextPage={hasNextPage}
+ isLoadingNextPage={isFetchingObjects}
+ onLoadNextPage={fetchNextPage}
+ />
+ )}
+ </div>
+
+ {isSearching && !!foldersData?.isTruncated && (
+ <p className="shrink-0 border-t border-overlay bg-surface-100 px-2.5 py-2 text-xs text-foreground-lighter">
+ {bucketName} has too many folders to search through all of them. Browse to the folder if
+ it isn't listed.
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPickerBreadcrumb.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPickerBreadcrumb.tsx
new file mode 100644
index 00000000000..47cceaa9b46
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPickerBreadcrumb.tsx
@@ -0,0 +1,98 @@
+import { Fragment } from 'react'
+import {
+ Breadcrumb,
+ BreadcrumbEllipsis,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from 'ui'
+
+import { getMoveBreadcrumbs, type MoveBreadcrumb } from './MoveItemsModal.utils'
+
+const CRUMB_CLASS = 'max-w-20 truncate text-xs md:max-w-none'
+
+interface MoveItemsFolderPickerBreadcrumbProps {
+ bucketName: string
+ pathSegments: string[]
+ onNavigate: (pathSegments: string[]) => void
+}
+
+const Crumb = ({
+ crumb,
+ onNavigate,
+}: {
+ crumb: MoveBreadcrumb
+ onNavigate: (pathSegments: string[]) => void
+}) => (
+ <BreadcrumbItem className="min-w-0">
+ {crumb.isCurrent ? (
+ <BreadcrumbPage className={CRUMB_CLASS}>{crumb.label}</BreadcrumbPage>
+ ) : (
+ <BreadcrumbLink asChild className={CRUMB_CLASS}>
+ <button type="button" tabIndex={0} onClick={() => onNavigate(crumb.pathSegments)}>
+ {crumb.label}
+ </button>
+ </BreadcrumbLink>
+ )}
+ </BreadcrumbItem>
+)
+
+/**
+ * Path to the folder being browsed. Follows the design system's responsive breadcrumb: the
+ * bucket and the deepest folders stay visible, and the folders between them collapse into a
+ * dropdown so a deeply nested path stays readable.
+ */
+export const MoveItemsFolderPickerBreadcrumb = ({
+ bucketName,
+ pathSegments,
+ onNavigate,
+}: MoveItemsFolderPickerBreadcrumbProps) => {
+ const { first, collapsed, tail } = getMoveBreadcrumbs(bucketName, pathSegments)
+
+ return (
+ <Breadcrumb className="min-w-0 flex-1 overflow-hidden">
+ <BreadcrumbList className="flex-nowrap gap-1 sm:gap-1">
+ <Crumb crumb={first} onNavigate={onNavigate} />
+
+ {collapsed.length > 0 && (
+ <>
+ <BreadcrumbSeparator className="shrink-0" />
+ <BreadcrumbItem>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className="flex items-center gap-1"
+ aria-label="Show the folders in between"
+ >
+ <BreadcrumbEllipsis className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {collapsed.map((crumb) => (
+ <DropdownMenuItem
+ key={crumb.pathSegments.join('/')}
+ onSelect={() => onNavigate(crumb.pathSegments)}
+ >
+ {crumb.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </BreadcrumbItem>
+ </>
+ )}
+
+ {tail.map((crumb) => (
+ <Fragment key={crumb.pathSegments.join('/')}>
+ <BreadcrumbSeparator className="shrink-0" />
+ <Crumb crumb={crumb} onNavigate={onNavigate} />
+ </Fragment>
+ ))}
+ </BreadcrumbList>
+ </Breadcrumb>
+ )
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPickerRow.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPickerRow.tsx
new file mode 100644
index 00000000000..b4e9c3ad3d1
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsFolderPickerRow.tsx
@@ -0,0 +1,72 @@
+import { ChevronRight } from 'lucide-react'
+import type { CSSProperties } from 'react'
+import { cn } from 'ui'
+
+import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES, STORAGE_VIEWS } from '../Storage.constants'
+import { StorageRowIcon } from '../StorageRowIcon'
+import { getParentPathLabel } from './MoveItemsModal.utils'
+import type { StorageFolder } from '@/data/storage/bucket-folders-query'
+
+interface FolderPickerRowProps {
+ item: StorageFolder
+ /** Path of the folder currently set as the move destination */
+ selectedPath: string
+ /** Shows where each folder lives — only useful for search, which spans the whole bucket */
+ showLocation: boolean
+ /** Stands in for a folder's location when it sits at the root of the bucket */
+ bucketName: string
+ onSelectFolder: (path: string) => void
+ style?: CSSProperties
+}
+
+export const FolderPickerRow = ({
+ item,
+ selectedPath,
+ showLocation,
+ bucketName,
+ onSelectFolder,
+ style,
+}: FolderPickerRowProps) => {
+ const isSelected = item.path === selectedPath
+ const location = getParentPathLabel(item.path, bucketName)
+
+ return (
+ <div style={style} className="border-b border-default">
+ <button
+ type="button"
+ tabIndex={0}
+ onClick={() => onSelectFolder(item.path)}
+ aria-label={showLocation ? `${item.name} in ${location}` : item.name}
+ aria-current={isSelected ? 'true' : undefined}
+ className={cn(
+ 'flex h-full w-full cursor-pointer items-center gap-x-2 px-2.5 text-left',
+ 'focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-[var(--ring)]',
+ isSelected
+ ? 'bg-selection'
+ : 'hover:bg-panel-footer-light in-data-[theme*=dark]:hover:bg-panel-footer-dark'
+ )}
+ >
+ <span className="flex w-[30px] shrink-0 items-center">
+ <StorageRowIcon
+ view={STORAGE_VIEWS.LIST}
+ status={STORAGE_ROW_STATUS.READY}
+ fileType={STORAGE_ROW_TYPES.FOLDER}
+ mimeType={undefined}
+ />
+ </span>
+ <span title={item.name} className="min-w-0 flex-1 truncate text-sm">
+ {item.name}
+ </span>
+ {showLocation && (
+ <span
+ title={location}
+ className="max-w-[45%] shrink-0 truncate text-xs text-foreground-lighter"
+ >
+ {location}
+ </span>
+ )}
+ <ChevronRight size={14} className="shrink-0 text-foreground-lighter" />
+ </button>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.test.tsx
new file mode 100644
index 00000000000..551719be029
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.test.tsx
@@ -0,0 +1,257 @@
+import { screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { HttpResponse } from 'msw'
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES } from '../Storage.constants'
+import type { StorageItemWithColumn } from '../Storage.types'
+import { MoveItemsModal } from './MoveItemsModal'
+import type { components } from '@/data/api'
+import { clickDropdown } from '@/tests/helpers'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+
+type StorageObject = components['schemas']['StorageObject_Output']
+
+const createFolder = (name: string): StorageObject => ({
+ id: null,
+ name,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ metadata: null,
+})
+
+const createFile = (name: string): StorageObject => ({
+ id: `id-${name}`,
+ name,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ last_accessed_at: '2024-01-01T00:00:00Z',
+ metadata: { size: 1024, mimetype: 'image/png' },
+})
+
+/** Contents of the fake bucket the picker browses, keyed by folder path */
+const BUCKET_CONTENTS: Record<string, StorageObject[]> = {
+ '': [
+ createFolder('photos'),
+ createFolder('photos-old'),
+ createFolder('invoices'),
+ createFile('avatar.png'),
+ ],
+ photos: [createFolder('2024'), createFile('beach.png')],
+ 'photos/2024': [createFolder('q1')],
+ 'photos/2024/q1': [],
+ invoices: [],
+}
+
+const mockObjectsList = () =>
+ addAPIMock({
+ method: 'post',
+ path: '/platform/storage/:ref/buckets/:id/objects/list',
+ response: async ({ request }) => {
+ const body = (await request.json()) as { path: string }
+ return HttpResponse.json(BUCKET_CONTENTS[body.path] ?? [])
+ },
+ })
+
+const selectedFile: StorageItemWithColumn = {
+ id: 'id-avatar.png',
+ name: 'avatar.png',
+ type: STORAGE_ROW_TYPES.FILE,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ isCorrupted: false,
+ columnIndex: 0,
+}
+
+const renderModal = (props: Partial<Parameters<typeof MoveItemsModal>[0]> = {}) => {
+ const onSelectMove = vi.fn()
+ const onSelectCancel = vi.fn()
+
+ customRender(
+ <MoveItemsModal
+ visible
+ projectRef="default"
+ bucketId="avatars"
+ bucketName="avatars"
+ selectedItemsToMove={[selectedFile]}
+ openedFolders={[]}
+ onSelectCancel={onSelectCancel}
+ onSelectMove={onSelectMove}
+ {...props}
+ />
+ )
+
+ return { onSelectMove, onSelectCancel }
+}
+
+describe('MoveItemsModal', () => {
+ beforeAll(() => {
+ // The picker virtualizes its rows, and jsdom reports every element as zero-sized, which
+ // would leave the list empty. Give the scroll container a viewport to render into.
+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, value: 400 })
+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { configurable: true, value: 640 })
+ })
+
+ afterAll(() => {
+ // @ts-expect-error -- restoring jsdom's own zero-size getters
+ delete HTMLElement.prototype.offsetHeight
+ // @ts-expect-error -- restoring jsdom's own zero-size getters
+ delete HTMLElement.prototype.offsetWidth
+ })
+
+ beforeEach(() => {
+ mockObjectsList()
+ })
+
+ it('names the item being moved and defaults the destination to the bucket root', async () => {
+ renderModal()
+
+ expect(await screen.findByText('Move avatar.png')).toBeInTheDocument()
+ expect(await screen.findByRole('button', { name: 'photos' })).toBeInTheDocument()
+ expect(screen.getByText('avatars', { selector: 'span.font-mono' })).toBeInTheDocument()
+ })
+
+ it('lists folders only, leaving files out entirely', async () => {
+ renderModal()
+
+ await screen.findByRole('button', { name: 'photos' })
+ expect(screen.getByRole('button', { name: 'invoices' })).toBeInTheDocument()
+ expect(screen.queryByText('avatar.png')).not.toBeInTheDocument()
+ })
+
+ it('marks the destination folder in the search results', async () => {
+ const user = userEvent.setup()
+ renderModal()
+
+ await user.click(await screen.findByRole('button', { name: 'photos' }))
+ await screen.findByRole('button', { name: 'Move to photos' })
+
+ await user.type(screen.getByPlaceholderText('Search folders in avatars...'), 'photos')
+
+ expect(await screen.findByRole('button', { name: 'photos in avatars' })).toHaveAttribute(
+ 'aria-current',
+ 'true'
+ )
+ expect(screen.getByRole('button', { name: 'photos-old in avatars' })).not.toHaveAttribute(
+ 'aria-current'
+ )
+ })
+
+ it('keeps paging until it finds folders hidden behind a page of files', async () => {
+ const files = Array.from({ length: 200 }, (_, index) => createFile(`file-${index}.png`))
+ addAPIMock({
+ method: 'post',
+ path: '/platform/storage/:ref/buckets/:id/objects/list',
+ response: async ({ request }) => {
+ const body = (await request.json()) as { options?: { offset?: number } }
+ const isFirstPage = (body.options?.offset ?? 0) === 0
+ return HttpResponse.json(isFirstPage ? files : [createFolder('buried')])
+ },
+ })
+
+ renderModal()
+
+ expect(await screen.findByRole('button', { name: 'buried' })).toBeInTheDocument()
+ })
+
+ it('collapses the middle of a deep path into a dropdown', async () => {
+ const user = userEvent.setup()
+ renderModal()
+
+ await user.click(await screen.findByRole('button', { name: 'photos' }))
+ await user.click(await screen.findByRole('button', { name: '2024' }))
+ await user.click(await screen.findByRole('button', { name: 'q1' }))
+ await screen.findByRole('button', { name: 'Move to q1' })
+
+ // The bucket and the last two folders stay visible, so only "photos" collapses
+ const breadcrumb = screen.getByRole('navigation', { name: 'breadcrumb' })
+ expect(within(breadcrumb).getByText('avatars')).toBeInTheDocument()
+ expect(within(breadcrumb).getByText('2024')).toBeInTheDocument()
+ expect(within(breadcrumb).getByText('q1')).toBeInTheDocument()
+ expect(within(breadcrumb).queryByText('photos')).not.toBeInTheDocument()
+
+ clickDropdown(within(breadcrumb).getByLabelText('Show the folders in between'))
+
+ const collapsedItem = await screen.findByRole('menuitem', { name: 'photos' })
+ await user.click(collapsedItem)
+
+ expect(await screen.findByRole('button', { name: 'Move to photos' })).toBeInTheDocument()
+ })
+
+ it('keeps a shallow path fully visible', async () => {
+ const user = userEvent.setup()
+ renderModal()
+
+ await user.click(await screen.findByRole('button', { name: 'photos' }))
+ await screen.findByRole('button', { name: 'Move to photos' })
+
+ const breadcrumb = screen.getByRole('navigation', { name: 'breadcrumb' })
+ expect(within(breadcrumb).getByText('photos')).toBeInTheDocument()
+ expect(
+ within(breadcrumb).queryByLabelText('Show the folders in between')
+ ).not.toBeInTheDocument()
+ })
+
+ it('blocks moving items into the folder they are already in', async () => {
+ renderModal()
+
+ const moveButton = await screen.findByRole('button', { name: 'Move to avatars' })
+ expect(moveButton).toBeAriaDisabled()
+ })
+
+ it('opens a folder on click and moves items into it', async () => {
+ const user = userEvent.setup()
+ const { onSelectMove } = renderModal()
+
+ await user.click(await screen.findByRole('button', { name: 'photos' }))
+
+ expect(await screen.findByRole('button', { name: '2024' })).toBeInTheDocument()
+ const moveButton = await screen.findByRole('button', { name: 'Move to photos' })
+ expect(moveButton).toBeEnabled()
+
+ await user.click(moveButton)
+ expect(onSelectMove).toHaveBeenCalledWith('photos')
+ })
+
+ it('navigates back up through the breadcrumb', async () => {
+ const user = userEvent.setup()
+ renderModal()
+
+ await user.click(await screen.findByRole('button', { name: 'photos' }))
+ await screen.findByRole('button', { name: 'Move to photos' })
+
+ const breadcrumb = screen.getByRole('navigation', { name: 'breadcrumb' })
+ await user.click(within(breadcrumb).getByRole('button', { name: 'avatars' }))
+
+ expect(await screen.findByRole('button', { name: 'Move to avatars' })).toBeInTheDocument()
+ })
+
+ it('swaps the listing for matching folders while searching', async () => {
+ const user = userEvent.setup()
+ renderModal()
+
+ await screen.findByRole('button', { name: 'photos' })
+ await user.type(screen.getByPlaceholderText('Search folders in avatars...'), '2024')
+
+ expect(await screen.findByRole('button', { name: '2024 in photos' })).toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByText('invoices')).not.toBeInTheDocument())
+ })
+
+ it('selects a searched folder as the destination', async () => {
+ const user = userEvent.setup()
+ const { onSelectMove } = renderModal()
+
+ await screen.findByRole('button', { name: 'photos' })
+ await user.type(screen.getByPlaceholderText('Search folders in avatars...'), '2024')
+
+ await user.click(await screen.findByRole('button', { name: '2024 in photos' }))
+ await user.click(await screen.findByRole('button', { name: 'Move to 2024' }))
+
+ expect(onSelectMove).toHaveBeenCalledWith('photos/2024')
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.tsx
index b634cb18f91..5998b1583e4 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.tsx
@@ -1,5 +1,4 @@
-import { noop } from 'lodash'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import {
Button,
Dialog,
@@ -10,90 +9,95 @@ import {
DialogSection,
DialogSectionSeparator,
DialogTitle,
- Input,
} from 'ui'
-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import { StorageItemWithColumn } from '../Storage.types'
+import { StorageItem, StorageItemWithColumn } from '../Storage.types'
+import { MoveItemsFolderPicker } from './MoveItemsFolderPicker'
+import {
+ getDestinationName,
+ getMoveItemsTitle,
+ getSourcePaths,
+ isSameAsSourcePath,
+} from './MoveItemsModal.utils'
+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
interface MoveItemsModalProps {
+ projectRef: string
+ bucketId: string
bucketName: string
visible: boolean
selectedItemsToMove: StorageItemWithColumn[]
+ openedFolders: readonly StorageItem[]
onSelectCancel: () => void
onSelectMove: (path: string) => void
}
-export const MoveItemsModal = ({
- bucketName = '',
- visible = false,
- selectedItemsToMove = [],
- onSelectCancel = noop,
- onSelectMove = noop,
-}: MoveItemsModalProps) => {
- const [moving, setMoving] = useState(false)
- const [newPath, setNewPath] = useState('')
-
- useEffect(() => {
- setMoving(false)
- setNewPath('')
- }, [visible])
-
- const multipleFiles = selectedItemsToMove.length > 1
-
- const title = multipleFiles
- ? `Moving ${selectedItemsToMove.length} items within ${bucketName}`
- : selectedItemsToMove.length === 1
- ? `Moving ${selectedItemsToMove[0]?.name} within ${bucketName}`
- : ``
+const MoveItemsDialogBody = ({
+ projectRef,
+ bucketId,
+ bucketName,
+ selectedItemsToMove,
+ openedFolders,
+ onSelectCancel,
+ onSelectMove,
+}: Omit<MoveItemsModalProps, 'visible'>) => {
+ const [isMoving, setIsMoving] = useState(false)
+ const [pathSegments, setPathSegments] = useState<string[]>([])
- const description = `Enter the path to where you'd like to move the file${
- multipleFiles ? 's' : ''
- } to.`
+ const destinationPath = pathSegments.join('/')
+ const destinationName = getDestinationName(bucketName, pathSegments)
+ const sourcePaths = getSourcePaths(selectedItemsToMove, openedFolders)
+ const isAlreadyInDestination = isSameAsSourcePath(sourcePaths, destinationPath)
- const onConfirmMove = (event: any) => {
- if (event) {
- event.preventDefault()
- }
- setMoving(true)
- const formattedPath = newPath[0] === '/' ? newPath.slice(1) : newPath
- onSelectMove(formattedPath)
+ const handleMove = () => {
+ setIsMoving(true)
+ onSelectMove(destinationPath)
}
return (
- <Dialog open={visible} onOpenChange={onSelectCancel}>
- <DialogContent size="medium">
- <DialogHeader>
- <DialogTitle>{title}</DialogTitle>
- <DialogDescription>{description}</DialogDescription>
- </DialogHeader>
- <DialogSectionSeparator />
- <DialogSection>
- <form>
- <FormItemLayout
- label={`Path to new directory in ${bucketName}`}
- description="Leave blank to move items to the root of the bucket"
- layout="vertical"
- isReactForm={false}
- >
- <Input
- autoFocus
- type="text"
- placeholder="e.g folder1/subfolder2"
- value={newPath}
- onChange={(event) => setNewPath(event.target.value)}
- />
- </FormItemLayout>
+ <>
+ <DialogHeader>
+ <DialogTitle>{getMoveItemsTitle(selectedItemsToMove)}</DialogTitle>
+ <DialogDescription>Select a destination folder in {bucketName}.</DialogDescription>
+ </DialogHeader>
+ <DialogSectionSeparator />
+ <DialogSection>
+ <MoveItemsFolderPicker
+ projectRef={projectRef}
+ bucketId={bucketId}
+ bucketName={bucketName}
+ pathSegments={pathSegments}
+ onChangePath={setPathSegments}
+ />
+ </DialogSection>
+ <DialogFooter className="gap-y-2">
+ <Button disabled={isMoving} onClick={onSelectCancel}>
+ Cancel
+ </Button>
+ <ButtonTooltip
+ variant="primary"
+ loading={isMoving}
+ disabled={isAlreadyInDestination}
+ onClick={handleMove}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: isAlreadyInDestination ? `Already in ${destinationName}` : undefined,
+ },
+ }}
+ >
+ {isMoving ? `Moving to ${destinationName}...` : `Move to ${destinationName}`}
+ </ButtonTooltip>
+ </DialogFooter>
+ </>
+ )
+}
- <button tabIndex={-1} className="hidden" type="submit" onClick={onConfirmMove} />
- </form>
- </DialogSection>
- <DialogFooter>
- <Button onClick={onSelectCancel}>Cancel</Button>
- <Button variant="primary" loading={moving} onClick={onConfirmMove}>
- {moving ? 'Moving files' : 'Move files'}
- </Button>
- </DialogFooter>
+export const MoveItemsModal = ({ visible, ...props }: MoveItemsModalProps) => {
+ return (
+ <Dialog open={visible} onOpenChange={props.onSelectCancel}>
+ <DialogContent size="xlarge">
+ <MoveItemsDialogBody {...props} />
</DialogContent>
</Dialog>
)
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.test.ts
new file mode 100644
index 00000000000..f0eeb0ab1b6
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.test.ts
@@ -0,0 +1,248 @@
+import { describe, expect, it } from 'vitest'
+
+import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES } from '../Storage.constants'
+import type { StorageItem, StorageItemWithColumn } from '../Storage.types'
+import {
+ BREADCRUMB_ITEMS_TO_DISPLAY,
+ filterFoldersBySearch,
+ getDestinationLabel,
+ getDestinationName,
+ getMoveBreadcrumbs,
+ getMoveItemsTitle,
+ getParentPathLabel,
+ getSourcePaths,
+ isSameAsSourcePath,
+ MAX_FOLDER_SEARCH_RESULTS,
+ toFolders,
+} from './MoveItemsModal.utils'
+
+const createItem = (name: string, type = STORAGE_ROW_TYPES.FILE): StorageItem => ({
+ id: name,
+ name,
+ type,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ isCorrupted: false,
+})
+
+const createItemWithColumn = (name: string, columnIndex: number): StorageItemWithColumn => ({
+ ...createItem(name),
+ columnIndex,
+})
+
+const createFolder = (path: string) => ({ name: path.split('/').pop()!, path })
+
+describe('getSourcePaths', () => {
+ const openedFolders = [
+ createItem('photos', STORAGE_ROW_TYPES.FOLDER),
+ createItem('2024', STORAGE_ROW_TYPES.FOLDER),
+ ]
+
+ it('returns the root for items in the first column', () => {
+ expect(getSourcePaths([createItemWithColumn('a.png', 0)], openedFolders)).toEqual([''])
+ })
+
+ it('joins the folders opened to reach the item', () => {
+ expect(getSourcePaths([createItemWithColumn('a.png', 2)], openedFolders)).toEqual([
+ 'photos/2024',
+ ])
+ })
+
+ it('deduplicates items that share a source folder', () => {
+ const items = [createItemWithColumn('a.png', 1), createItemWithColumn('b.png', 1)]
+ expect(getSourcePaths(items, openedFolders)).toEqual(['photos'])
+ })
+
+ it('returns every distinct source when items span columns', () => {
+ const items = [createItemWithColumn('a.png', 1), createItemWithColumn('b.png', 2)]
+ expect(getSourcePaths(items, openedFolders)).toEqual(['photos', 'photos/2024'])
+ })
+})
+
+describe('isSameAsSourcePath', () => {
+ it('is true when the only source folder is the destination', () => {
+ expect(isSameAsSourcePath(['photos'], 'photos')).toBe(true)
+ expect(isSameAsSourcePath([''], '')).toBe(true)
+ })
+
+ it('is false when the destination is a different folder', () => {
+ expect(isSameAsSourcePath(['photos'], 'photos/2024')).toBe(false)
+ expect(isSameAsSourcePath([''], 'photos')).toBe(false)
+ })
+
+ it('is false when items come from more than one folder', () => {
+ expect(isSameAsSourcePath(['photos', 'photos/2024'], 'photos')).toBe(false)
+ })
+})
+
+describe('getDestinationName', () => {
+ it('falls back to the bucket name at the root', () => {
+ expect(getDestinationName('avatars', [])).toBe('avatars')
+ })
+
+ it('uses the deepest folder', () => {
+ expect(getDestinationName('avatars', ['photos', '2024'])).toBe('2024')
+ })
+})
+
+describe('getDestinationLabel', () => {
+ it('prefixes the path with the bucket', () => {
+ expect(getDestinationLabel('avatars', ['photos', '2024'])).toBe('avatars/photos/2024')
+ expect(getDestinationLabel('avatars', [])).toBe('avatars')
+ })
+})
+
+describe('filterFoldersBySearch', () => {
+ const folders = [
+ createFolder('archive/photos'),
+ createFolder('photos'),
+ createFolder('photos-2024'),
+ createFolder('screenshots'),
+ createFolder('videos'),
+ ]
+
+ it('returns nothing for an empty search', () => {
+ expect(filterFoldersBySearch(folders, ' ')).toEqual([])
+ })
+
+ it('matches names case insensitively', () => {
+ expect(filterFoldersBySearch(folders, 'PHOTOS').map((folder) => folder.path)).toEqual([
+ 'archive/photos',
+ 'photos',
+ 'photos-2024',
+ ])
+ })
+
+ it('ranks exact names first, then prefixes, then substrings', () => {
+ expect(filterFoldersBySearch(folders, 'photos').map((folder) => folder.path)).toEqual([
+ 'archive/photos',
+ 'photos',
+ 'photos-2024',
+ ])
+ })
+
+ it('matches on the folder path when the name does not match', () => {
+ expect(filterFoldersBySearch(folders, 'archive').map((folder) => folder.path)).toEqual([
+ 'archive/photos',
+ ])
+ })
+
+ it('returns nothing when no folder matches', () => {
+ expect(filterFoldersBySearch(folders, 'invoices')).toEqual([])
+ })
+
+ it('caps the number of results', () => {
+ const many = Array.from({ length: MAX_FOLDER_SEARCH_RESULTS + 10 }, (_, index) =>
+ createFolder(`photos-${index}`)
+ )
+ expect(filterFoldersBySearch(many, 'photos')).toHaveLength(MAX_FOLDER_SEARCH_RESULTS)
+ })
+})
+
+describe('toFolders', () => {
+ // Objects without an id are prefixes (folders); the rest are files
+ const objects = [
+ { id: null, name: 'photos' },
+ { id: 'id-a', name: 'a.png' },
+ { id: null, name: 'videos' },
+ ] as Parameters<typeof toFolders>[0]
+
+ it('drops files and keeps folders in order', () => {
+ expect(toFolders(objects, '').map((folder) => folder.name)).toEqual(['photos', 'videos'])
+ })
+
+ it('builds paths relative to the bucket root', () => {
+ expect(toFolders(objects, '').map((folder) => folder.path)).toEqual(['photos', 'videos'])
+ })
+
+ it('prefixes paths with the parent folder', () => {
+ expect(toFolders(objects, 'archive/2024').map((folder) => folder.path)).toEqual([
+ 'archive/2024/photos',
+ 'archive/2024/videos',
+ ])
+ })
+
+ it('returns nothing for a folder of only files', () => {
+ expect(toFolders([{ id: 'id-a', name: 'a.png' }] as typeof objects, '')).toEqual([])
+ })
+})
+
+describe('getParentPathLabel', () => {
+ it('falls back to the bucket name for a top level folder', () => {
+ expect(getParentPathLabel('photos', 'avatars')).toBe('avatars')
+ })
+
+ it('joins the parent segments for a nested folder', () => {
+ expect(getParentPathLabel('archive/2024/photos', 'avatars')).toBe('archive/2024')
+ })
+})
+
+describe('getMoveBreadcrumbs', () => {
+ const labels = (crumbs: { label: string }[]) => crumbs.map((crumb) => crumb.label)
+
+ it('shows only the bucket at the root, marked as current', () => {
+ const { first, collapsed, tail } = getMoveBreadcrumbs('avatars', [])
+ expect(first).toEqual({ label: 'avatars', pathSegments: [], isCurrent: true })
+ expect(collapsed).toEqual([])
+ expect(tail).toEqual([])
+ })
+
+ it('keeps every crumb visible up to the display limit', () => {
+ const { first, collapsed, tail } = getMoveBreadcrumbs('avatars', ['a', 'b'])
+ expect(first.label).toBe('avatars')
+ expect(collapsed).toEqual([])
+ expect(labels(tail)).toEqual(['a', 'b'])
+ })
+
+ it('collapses the middle once the path exceeds the display limit', () => {
+ const { first, collapsed, tail } = getMoveBreadcrumbs('avatars', ['a', 'b', 'c'])
+ expect(first.label).toBe('avatars')
+ expect(labels(collapsed)).toEqual(['a'])
+ expect(labels(tail)).toEqual(['b', 'c'])
+ })
+
+ it('collapses everything between the bucket and the last two folders', () => {
+ const { first, collapsed, tail } = getMoveBreadcrumbs('avatars', ['a', 'b', 'c', 'd', 'e'])
+ expect(first.label).toBe('avatars')
+ expect(labels(collapsed)).toEqual(['a', 'b', 'c'])
+ expect(labels(tail)).toEqual(['d', 'e'])
+ })
+
+ it('never renders more than the display limit of visible crumbs', () => {
+ const deep = Array.from({ length: 20 }, (_, index) => `folder-${index}`)
+ const { collapsed, tail } = getMoveBreadcrumbs('avatars', deep)
+ expect(1 + tail.length).toBe(BREADCRUMB_ITEMS_TO_DISPLAY)
+ expect(collapsed).toHaveLength(deep.length - tail.length)
+ })
+
+ it('points each crumb at the path it should navigate to', () => {
+ const { first, collapsed, tail } = getMoveBreadcrumbs('avatars', ['a', 'b', 'c', 'd'])
+ expect(first.pathSegments).toEqual([])
+ expect(collapsed.map((crumb) => crumb.pathSegments)).toEqual([['a'], ['a', 'b']])
+ expect(tail.map((crumb) => crumb.pathSegments)).toEqual([
+ ['a', 'b', 'c'],
+ ['a', 'b', 'c', 'd'],
+ ])
+ })
+
+ it('marks only the deepest folder as current', () => {
+ const { first, collapsed, tail } = getMoveBreadcrumbs('avatars', ['a', 'b', 'c', 'd'])
+ expect(first.isCurrent).toBe(false)
+ expect(collapsed.some((crumb) => crumb.isCurrent)).toBe(false)
+ expect(tail.map((crumb) => crumb.isCurrent)).toEqual([false, true])
+ })
+})
+
+describe('getMoveItemsTitle', () => {
+ it('names the file when moving one item', () => {
+ expect(getMoveItemsTitle([createItemWithColumn('avatar.png', 0)])).toBe('Move avatar.png')
+ })
+
+ it('counts the items when moving several', () => {
+ const items = [createItemWithColumn('a.png', 0), createItemWithColumn('b.png', 0)]
+ expect(getMoveItemsTitle(items)).toBe('Move 2 items')
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.ts
new file mode 100644
index 00000000000..dfab83ac4d8
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/MoveItemsModal.utils.ts
@@ -0,0 +1,117 @@
+import type { StorageItem, StorageItemWithColumn } from '../Storage.types'
+import type { StorageFolder } from '@/data/storage/bucket-folders-query'
+import type { StorageObject } from '@/data/storage/bucket-objects-list-mutation'
+
+/** Maximum number of folders rendered in the search results list */
+export const MAX_FOLDER_SEARCH_RESULTS = 100
+
+/**
+ * Returns the folder each item currently lives in
+ */
+export function getSourcePaths(
+ items: StorageItemWithColumn[],
+ openedFolders: readonly StorageItem[]
+): string[] {
+ const paths = items.map((item) =>
+ openedFolders
+ .slice(0, item.columnIndex)
+ .map((folder) => folder.name)
+ .join('/')
+ )
+ return Array.from(new Set(paths))
+}
+
+/**
+ * True when every item is already in `destinationPath`, which would make the move a no-op.
+ */
+export function isSameAsSourcePath(sourcePaths: string[], destinationPath: string): boolean {
+ return sourcePaths.length === 1 && sourcePaths[0] === destinationPath
+}
+
+export function getDestinationName(bucketName: string, pathSegments: string[]): string {
+ return pathSegments.length > 0 ? pathSegments[pathSegments.length - 1] : bucketName
+}
+
+export function getDestinationLabel(bucketName: string, pathSegments: string[]): string {
+ return [bucketName, ...pathSegments].join('/')
+}
+
+/**
+ * Folders whose name matches `searchString`, ordered by how closely they match: exact name
+ * first, then names starting with the search string, then the rest. Capped at
+ * `MAX_FOLDER_SEARCH_RESULTS` so a broad search can't render thousands of rows.
+ */
+export function filterFoldersBySearch(
+ folders: StorageFolder[],
+ searchString: string
+): StorageFolder[] {
+ const query = searchString.trim().toLowerCase()
+ if (query.length === 0) return []
+
+ const scored = folders
+ .map((folder) => {
+ const name = folder.name.toLowerCase()
+ if (name === query) return { folder, score: 0 }
+ if (name.startsWith(query)) return { folder, score: 1 }
+ if (name.includes(query)) return { folder, score: 2 }
+ if (folder.path.toLowerCase().includes(query)) return { folder, score: 3 }
+ return undefined
+ })
+ .filter((match) => match !== undefined)
+
+ return scored
+ .sort((a, b) => a.score - b.score || a.folder.path.localeCompare(b.folder.path))
+ .slice(0, MAX_FOLDER_SEARCH_RESULTS)
+ .map((match) => match.folder)
+}
+
+/**
+ * Narrows a listing to the folders in it. The picker only offers folders, so files are dropped.
+ */
+export function toFolders(objects: StorageObject[], parentPath: string): StorageFolder[] {
+ return objects
+ .filter((object) => !object.id)
+ .map((object) => ({
+ name: object.name,
+ path: parentPath.length > 0 ? `${parentPath}/${object.name}` : object.name,
+ }))
+}
+
+export function getParentPathLabel(folderPath: string, bucketName: string): string {
+ const parentSegments = folderPath.split('/').slice(0, -1)
+ return parentSegments.length > 0 ? parentSegments.join('/') : bucketName
+}
+
+export const BREADCRUMB_ITEMS_TO_DISPLAY = 3
+
+export type MoveBreadcrumb = {
+ label: string
+ pathSegments: string[]
+ isCurrent: boolean
+}
+
+export function getMoveBreadcrumbs(
+ bucketName: string,
+ pathSegments: string[]
+): { first: MoveBreadcrumb; collapsed: MoveBreadcrumb[]; tail: MoveBreadcrumb[] } {
+ const crumbs: MoveBreadcrumb[] = [bucketName, ...pathSegments].map((label, index) => ({
+ label,
+ pathSegments: pathSegments.slice(0, index),
+ isCurrent: index === pathSegments.length,
+ }))
+
+ const [first, ...rest] = crumbs
+ const tailLength = BREADCRUMB_ITEMS_TO_DISPLAY - 1
+ const shouldCollapse = crumbs.length > BREADCRUMB_ITEMS_TO_DISPLAY
+
+ return {
+ first,
+ collapsed: shouldCollapse ? rest.slice(0, -tailLength) : [],
+ tail: shouldCollapse ? rest.slice(-tailLength) : rest,
+ }
+}
+
+export function getMoveItemsTitle(items: StorageItemWithColumn[]): string {
+ if (items.length === 1) return `Move ${items[0].name}`
+ return `Move ${items.length} items`
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
index e372d772d45..6bc07b56742 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx
@@ -182,9 +182,12 @@ export const StorageExplorer = () => {
<ConfirmDeleteModal />
<MoveItemsModal
- bucketName={selectedBucket.name}
visible={selectedItemsToMove.length > 0}
+ projectRef={projectRef}
+ bucketId={selectedBucket.id}
+ bucketName={selectedBucket.name}
selectedItemsToMove={selectedItemsToMove}
+ openedFolders={openedFolders}
onSelectCancel={() => setSelectedItemsToMove([])}
onSelectMove={onMoveSelectedFiles}
/>
diff --git a/apps/studio/data/storage/bucket-folders-query.ts b/apps/studio/data/storage/bucket-folders-query.ts
new file mode 100644
index 00000000000..d17a8395f09
--- /dev/null
+++ b/apps/studio/data/storage/bucket-folders-query.ts
@@ -0,0 +1,121 @@
+import { queryOptions } from '@tanstack/react-query'
+
+import { listBucketObjects } from './bucket-objects-list-mutation'
+import { storageKeys } from './keys'
+import type { ResponseError } from '@/types'
+
+/** Number of objects requested per folder listing */
+const PAGE_LIMIT = 1000
+/** Cap on how many listings the crawl issues */
+const MAX_LISTINGS = 200
+/** Cap on how many folders are collected */
+const MAX_FOLDERS = 1000
+/** How many listings are issued at a time while crawling */
+const CONCURRENCY = 5
+
+export type StorageFolder = {
+ name: string
+ path: string
+}
+
+export type BucketFoldersVariables = {
+ projectRef?: string
+ bucketId?: string
+}
+
+export type BucketFoldersData = {
+ folders: StorageFolder[]
+ /** True when the crawl hit its limits, so `folders` is only part of the bucket */
+ isTruncated: boolean
+}
+
+export type BucketFoldersError = ResponseError
+
+/** Pages through a single folder, counting each page fetched against the shared `listingsState` */
+const listFolderNames = async (
+ { projectRef, bucketId, path }: { projectRef: string; bucketId: string; path: string },
+ listingsState: { count: number },
+ signal?: AbortSignal
+): Promise<{ names: string[]; isTruncated: boolean }> => {
+ const names: string[] = []
+ let offset = 0
+
+ while (true) {
+ if (listingsState.count >= MAX_LISTINGS) {
+ return { names, isTruncated: true }
+ }
+
+ listingsState.count++
+ const objects = await listBucketObjects(
+ {
+ projectRef,
+ bucketId,
+ path,
+ options: { limit: PAGE_LIMIT, offset, sortBy: { column: 'name', order: 'asc' } },
+ },
+ signal
+ )
+
+ const page = objects ?? []
+ // Objects without an id are prefixes (folders) rather than files
+ names.push(...page.filter((object) => !object.id).map((object) => object.name))
+
+ if (page.length < PAGE_LIMIT) return { names, isTruncated: false }
+ offset += PAGE_LIMIT
+ }
+}
+
+/** Crawls a bucket breadth first for every folder, stopping early once `MAX_LISTINGS`/`MAX_FOLDERS` is hit */
+async function getBucketFolders(
+ { projectRef, bucketId }: BucketFoldersVariables,
+ signal?: AbortSignal
+): Promise<BucketFoldersData> {
+ if (!projectRef) throw new Error('projectRef is required')
+ if (!bucketId) throw new Error('bucketId is required')
+
+ const folders: StorageFolder[] = []
+ let queue = ['']
+ const listingsState = { count: 0 }
+ let isTruncated = false
+
+ while (queue.length > 0) {
+ if (listingsState.count >= MAX_LISTINGS || folders.length >= MAX_FOLDERS) {
+ isTruncated = true
+ break
+ }
+
+ const batch = queue.slice(0, CONCURRENCY)
+ queue = queue.slice(CONCURRENCY)
+
+ const results = await Promise.all(
+ batch.map(async (path) => {
+ const { names, isTruncated: isPathTruncated } = await listFolderNames(
+ { projectRef, bucketId, path },
+ listingsState,
+ signal
+ )
+ return { path, names, isTruncated: isPathTruncated }
+ })
+ )
+
+ for (const { path, names, isTruncated: isPathTruncated } of results) {
+ if (isPathTruncated) isTruncated = true
+ for (const name of names) {
+ const folderPath = path.length > 0 ? `${path}/${name}` : name
+ folders.push({ name, path: folderPath })
+ queue.push(folderPath)
+ }
+ }
+ }
+
+ return { folders: folders.slice(0, MAX_FOLDERS), isTruncated: isTruncated || queue.length > 0 }
+}
+
+export const bucketFoldersQueryOptions = ({ projectRef, bucketId }: BucketFoldersVariables) =>
+ queryOptions({
+ queryKey: storageKeys.folders(projectRef, bucketId),
+ queryFn: ({ signal }) => getBucketFolders({ projectRef, bucketId }, signal),
+ enabled: typeof projectRef !== 'undefined' && typeof bucketId !== 'undefined',
+ // The crawl is expensive, so hold onto the result for the lifetime of a picker session
+ staleTime: 60 * 1000,
+ })
diff --git a/apps/studio/data/storage/keys.ts b/apps/studio/data/storage/keys.ts
index 70d12059147..f6614f28357 100644
--- a/apps/studio/data/storage/keys.ts
+++ b/apps/studio/data/storage/keys.ts
@@ -54,6 +54,8 @@ export const storageKeys = {
...(path ? [path] : []),
...(params ? [params] : []),
] as const,
+ folders: (projectRef: string | undefined, bucketId: string | undefined) =>
+ ['projects', projectRef, 'buckets', bucketId, 'folders'] as const,
icebergNamespaces: ({ projectRef, warehouse }: { projectRef?: string; warehouse?: string }) =>
[projectRef, 'warehouse', warehouse, 'namespaces'] as const,
icebergNamespace: ({