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

339 lines
12 KiB
TypeScript

import { QueryClient } from '@tanstack/react-query'
import { fireEvent, screen, waitFor } from '@testing-library/react'
import type { components } from 'api-types'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { http, HttpResponse } from 'msw'
import { useQueryState } from 'nuqs'
import { beforeEach, expect, test, vi } from 'vitest'
import { Destinations } from './Destinations'
import { replicationKeys } from '@/data/replication/keys'
import { createTestRouter, customRender } from '@/tests/lib/custom-render'
import { addAPIMock, mswServer, type APIErrorBody } from '@/tests/lib/msw'
mockAnimationsApi()
const options = vi.hoisted(() => ({
wizard: false,
previewLoading: false,
flagsLoaded: true,
bigQueryEnabled: true,
hasAccess: true,
isLoading: false,
failEnable: false,
failRefresh: false,
}))
vi.mock('@/lib/constants', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/constants')>()),
IS_PLATFORM: true,
}))
vi.mock('common', async (importOriginal) => ({
...(await importOriginal<typeof import('common')>()),
useParams: () => ({ ref: 'default' }),
useFeatureFlags: () => ({ hasLoaded: options.flagsLoaded }),
}))
vi.mock('@/components/interfaces/App/FeaturePreview/FeaturePreviewContext', () => ({
usePipelineCreationPreview: () => ({
isEnabled: options.wizard,
isLoading: options.previewLoading,
}),
}))
vi.mock('./useIsPipelinesEnabled', () => ({
useIsPipelinesBigQueryEnabled: () => options.bigQueryEnabled,
useIsPipelinesDuckLakeEnabled: () => false,
useIsPipelinesSnowflakeEnabled: () => false,
useIsPipelinesClickHouseEnabled: () => false,
}))
vi.mock('@/hooks/misc/useCheckEntitlements', () => ({
useCheckEntitlements: () => ({ hasAccess: options.hasAccess, isLoading: options.isLoading }),
}))
vi.mock('./DestinationPanel/DestinationPanel', () => ({
DestinationPanel: () => {
const [type] = useQueryState('destinationType')
return type ? <h2>Creation sheet: {type}</h2> : null
},
}))
let isEnabled = false
let enableGate: Promise<void> | undefined
let navigateSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
options.wizard = false
options.previewLoading = false
options.flagsLoaded = true
isEnabled = false
enableGate = undefined
options.bigQueryEnabled = true
options.hasAccess = true
options.isLoading = false
options.failRefresh = false
options.failEnable = false
mswServer.use(
http.get('http://localhost:3000/api/enabled-features-overrides', () =>
HttpResponse.json<{ disabled_features: string[] }>({ disabled_features: [] })
)
)
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: () => HttpResponse.json<APIErrorBody>({ message: 'Unavailable' }, { status: 404 }),
})
addAPIMock({
method: 'get',
path: '/platform/replication/:ref/destinations',
response: () =>
HttpResponse.json<components['schemas']['DestinationsResponse_Output']>({ destinations: [] }),
})
addAPIMock({
method: 'get',
path: '/platform/replication/:ref/pipelines',
response: () =>
HttpResponse.json<components['schemas']['PipelinesResponse_Output']>({ pipelines: [] }),
})
addAPIMock({
method: 'get',
path: '/platform/replication/:ref/sources',
response: () =>
options.failRefresh && isEnabled
? HttpResponse.json<APIErrorBody>(
{ message: 'replication API URL is not configured' },
{ status: 503 }
)
: HttpResponse.json<components['schemas']['SourcesResponse_Output']>({
sources: isEnabled
? [
{
id: 42,
name: 'default',
tenant_id: 'tenant',
config: {
host: 'localhost',
port: 5432,
name: 'postgres',
username: 'postgres',
},
},
]
: [],
}),
})
addAPIMock({
method: 'post',
path: '/platform/replication/:ref/tenants-sources',
response: async () => {
await enableGate
if (options.failEnable) {
options.failEnable = false
return HttpResponse.json<APIErrorBody>({ message: 'Unavailable' }, { status: 503 })
}
isEnabled = true
return HttpResponse.json<components['schemas']['CreateTenantSourceResponse_Output']>({
source_id: 42,
tenant_id: 'tenant',
})
},
})
})
const renderList = async (waitForSources = true) => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const router = createTestRouter('/project/default/database/pipelines')
navigateSpy = vi.spyOn(router, 'navigate')
const view = customRender(<Destinations />, { queryClient, router, nuqs: { hasMemory: true } })
await screen.findByRole('heading', { name: 'Add a pipeline' })
if (waitForSources)
await waitFor(() =>
expect(queryClient.getQueryState(replicationKeys.sources('default'))?.status).toBe('success')
)
return view
}
const addPipeline = () =>
fireEvent.click(screen.getAllByRole('button', { name: 'Add pipeline' })[0])
test.each([true, false, 'retry', 'refresh error'])(
'opens creation after enabling when needed (enabled: %s)',
async (enabled) => {
isEnabled = enabled === true
options.failEnable = enabled === 'retry'
const view = await renderList()
options.failRefresh = enabled === 'refresh error'
options.isLoading = enabled !== true
options.hasAccess = !options.isLoading
addPipeline()
if (enabled !== true) {
expect(screen.getByText('Checking Pipelines access…')).toBeInTheDocument()
expect(screen.queryByText('Pipelines requires the Pro plan.')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Enable' })).toBeDisabled()
options.isLoading = false
options.hasAccess = true
view.rerender(<Destinations />)
fireEvent.click(screen.getByRole('button', { name: 'Enable' }))
if (enabled === 'retry') {
await waitFor(() => expect(options.failEnable).toBe(false))
await waitFor(() => expect(screen.getByRole('button', { name: 'Enable' })).toBeEnabled())
expect(screen.queryByRole('heading', { name: /Creation sheet/ })).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Enable' }))
}
}
if (enabled === 'refresh error') {
await screen.findByRole('button', { name: 'Retry' })
expect(screen.queryByRole('heading', { name: /Creation sheet/ })).not.toBeInTheDocument()
options.failRefresh = false
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
await waitFor(() =>
expect(screen.getAllByRole('button', { name: 'Add pipeline' })[0]).not.toHaveAttribute(
'aria-disabled',
'true'
)
)
addPipeline()
}
await screen.findByRole('heading', { name: 'Creation sheet: BigQuery' })
}
)
test('dismissal during enablement prevents a late response opening creation', async () => {
let finish: (() => void) | undefined
enableGate = new Promise<void>((resolve) => {
finish = resolve
})
await renderList()
addPipeline()
fireEvent.click(await screen.findByRole('button', { name: 'Enable' }))
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
finish?.()
fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), {
button: 0,
ctrlKey: false,
})
expect(await screen.findByRole('menuitem', { name: 'Disable Pipelines' })).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: /Creation sheet/ })).not.toBeInTheDocument()
})
test('creation defaults to BigQuery when destination flags are disabled', async () => {
options.bigQueryEnabled = false
isEnabled = true
await renderList()
addPipeline()
await screen.findByRole('heading', { name: 'Creation sheet: BigQuery' })
})
test.each(['loading', 'error'])('blocks creation when source status is %s', async (state) => {
let finish: (() => void) | undefined
let hasFailed = false
addAPIMock({
method: 'get',
path: '/platform/replication/:ref/sources',
response: async () => {
if (state === 'loading')
await new Promise<void>((resolve) => {
finish = resolve
})
if (state === 'error' && !hasFailed) {
hasFailed = true
return HttpResponse.json<APIErrorBody>(
{ message: 'replication API URL is not configured' },
{ status: 503 }
)
}
return HttpResponse.json<components['schemas']['SourcesResponse_Output']>({ sources: [] })
},
})
await renderList(false)
if (state === 'error') {
await screen.findByRole('button', { name: 'Retry' })
const button = screen.getAllByRole('button', { name: 'Add pipeline' })[0]
expect(button).toHaveAttribute('aria-disabled', 'true')
fireEvent.focus(button)
expect(await screen.findByRole('tooltip')).toHaveTextContent('Replication unavailable locally')
} else {
expect(screen.getAllByRole('button', { name: 'Add pipeline' })[0]).toBeDisabled()
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()
}
addPipeline()
fireEvent.keyDown(document, { key: 'N', shiftKey: true })
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(screen.queryByRole('heading', { name: /Creation sheet/ })).not.toBeInTheDocument()
if (state === 'error') fireEvent.click(await screen.findByRole('button', { name: 'Retry' }))
else {
await waitFor(() => expect(finish).toBeDefined())
finish?.()
}
await waitFor(() =>
expect(screen.getAllByRole('button', { name: 'Add pipeline' })[0]).toBeEnabled()
)
addPipeline()
expect(await screen.findByRole('dialog')).toHaveTextContent('Enable Pipelines')
})
test('renders both wizard entry controls as links', async () => {
options.wizard = true
isEnabled = true
await renderList()
const links = screen.getAllByRole('link', { name: 'Add pipeline' })
expect(links).toHaveLength(2)
links.forEach((link) =>
expect(link).toHaveAttribute('href', '/project/default/database/pipelines/new')
)
fireEvent.click(links[0], { ctrlKey: true })
expect(navigateSpy).not.toHaveBeenCalled()
})
test('opens the wizard with the shortcut', async () => {
options.wizard = true
isEnabled = true
await renderList()
fireEvent.keyDown(document, { key: 'N', shiftKey: true })
expect(navigateSpy).toHaveBeenCalledWith(
expect.objectContaining({
to: '/project/$ref/database/pipelines/new',
params: { ref: 'default' },
})
)
})
test('enables Pipelines before opening the wizard', async () => {
options.wizard = true
await renderList()
addPipeline()
expect(navigateSpy).not.toHaveBeenCalled()
fireEvent.click(await screen.findByRole('button', { name: 'Enable' }))
await waitFor(() =>
expect(navigateSpy).toHaveBeenCalledWith(
expect.objectContaining({
to: '/project/$ref/database/pipelines/new',
params: { ref: 'default' },
})
)
)
})
test.each(['previewLoading', 'flagsLoaded'] as const)(
'waits for %s before choosing a creation flow',
async (gate) => {
options.previewLoading = gate === 'previewLoading'
options.flagsLoaded = gate !== 'flagsLoaded'
isEnabled = true
const view = await renderList()
expect(screen.getAllByRole('button', { name: 'Add pipeline' })[0]).toBeDisabled()
addPipeline()
fireEvent.keyDown(document, { key: 'N', shiftKey: true })
expect(navigateSpy).not.toHaveBeenCalled()
expect(screen.queryByRole('heading', { name: /Creation sheet/ })).not.toBeInTheDocument()
options.previewLoading = false
options.flagsLoaded = true
options.wizard = true
view.rerender(<Destinations />)
fireEvent.keyDown(document, { key: 'N', shiftKey: true })
expect(navigateSpy).toHaveBeenCalledWith(
expect.objectContaining({
to: '/project/$ref/database/pipelines/new',
params: { ref: 'default' },
})
)
}
)
test('keeps request-access creation in the sheet when no wizard destination is available', async () => {
options.wizard = true
options.bigQueryEnabled = false
isEnabled = true
await renderList()
addPipeline()
expect(
await screen.findByRole('heading', { name: 'Creation sheet: BigQuery' })
).toBeInTheDocument()
expect(navigateSpy).not.toHaveBeenCalled()
})