Files
supabase/apps/studio/components/interfaces/Storage/FilesBuckets/DeleteBucketModal.tsx
Alaister YoungandAlaister Young d8568215ad [FE-5109] (part 4) refactor(studio): migrate database, editor, storage, and functions interfaces off next/router (#54056)
Part 4 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| **4** | **#54056 ← this PR** | **Database, Branching, Compute, Edge
Functions, Explorer, SQL Editor, Storage, Table Editor** |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Migrates the database, branching, compute, functions, explorer, SQL
editor, storage, and table editor interfaces off `next/router` and
`next/compat/router`.

**Changed:**

- Migrated the sole `next/compat/router` consumer
(`components/interfaces/Database/Replication/Destinations.tsx`) to
`useNavigate`
- Replaced `useRouter` across `BranchManagement`, `Branching`,
`Compute`, `Database` (`Backups`, `Functions`, `Replication`, `Schemas`,
`Tables`, `Triggers`), `EdgeFunctions`, `Explorer`, `Functions`,
`SQLEditor`, `Storage` (`AnalyticsBuckets`, `FilesBuckets`,
`VectorBuckets`, `StorageMenuV2`, `Storage.utils`), and
`TableGridEditor` with TanStack Router hooks (`useNavigate`,
`useLocation`, `useRoutePattern`) and `useParams` from `common`
- Updated unit and component tests across `Database/Replication`,
`Explorer`, `Functions`, and
`Storage/FilesBuckets/DeleteBucketModal.test.tsx` to use TanStack Router

**Simplified:**

- `useSnippetEditor` and `useRedirectLegacyReadReplicaDestination` read
search values from `useParams` instead of casting `location.search`
- `resolveSourceSwitch` returns `replace: boolean` instead of a
`push`/`replace` method name
- `ExplorerQueryTab` and `EdgeFunctionDetails` guard on a defined ref
instead of navigating with `ref ?? ''`
- `useFunctionsDetailShortcuts` and `StorageMenuV2` use a local `goTo`
helper for their navigation shortcuts
- Tests use the shared `createTestRouter` and `customRender` router, use
`toMatchObject` for search assertions, and drop duplicate assertions

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] SQL Editor: creating, renaming, moving, opening
templates/examples, and keyboard shortcuts navigate between snippets
cleanly
- [ ] Table Editor & Database: opening tables, schema table nodes,
triggers, functions, backups/PITR, and replication destination flows
navigate as expected
- [ ] Storage: switching between Files, Analytics, and Vector buckets
and deleting a bucket navigates cleanly
- [ ] Edge Functions & Explorer: opening function details/logs, explorer
chat/query tabs, and branch management actions navigate properly

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 14:44:59 +08:00

118 lines
4.3 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import { toast } from 'sonner'
import { getPolicyBucketNames } from '@/components/interfaces/Storage/Storage.utils'
import { hasVersioningHistory } from '@/components/interfaces/Storage/StorageVersioning.constants'
import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'
import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'
import { useDatabasePolicyDeleteMutation } from '@/data/database-policies/database-policy-delete-mutation'
import { useBucketDeleteMutation } from '@/data/storage/bucket-delete-mutation'
import { Bucket } from '@/data/storage/buckets-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { navigateToUrl } from '@/lib/navigation'
export interface DeleteBucketModalProps {
visible: boolean
bucket: Bucket
onClose: () => void
}
export const DeleteBucketModal = ({ visible, bucket, onClose }: DeleteBucketModalProps) => {
const navigate = useNavigate()
const { ref: projectRef, bucketId } = useParams()
const { data: project } = useSelectedProjectQuery()
const { data: policies } = useDatabasePoliciesQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
schemas: ['storage'],
})
const { mutateAsync: deletePolicy } = useDatabasePolicyDeleteMutation()
const { mutate: deleteBucket, isPending: isDeletingBucket } = useBucketDeleteMutation({
onSuccess: async () => {
// Close the modal and navigate away as soon as the bucket itself is deleted, so
// policy cleanup below (which can be slow) doesn't hold the loading state or block
// the success feedback.
toast.success(`Successfully deleted bucket ${bucket.id}`)
if (bucketId) {
await navigateToUrl(navigate, `/project/${projectRef}/storage/files`)
} else {
onClose()
}
if (!project) return console.error('Project is required')
// Clean up policies that target only the bucket that was deleted. Policies that also
// cover other buckets (or negate the bucket condition) are left in place.
const bucketPolicies = (policies ?? []).filter((policy) => {
if (policy.table !== 'objects') return false
const policyBuckets = getPolicyBucketNames(policy)
return policyBuckets.length === 1 && policyBuckets[0] === bucket.name
})
if (bucketPolicies.length === 0) return
try {
await Promise.all(
bucketPolicies.map((policy) =>
deletePolicy({
projectRef: project.ref,
connectionString: project.connectionString,
originalPolicy: policy,
})
)
)
} catch (error) {
toast.success(
`Successfully deleted bucket ${bucket.id}. However, there was a problem deleting the policies tied to the bucket. Please review them in the storage policies section`
)
}
},
})
const onConfirmDelete = async () => {
if (!projectRef) return console.error('Project ref is required')
if (!bucket) return console.error('No bucket is selected')
deleteBucket({ projectRef, id: bucket.id })
}
// Not gated on the feature preview: the retained data is destroyed either way, so the
// warning has to reflect the bucket rather than what the dashboard happens to be showing.
const isRetainingVersions = hasVersioningHistory(bucket)
return (
<TextConfirmModal
visible={visible}
size="medium"
variant="destructive"
title={`Delete bucket “${bucket.id}”`}
loading={isDeletingBucket}
confirmPlaceholder="Type bucket name"
confirmString={bucket.id}
confirmLabel="Delete bucket"
onCancel={onClose}
onConfirm={onConfirmDelete}
alert={{
title: 'You cannot recover this bucket once deleted',
description: 'This action cannot be undone',
}}
>
<p className="text-sm">
Your bucket <span className="font-bold text-foreground">{bucket.id}</span> and all of its
contents will be permanently deleted.
{isRetainingVersions && (
<span>
{
' That includes every archived file and every retained version, which cannot be restored afterwards.'
}
</span>
)}
</p>
</TextConfirmModal>
)
}