Files
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

155 lines
5.0 KiB
TypeScript

import { faker } from '@faker-js/faker'
import { fireEvent, screen, waitFor } from '@testing-library/dom'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { DeleteBucketModal } from './DeleteBucketModal'
import { ProjectContextProvider } from '@/components/layouts/ProjectLayout/ProjectContext'
import { Bucket } from '@/data/storage/buckets-query'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
import { routerMock } from '@/tests/lib/route-mock'
// Use the real `useParams` (backed by the router mock) instead of the global stub, so the
// modal sees the `bucketId` of the current URL.
vi.mock('common', async (importOriginal) => importOriginal<typeof import('common')>())
const bucket: Bucket = {
id: 'test',
name: 'test',
owner: faker.string.uuid(),
public: faker.datatype.boolean(),
allowed_mime_types: faker.helpers.multiple(() => faker.system.mimeType(), {
count: { min: 1, max: 5 },
}),
file_size_limit: faker.number.int({ min: 0, max: 25165824 }),
type: 'STANDARD',
created_at: faker.date.recent().toISOString(),
updated_at: faker.date.recent().toISOString(),
}
const Page = ({ onClose }: { onClose: () => void }) => {
const [open, setOpen] = useState(false)
return (
<ProjectContextProvider projectRef="default">
<button tabIndex={0} onClick={() => setOpen(true)}>
Open
</button>
<DeleteBucketModal
visible={open}
bucket={bucket}
onClose={() => {
setOpen(false)
onClose()
}}
/>
</ProjectContextProvider>
)
}
describe(`DeleteBucketModal`, () => {
beforeEach(() => {
// useParams
routerMock.setCurrentUrl(`/project/default/storage/files`)
// useProjectContext
addAPIMock({
method: `get`,
path: `/platform/projects/:ref`,
// @ts-expect-error
response: {
cloud_provider: 'localhost',
id: 1,
inserted_at: '2021-08-02T06:40:40.646Z',
name: 'Default Project',
organization_id: 1,
ref: 'default',
region: 'local',
status: 'ACTIVE_HEALTHY',
},
})
// usePaginatedBucketsQuery
addAPIMock({
method: `get`,
path: `/platform/storage/:ref/buckets`,
response: [bucket],
})
// useDatabasePoliciesQuery
addAPIMock({
method: `get`,
path: `/platform/pg-meta/:ref/policies`,
response: [
{
id: faker.number.int({ min: 1 }),
name: faker.word.noun(),
action: faker.helpers.arrayElement(['PERMISSIVE', 'RESTRICTIVE']),
command: faker.helpers.arrayElement(['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'ALL']),
table: faker.word.noun(),
table_id: faker.number.int({ min: 1 }),
check: null,
definition: null,
schema: faker.lorem.sentence(),
roles: faker.helpers.multiple(() => faker.word.noun(), {
count: { min: 1, max: 5 },
}),
},
],
})
// useBucketDeleteMutation - empty bucket
addAPIMock({
method: `post`,
path: `/platform/storage/:ref/buckets/:id/empty`,
})
// useBucketDeleteMutation - poll for empty bucket
addAPIMock({
method: `post`,
path: `/platform/storage/:ref/buckets/:id/objects/list`,
response: [], // Return empty array to indicate bucket is empty
})
// useBucketDeleteMutation - delete bucket
addAPIMock({
method: `delete`,
path: `/platform/storage/:ref/buckets/:id`,
})
})
it(`renders a confirmation dialog`, async () => {
const onClose = vi.fn()
const { router } = customRender(<Page onClose={onClose} />, {
initialUrl: `/project/default/storage/files`,
})
const openButton = screen.getByRole(`button`, { name: `Open` })
await userEvent.click(openButton)
await screen.findByRole(`dialog`)
const input = screen.getByPlaceholderText(`Type bucket name`)
await userEvent.type(input, `test`)
const confirmButton = screen.getByRole(`button`, { name: `Delete bucket` })
fireEvent.click(confirmButton)
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
expect(router.state.location.href).toStrictEqual(`/project/default/storage/files`)
})
it(`navigates from the deleted bucket's page to the buckets list`, async () => {
const bucketUrl = `/project/default/storage/files/buckets/${bucket.id}?action=delete`
routerMock.setCurrentUrl(bucketUrl)
const onClose = vi.fn()
const { router } = customRender(<Page onClose={onClose} />, { initialUrl: bucketUrl })
await userEvent.click(screen.getByRole(`button`, { name: `Open` }))
await screen.findByRole(`dialog`)
await userEvent.type(screen.getByPlaceholderText(`Type bucket name`), bucket.id)
fireEvent.click(screen.getByRole(`button`, { name: `Delete bucket` }))
await waitFor(() =>
expect(router.state.location.href).toStrictEqual(`/project/default/storage/files`)
)
expect(onClose).not.toHaveBeenCalled()
})
})