Skip to content

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

refactor: move storage utils out of valtio + write tests (#43225)

Charisb8b14f06e029
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts
new file mode 100644
index 00000000000..478f04475e4
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts
@@ -0,0 +1,277 @@
+import { toast } from 'sonner'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ STORAGE_ROW_STATUS,
+ STORAGE_ROW_TYPES,
+} from '@/components/interfaces/Storage/Storage.constants'
+import type { StorageItem } from '@/components/interfaces/Storage/Storage.types'
+import {
+ getPathAlongFoldersToIndex,
+ getPathAlongOpenedFolders,
+ sanitizeNameForDuplicateInColumn,
+ validateFolderName,
+} from '@/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils'
+
+function makeBucket(name: string) {
+ return {
+ id: name,
+ name,
+ owner: 'owner',
+ public: false,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ }
+}
+
+function makeFolder(name: string): StorageItem {
+ return {
+ id: null,
+ name,
+ type: STORAGE_ROW_TYPES.FOLDER,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ isCorrupted: false,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ }
+}
+
+describe('validateFolderName', () => {
+ describe('valid names', () => {
+ it('accepts plain alphanumeric names', () => {
+ expect(validateFolderName('myfolder')).toBeNull()
+ expect(validateFolderName('MyFolder123')).toBeNull()
+ })
+
+ it('accepts names with underscores and hyphens', () => {
+ expect(validateFolderName('my_folder')).toBeNull()
+ expect(validateFolderName('my-folder')).toBeNull()
+ })
+
+ it('accepts names with dots', () => {
+ expect(validateFolderName('my.folder')).toBeNull()
+ })
+
+ it('accepts names with spaces', () => {
+ expect(validateFolderName('my folder')).toBeNull()
+ })
+
+ it('accepts names with allowed special characters', () => {
+ expect(validateFolderName('folder!')).toBeNull()
+ expect(validateFolderName("folder'")).toBeNull()
+ expect(validateFolderName('folder(1)')).toBeNull()
+ expect(validateFolderName('folder*')).toBeNull()
+ expect(validateFolderName('folder&name')).toBeNull()
+ expect(validateFolderName('folder$name')).toBeNull()
+ expect(validateFolderName('folder@name')).toBeNull()
+ expect(validateFolderName('folder=name')).toBeNull()
+ expect(validateFolderName('folder;name')).toBeNull()
+ expect(validateFolderName('folder:name')).toBeNull()
+ expect(validateFolderName('folder+name')).toBeNull()
+ expect(validateFolderName('folder,name')).toBeNull()
+ expect(validateFolderName('folder?name')).toBeNull()
+ })
+
+ it('accepts names with forward slashes', () => {
+ expect(validateFolderName('parent/child')).toBeNull()
+ })
+
+ it('accepts an empty string', () => {
+ expect(validateFolderName('')).toBeNull()
+ })
+ })
+
+ describe('invalid names', () => {
+ it('rejects a name containing #', () => {
+ const result = validateFolderName('my#folder')
+ expect(result).toBe('Folder name cannot contain the "#" character')
+ })
+
+ it('rejects a name containing %', () => {
+ const result = validateFolderName('my%folder')
+ expect(result).toBe('Folder name cannot contain the "%" character')
+ })
+
+ it('rejects a name containing ^', () => {
+ const result = validateFolderName('my^folder')
+ expect(result).toBe('Folder name cannot contain the "^" character')
+ })
+
+ it('rejects a name containing [', () => {
+ const result = validateFolderName('my[folder')
+ expect(result).toBe('Folder name cannot contain the "[" character')
+ })
+ })
+})
+
+describe('getPathAlongOpenedFolders', () => {
+ const selectedBucket = makeBucket('my-bucket')
+
+ it('returns only the bucket name when there are no opened folders and includeBucket=true', () => {
+ expect(getPathAlongOpenedFolders({ openedFolders: [], selectedBucket })).toBe('my-bucket')
+ })
+
+ it('returns bucket/folder when one folder is open and includeBucket=true', () => {
+ expect(
+ getPathAlongOpenedFolders({ openedFolders: [makeFolder('images')], selectedBucket })
+ ).toBe('my-bucket/images')
+ })
+
+ it('returns the full path when multiple folders are open and includeBucket=true', () => {
+ const openedFolders = [makeFolder('images'), makeFolder('2024'), makeFolder('january')]
+ expect(getPathAlongOpenedFolders({ openedFolders, selectedBucket })).toBe(
+ 'my-bucket/images/2024/january'
+ )
+ })
+
+ it('returns an empty string when there are no opened folders and includeBucket=false', () => {
+ expect(getPathAlongOpenedFolders({ openedFolders: [], selectedBucket }, false)).toBe('')
+ })
+
+ it('returns the folder path without the bucket when includeBucket=false', () => {
+ const openedFolders = [makeFolder('images'), makeFolder('2024')]
+ expect(getPathAlongOpenedFolders({ openedFolders, selectedBucket }, false)).toBe('images/2024')
+ })
+})
+
+describe('getPathAlongFoldersToIndex', () => {
+ const openedFolders = [makeFolder('images'), makeFolder('2024'), makeFolder('january')]
+
+ it('returns an empty string for index 0', () => {
+ expect(getPathAlongFoldersToIndex({ openedFolders }, 0)).toBe('')
+ })
+
+ it('returns the first folder name for index 1', () => {
+ expect(getPathAlongFoldersToIndex({ openedFolders }, 1)).toBe('images')
+ })
+
+ it('returns folders joined up to (not including) the given index', () => {
+ expect(getPathAlongFoldersToIndex({ openedFolders }, 2)).toBe('images/2024')
+ expect(getPathAlongFoldersToIndex({ openedFolders }, 3)).toBe('images/2024/january')
+ })
+
+ it('returns an empty string for an empty openedFolders array', () => {
+ expect(getPathAlongFoldersToIndex({ openedFolders: [] }, 5)).toBe('')
+ })
+})
+
+vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
+
+describe('sanitizeNameForDuplicateInColumn', () => {
+ // Reset mock call counts between tests
+ beforeEach(() => vi.mocked(toast.error).mockClear())
+
+ // Build a state with one column per array of item overrides.
+ // e.g. makeState([['a.txt'], ['b.txt', 'c.txt']]) → two columns
+ function makeState(columns: Array<Array<Partial<StorageItem>>>) {
+ return {
+ columns: columns.map((columnItems, i) => ({
+ id: null,
+ name: `col-${i}`,
+ status: STORAGE_ROW_STATUS.READY,
+ items: columnItems.map((overrides) => ({
+ id: 'file-id',
+ name: 'file.txt',
+ type: STORAGE_ROW_TYPES.FILE,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ isCorrupted: false,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ ...overrides,
+ })),
+ })),
+ }
+ }
+
+ it('returns the original name when there is no conflict', () => {
+ const state = makeState([[{ name: 'other.txt' }]])
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt' })).toBe('file.txt')
+ })
+
+ it('is case-insensitive when detecting duplicates', () => {
+ const state = makeState([[{ name: 'FILE.TXT' }]])
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt' })).toBeNull()
+ expect(toast.error).toHaveBeenCalled()
+ })
+
+ it('skips items that are currently being edited', () => {
+ const state = makeState([[{ name: 'file.txt', status: STORAGE_ROW_STATUS.EDITING }]])
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt' })).toBe('file.txt')
+ })
+
+ describe('columnIndex', () => {
+ // Two-column state: col 0 has 'file.txt', col 1 has 'other.txt'
+ const state = makeState([[{ name: 'file.txt' }], [{ name: 'other.txt' }]])
+
+ it('defaults to the last column when columnIndex is omitted', () => {
+ // col 1 has 'other.txt', not 'file.txt' → no conflict
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt' })).toBe('file.txt')
+ })
+
+ it('uses the explicitly provided columnIndex', () => {
+ // col 0 has 'file.txt' → conflict
+ expect(
+ sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', columnIndex: 0 })
+ ).toBeNull()
+ expect(toast.error).toHaveBeenCalled()
+ })
+
+ it('only checks the specified column, ignoring conflicts in other columns', () => {
+ // col 1 has 'other.txt' but not 'file.txt' → no conflict at columnIndex 1
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', columnIndex: 1 })).toBe(
+ 'file.txt'
+ )
+ })
+
+ it('detects a conflict in the first column when columnIndex is 0', () => {
+ // col 0 has 'file.txt' → conflict
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'other.txt', columnIndex: 0 })).toBe(
+ 'other.txt'
+ ) // 'other.txt' is not in col 0
+ expect(
+ sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', columnIndex: 0 })
+ ).toBeNull()
+ })
+ })
+
+ describe('autofix: false (default)', () => {
+ it('shows an error toast and returns null on conflict', () => {
+ const state = makeState([[{ name: 'file.txt' }]])
+ const result = sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', autofix: false })
+ expect(result).toBeNull()
+ expect(toast.error).toHaveBeenCalledWith(
+ 'The name file.txt already exists in the current directory. Please use a different name.'
+ )
+ })
+ })
+
+ describe('autofix: true', () => {
+ it('appends (1) to a file name with no prior duplicates', () => {
+ const state = makeState([[{ name: 'file.txt' }]])
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', autofix: true })).toBe(
+ 'file (1).txt'
+ )
+ })
+
+ it('appends (2) when one auto-named duplicate already exists', () => {
+ const state = makeState([[{ name: 'file.txt' }, { name: 'file (1).txt' }]])
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', autofix: true })).toBe(
+ 'file (2).txt'
+ )
+ })
+
+ it('treats the whole name as the extension when there is no dot (existing behaviour)', () => {
+ // NOTE: the function splits on '.' and always treats the last segment as the
+ // extension, so a dotless name produces " (1).myfile" rather than "myfile (1)".
+ // This is a known quirk of the implementation — not a regression.
+ const state = makeState([[{ name: 'myfile' }]])
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'myfile', autofix: true })).toBe(
+ ' (1).myfile'
+ )
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
index bd1af77e8f1..bc8dbe73db0 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
@@ -2,8 +2,10 @@ import { toast } from 'sonner'
import { StorageObject } from 'data/storage/bucket-objects-list-mutation'
import { copyToClipboard } from 'ui'
+import { inverseValidObjectKeyRegex, validObjectKeyRegex } from '../CreateBucketModal.utils'
import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES } from '../Storage.constants'
import { StorageItem, StorageItemMetadata } from '../Storage.types'
+import type { StorageExplorerState } from '@/state/storage-explorer'
type UploadProgress = {
percentage: number
@@ -16,6 +18,105 @@ type UploadProgress = {
const CORRUPTED_THRESHOLD_MS = 15 * 60 * 1000 // 15 minutes
export const EMPTY_FOLDER_PLACEHOLDER_FILE_NAME = '.emptyFolderPlaceholder'
+/**
+ * Returns the path to the current folder, optionally prefixed with the bucket name.
+ */
+export function getPathAlongOpenedFolders(
+ state: Pick<StorageExplorerState, 'openedFolders' | 'selectedBucket'>,
+ includeBucket = true
+): string {
+ if (includeBucket) {
+ return state.openedFolders.length > 0
+ ? `${state.selectedBucket.name}/${state.openedFolders.map((folder) => folder.name).join('/')}`
+ : state.selectedBucket.name
+ }
+ return state.openedFolders.map((folder) => folder.name).join('/')
+}
+
+/**
+ * Returns the path to the folder at the given index in the openedFolders array,
+ * joining all folders from the root up to (but not including) the given index.
+ */
+export function getPathAlongFoldersToIndex(
+ state: Pick<StorageExplorerState, 'openedFolders'>,
+ index: number
+): string {
+ return state.openedFolders
+ .slice(0, index)
+ .map((folder) => folder.name)
+ .join('/')
+}
+
+/**
+ * Returns an error message string if the folder name contains invalid characters,
+ * or null if the name is valid.
+ */
+export function validateFolderName(name: string): string | null {
+ if (!validObjectKeyRegex.test(name)) {
+ const [match] = name.match(inverseValidObjectKeyRegex) ?? []
+ return !!match
+ ? `Folder name cannot contain the "${match}" character`
+ : 'Folder name contains an invalid special character'
+ }
+ return null
+}
+
+/**
+ * Checks whether `name` already exists in the column (case-insensitive).
+ * - When `autofix` is false and a duplicate is found, shows an error toast and returns null.
+ * - When `autofix` is true and a duplicate is found, appends a numeric suffix and returns the new name.
+ * - Returns the original name when there is no conflict.
+ *
+ * When `columnIndex` is omitted it defaults to the last column.
+ */
+export function sanitizeNameForDuplicateInColumn(
+ state: Pick<StorageExplorerState, 'columns'>,
+ {
+ name,
+ columnIndex,
+ autofix = false,
+ }: {
+ name: string
+ columnIndex?: number
+ autofix?: boolean
+ }
+): string | null {
+ const columnIndex_ = columnIndex !== undefined ? columnIndex : state.columns.length - 1
+ const currentColumn = state.columns[columnIndex_]
+ const currentColumnItems = currentColumn.items.filter(
+ (item) => item.status !== STORAGE_ROW_STATUS.EDITING
+ )
+ // [Joshen] JFYI storage does support folders of the same name with different casing
+ // but its an issue with the List V1 endpoint that's causing an issue with fetching contents
+ // for folders of the same name with different casing
+ // We should remove this check once all projects are on the List V2 endpoint
+ const hasSameNameInColumn =
+ currentColumnItems.filter((item) => item.name.toLowerCase() === name.toLowerCase()).length > 0
+
+ if (hasSameNameInColumn) {
+ if (autofix) {
+ const fileNameSegments = name.split('.')
+ const fileName = fileNameSegments.slice(0, fileNameSegments.length - 1).join('.')
+ const fileExt = fileNameSegments[fileNameSegments.length - 1]
+
+ const dupeNameRegex = new RegExp(`${fileName} \\([-0-9]+\\)${fileExt ? '.' + fileExt : ''}$`)
+ const itemsWithSameNameInColumn = currentColumnItems.filter((item) =>
+ item.name.match(dupeNameRegex)
+ )
+
+ const updatedFileName = fileName + ` (${itemsWithSameNameInColumn.length + 1})`
+ return fileExt ? `${updatedFileName}.${fileExt}` : updatedFileName
+ } else {
+ toast.error(
+ `The name ${name} already exists in the current directory. Please use a different name.`
+ )
+ return null
+ }
+ }
+
+ return name
+}
+
export const copyPathToFolder = (
openedFolders: StorageItem[],
item: StorageItem & { columnIndex: number }
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/useCopyUrl.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/useCopyUrl.tsx
index 44a9f3b8125..ed94cfbddcc 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/useCopyUrl.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/useCopyUrl.tsx
@@ -6,11 +6,11 @@ import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import { copyToClipboard } from 'ui'
import { URL_EXPIRY_DURATION } from '../Storage.constants'
+import { getPathAlongOpenedFolders } from './StorageExplorer.utils'
import { fetchFileUrl } from './useFetchFileUrlQuery'
export const useCopyUrl = () => {
- const { projectRef, selectedBucket, getPathAlongOpenedFolders } =
- useStorageExplorerStateSnapshot()
+ const { projectRef, selectedBucket, openedFolders } = useStorageExplorerStateSnapshot()
const { data: customDomainData } = useCustomDomainsQuery({ projectRef: projectRef })
const { data: settings } = useProjectSettingsV2Query({ projectRef: projectRef })
@@ -20,7 +20,7 @@ export const useCopyUrl = () => {
const getFileUrl = useCallback(
(fileName: string, expiresIn?: URL_EXPIRY_DURATION) => {
- const pathToFile = getPathAlongOpenedFolders(false)
+ const pathToFile = getPathAlongOpenedFolders({ openedFolders, selectedBucket }, false)
const formattedPathToFile = [pathToFile, fileName].join('/')
return fetchFileUrl(
@@ -31,7 +31,7 @@ export const useCopyUrl = () => {
expiresIn
)
},
- [projectRef, selectedBucket.id, selectedBucket.public, getPathAlongOpenedFolders]
+ [projectRef, selectedBucket, openedFolders]
)
const onCopyUrl = useCallback(
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
index 74579a90e62..289303c4b95 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery.tsx
@@ -5,6 +5,7 @@ import { Bucket } from 'data/storage/buckets-query'
import { useStorageExplorerStateSnapshot } from 'state/storage-explorer'
import type { ResponseError, UseCustomQueryOptions } from 'types'
import { StorageItem } from '../Storage.types'
+import { getPathAlongOpenedFolders } from './StorageExplorer.utils'
const DEFAULT_EXPIRY = 7 * 24 * 60 * 60 // in seconds, default to 1 week
@@ -43,8 +44,8 @@ export const useFetchFileUrlQuery = (
{ file, projectRef, bucket }: UseFileUrlQueryVariables,
{ ...options }: UseCustomQueryOptions<string, ResponseError> = {}
) => {
- const { getPathAlongOpenedFolders } = useStorageExplorerStateSnapshot()
- const pathToFile = getPathAlongOpenedFolders(false)
+ const { openedFolders, selectedBucket } = useStorageExplorerStateSnapshot()
+ const pathToFile = getPathAlongOpenedFolders({ openedFolders, selectedBucket }, false)
const formattedPathToFile = [pathToFile, file?.name].join('/')
return useQuery<string, ResponseError, string>({
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index fa1a9590e69..e4fcede7007 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -8,10 +8,6 @@ import * as tus from 'tus-js-client'
import { Button, SONNER_DEFAULT_DURATION, SonnerProgress } from 'ui'
import { proxy, useSnapshot } from 'valtio'
-import {
- inverseValidObjectKeyRegex,
- validObjectKeyRegex,
-} from '@/components/interfaces/Storage/CreateBucketModal.utils'
import {
STORAGE_BUCKET_SORT,
STORAGE_ROW_STATUS,
@@ -32,6 +28,10 @@ import {
formatFolderItems,
formatTime,
getFilesDataTransferItems,
+ getPathAlongFoldersToIndex,
+ getPathAlongOpenedFolders,
+ sanitizeNameForDuplicateInColumn,
+ validateFolderName,
} from '@/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils'
import { convertFromBytes } from '@/components/interfaces/Storage/StorageSettings/StorageSettings.utils'
import { InlineLink } from '@/components/ui/InlineLink'
@@ -73,7 +73,7 @@ const DEFAULT_PREFERENCES = {
}
const STORAGE_PROGRESS_INFO_TEXT = "Do not close the browser until it's completed"
-let abortController: any
+let abortController: AbortController
if (typeof window !== 'undefined') {
abortController = new AbortController()
}
@@ -100,7 +100,6 @@ function createStorageExplorerState({
resumableUploadUrl,
uploadProgresses: [] as UploadProgress[],
- // abortController,
abortApiCalls: () => {
if (abortController) {
abortController.abort()
@@ -133,7 +132,6 @@ function createStorageExplorerState({
popOpenedFolders: () => {
state.openedFolders = state.openedFolders.slice(0, state.openedFolders.length - 1)
},
-
popOpenedFoldersAtIndex: (index: number) => {
state.openedFolders = state.openedFolders.slice(0, index + 1)
},
@@ -241,33 +239,6 @@ function createStorageExplorerState({
// ======== Folders CRUD ========
- getPathAlongOpenedFolders: (includeBucket = true) => {
- if (includeBucket) {
- return state.openedFolders.length > 0
- ? `${state.selectedBucket.name}/${state.openedFolders.map((folder) => folder.name).join('/')}`
- : state.selectedBucket.name
- }
- return state.openedFolders.map((folder) => folder.name).join('/')
- },
-
- getPathAlongFoldersToIndex: (index: number) => {
- return state.openedFolders
- .slice(0, index)
- .map((folder) => folder.name)
- .join('/')
- },
-
- validateFolderName: (name: string) => {
- if (!validObjectKeyRegex.test(name)) {
- const [match] = name.match(inverseValidObjectKeyRegex) ?? []
- return !!match
- ? `Folder name cannot contain the "${match}" character`
- : 'Folder name contains an invalid special character'
- }
-
- return null
- },
-
addNewFolderPlaceholder: (columnIndex: number) => {
const isPrepend = true
const folderName = 'Untitled folder'
@@ -293,7 +264,7 @@ function createStorageExplorerState({
onError?: () => void
}) => {
const autofix = false
- const formattedName = state.sanitizeNameForDuplicateInColumn({
+ const formattedName = sanitizeNameForDuplicateInColumn(state, {
name: folderName,
autofix,
columnIndex,
@@ -308,7 +279,7 @@ function createStorageExplorerState({
return state.removeTempRows(columnIndex)
}
- const folderNameError = state.validateFolderName(formattedName)
+ const folderNameError = validateFolderName(formattedName)
if (folderNameError) {
onError?.()
return toast.error(folderNameError)
@@ -640,7 +611,7 @@ function createStorageExplorerState({
})
}
- const folderNameError = state.validateFolderName(newName)
+ const folderNameError = validateFolderName(newName)
if (folderNameError) {
onError?.()
return toast.error(folderNameError)
@@ -1103,7 +1074,7 @@ function createStorageExplorerState({
const path = file.path.split('/')
const topLevelFolder = path.length > 1 ? path[0] : null
if (topLevelFolders.includes(topLevelFolder as string)) {
- const newTopLevelFolder = state.sanitizeNameForDuplicateInColumn({
+ const newTopLevelFolder = sanitizeNameForDuplicateInColumn(state, {
name: topLevelFolder as string,
autofix,
columnIndex,
@@ -1144,7 +1115,7 @@ function createStorageExplorerState({
const isWithinFolder = (file?.path ?? '').split('/').length > 1
const fileName = !isWithinFolder
- ? state.sanitizeNameForDuplicateInColumn({ name: file.name, autofix })
+ ? sanitizeNameForDuplicateInColumn(state, { name: file.name, autofix })
: file.name
const unsanitizedFormattedFileName =
has(file, ['path']) && isWithinFolder ? file.path : fileName
@@ -1707,7 +1678,7 @@ function createStorageExplorerState({
columnIndex,
updatedName: newName,
})
- const pathToFile = state.getPathAlongFoldersToIndex(columnIndex)
+ const pathToFile = getPathAlongFoldersToIndex(state, columnIndex)
const fromPath = pathToFile.length > 0 ? `${pathToFile}/${originalName}` : originalName
const toPath = pathToFile.length > 0 ? `${pathToFile}/${newName}` : newName
@@ -1777,54 +1748,6 @@ function createStorageExplorerState({
}
},
- sanitizeNameForDuplicateInColumn: ({
- name,
- columnIndex,
- autofix = false,
- }: {
- name: string
- columnIndex?: number
- autofix?: boolean
- }) => {
- const columnIndex_ = columnIndex !== undefined ? columnIndex : state.getLatestColumnIndex()
- const currentColumn = state.columns[columnIndex_]
- const currentColumnItems = currentColumn.items.filter(
- (item) => item.status !== STORAGE_ROW_STATUS.EDITING
- )
- // [Joshen] JFYI storage does support folders of the same name with different casing
- // but its an issue with the List V1 endpoint that's causing an issue with fetching contents
- // for folders of the same name with different casing
- // We should remove this check once all projects are on the List V2 endpoint
- const hasSameNameInColumn =
- currentColumnItems.filter((item) => item.name.toLowerCase() === name.toLowerCase()).length >
- 0
-
- if (hasSameNameInColumn) {
- if (autofix) {
- const fileNameSegments = name.split('.')
- const fileName = fileNameSegments.slice(0, fileNameSegments.length - 1).join('.')
- const fileExt = fileNameSegments[fileNameSegments.length - 1]
-
- const dupeNameRegex = new RegExp(
- `${fileName} \\([-0-9]+\\)${fileExt ? '.' + fileExt : ''}$`
- )
- const itemsWithSameNameInColumn = currentColumnItems.filter((item) =>
- item.name.match(dupeNameRegex)
- )
-
- const updatedFileName = fileName + ` (${itemsWithSameNameInColumn.length + 1})`
- return fileExt ? `${updatedFileName}.${fileExt}` : updatedFileName
- } else {
- toast.error(
- `The name ${name} already exists in the current directory. Please use a different name.`
- )
- return null
- }
- }
-
- return name
- },
-
addTempRow: ({
type,
name,
@@ -1927,7 +1850,7 @@ function createStorageExplorerState({
return state
}
-type StorageExplorerState = ReturnType<typeof createStorageExplorerState>
+export type StorageExplorerState = ReturnType<typeof createStorageExplorerState>
const DEFAULT_STATE_CONFIG = {
projectRef: '',