Files
Alaister YoungandAlaister Young 0f14ef4d67 [FE-5109] (part 5) refactor(studio): migrate remaining interfaces and router events off next/router (#54057)
Part 5 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 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| **5** | **#54057 ← this PR** | **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 all remaining `apps/studio/components/interfaces/**`
directories off `next/router`, including the last production
`router.events` consumer (`QueryInsightsTable`) and the only default
`next/router` import (`DiscordCTACard`). After this PR, zero files under
`apps/studio/components/**` import `next/router` or
`next/compat/router`.

**Added:**

-
`apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx`:
verifies that pathname changes clear selected query state without
mutating destination or history search params, while same-pathname
search updates preserve selection

**Changed:**

- Replaced the sole production `router.events.on('routeChangeStart',
...)` consumer in `QueryInsightsTable.tsx` with a `pathname` effect that
clears `onCurrentSelectQuery` on pathname changes, and derived
`searchQuery` directly from `nuqs` (`urlSearch`) instead of mirroring it
in local state. Drops the legacy `setQueryStates({ search: null })` call
on leave, which ran after `history.push` on TanStack Router (targeting
the destination URL rather than the previous history entry, while
browser Back is expected to restore previous search params).
- Removed the `router: NextRouter` prop from `ReportWidgetRendererProps`
in `Reports/ReportWidget.tsx` and updated its callers (`ChartBlock`,
`ReportHeader`, `CreateReportModal`)
- Updated `LOG_ROUTES_WITH_REPLICA_SUPPORT` in
`Settings/Logs/Logs.constants.ts` from `[ref]` to `$ref` for TanStack
route patterns
- Replaced the default `import router from 'next/router'` in
`Support/DiscordCTACard.tsx` with `useNavigate`
- Replaced `useRouter` across `Account`, `Advisors`, `App`, `Auth`,
`ErrorHandling`, `Home`, `HomePageActions`, `Integrations`, `Linter`,
`LocalDropdown`, `Observability`, `Organization`, `OrganizationInvite`,
`Platform/Webhooks`, `Project`, `ProjectCreation`, `ProjectHome`,
`QueryPerformance`, `RedeemCredits`, `Settings`, `Sidebar`, `SignIn`,
`Support`, `UnifiedLogs`, and `UserDropdown`
- Updated affected tests (`Auth/Users/UserPanel`, `Home/ProjectList`,
`LocalDropdown`, `Organization/*`, `OrganizationInvite`,
`RedeemCredits`, `Settings/General/*`, `SignIn/SignInRecoveryCodeForm`,
`UnifiedLogs/*`)

**Simplified:**

- `LocalDropdown`, `UserDropdown` and `RedeemCredits` build the current
route from `location.href`, so the hash keeps its leading `#`
- `NewOrgForm` navigates to the `returnTo` path instead of an absolute
URL, which was being treated as external. It also uses a typed
`/new/$slug` navigate.
- Read search params from `useParams()` instead of `location.search`
casts (`CronJobPage`, `QueuePage`, `LogsPreviewer`,
`LinkSupportTicketPage`, `MarketplaceSidebar`, `PlanCards`,
`SignUpForm`)
- Dropped the dead `isReady`/`isRouterReady` constants and the
`navigate<AnyRouter, string>` casts where typed routes work
(`ForgotPasswordWizard`, `SignInPartner`, `ReportWidget`,
`ProjectUpgradeAlert`)
- Linter, `ReportHeader` and `LogsPreviewer` use `to: '.'` instead of a
separate pathname subscription. `CreateReportModal` builds the preserved
query params in `onSuccess` instead of a `useMemo`.
- Tests use the shared `createTestRouter` and `customRender` router.
`LocalDropdown` now tests that the hash is kept.

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

## To test

- [x] Query Insights: select a query and confirm search/filter updates
keep selection while switching projects/routes clears it; navigating to
Logs keeps Logs' query params intact and pressing Back restores Query
Insights' `?search=` param cleanly
- [x] Auth / Sign-in flows: sign in, sign up, MFA, recovery code,
forgot/reset password, and partner sign-in preserve `returnTo` and
redirect as expected
- [x] Organization & Project flows: creating an org/project, accepting
an org invite, claiming a project, redeeming credits, and
deleting/pausing/restarting a project or branch navigate cleanly
- [ ] Logs & Reports: replica selector appears on supported log routes
(`LOG_ROUTES_WITH_REPLICA_SUPPORT`), saved log queries open, and custom
reports create/navigate properly
- [ ] Sidebar, LocalDropdown, UserDropdown, Integrations
(Cron/Queues/Marketplace), Advisors/Linter, and Unified Logs navigate
cleanly

---------

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

177 lines
5.7 KiB
TypeScript

import { fireEvent, screen, waitFor } from '@testing-library/react'
import { mockAnimationsApi } from 'jsdom-testing-mocks'
import { HttpResponse } from 'msw'
import { act } from 'react'
import { toast } from 'sonner'
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { DeleteProjectModal } from './DeleteProjectModal'
import type { OrgProject } from '@/data/projects/org-projects-infinite-query'
import { createMockOrganization } from '@/tests/helpers'
import { createTestRouter, customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
mockAnimationsApi()
// Heavy child with its own queries and permission checks, unrelated to this flow
vi.mock('@/components/layouts/ProjectLayout/LogicalBackupCliInstructions', () => ({
LogicalBackupCliInstructions: () => null,
}))
const PROJECT: OrgProject = {
ref: 'abcdefghijklmnopqrst',
name: 'Project 1',
status: 'ACTIVE_HEALTHY',
cloud_provider: 'AWS',
region: 'us-east-1',
inserted_at: '2024-01-01T00:00:00Z',
integration_source: null,
is_branch: false,
databases: [],
}
const ORGANIZATION = createMockOrganization({ slug: 'org-slug', plan: { id: 'pro', name: 'Pro' } })
const mockSubscription = (planId: 'free' | 'pro') => {
addAPIMock({
method: 'get',
path: '/platform/organizations/:slug/billing/subscription',
response: {
addons: [],
billing_via_partner: false,
current_period_end: 1700000000,
current_period_start: 1700000000,
next_invoice_at: 1700000000,
payment_method_type: 'card',
plan: { id: planId, name: planId },
project_addons: [],
usage_billing_enabled: false,
},
})
}
// Records the order requests hit the API, since the ordering is the contract under test
const mockSurveyAndDelete = ({ surveyStatus }: { surveyStatus: 201 | 403 }) => {
const calls: string[] = []
// The selected-project hook fires alongside the props; the component prefers the props
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: () => HttpResponse.json<APIErrorBody>({ message: 'Not found' }, { status: 404 }),
})
addAPIMock({
method: 'post',
path: '/platform/feedback/downgrade',
response: () => {
calls.push('survey')
if (surveyStatus === 403) {
return HttpResponse.json<APIErrorBody>({ message: 'Forbidden' }, { status: 403 })
}
return HttpResponse.json<{ result: string }>({ result: 'success' }, { status: 201 })
},
})
addAPIMock({
method: 'delete',
path: '/platform/projects/:ref',
response: () => {
calls.push('delete')
return HttpResponse.json<{ id: number; name: string; ref: string }>({
id: 1,
name: PROJECT.name,
ref: PROJECT.ref,
})
},
})
return calls
}
const deleteProject = async () => {
const [reason] = await screen.findAllByRole('radio', { hidden: true })
fireEvent.click(reason)
fireEvent.change(screen.getByPlaceholderText('Type the project name in here'), {
target: { value: PROJECT.name },
})
fireEvent.click(screen.getByRole('button', { name: 'I understand, delete this project' }))
}
describe('DeleteProjectModal', () => {
beforeEach(() => {
vi.spyOn(toast, 'error')
vi.spyOn(toast, 'success')
})
test('sends the exit survey before deleting a paid project', async () => {
mockSubscription('pro')
const calls = mockSurveyAndDelete({ surveyStatus: 201 })
customRender(
<DeleteProjectModal visible onClose={vi.fn()} project={PROJECT} organization={ORGANIZATION} />
)
await deleteProject()
await waitFor(() => expect(calls).toEqual(['survey', 'delete']))
})
test('still deletes the project, without an error toast, when the survey fails', async () => {
mockSubscription('pro')
const calls = mockSurveyAndDelete({ surveyStatus: 403 })
customRender(
<DeleteProjectModal visible onClose={vi.fn()} project={PROJECT} organization={ORGANIZATION} />
)
await deleteProject()
await waitFor(() => expect(calls).toEqual(['survey', 'delete']))
expect(toast.error).not.toHaveBeenCalled()
})
test('does not redirect when the user left the deleted project before deletion finished', async () => {
mockSubscription('free')
let resolveDelete: () => void = () => {}
const deleteResponse = new Promise<void>((resolve) => {
resolveDelete = resolve
})
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: () => HttpResponse.json<APIErrorBody>({ message: 'Not found' }, { status: 404 }),
})
addAPIMock({
method: 'delete',
path: '/platform/projects/:ref',
response: async () => {
await deleteResponse
return HttpResponse.json<{ id: number; name: string; ref: string }>({
id: 1,
name: PROJECT.name,
ref: PROJECT.ref,
})
},
})
const router = createTestRouter(`/project/${PROJECT.ref}/settings/general`)
const { unmount } = customRender(
<DeleteProjectModal
visible
onClose={vi.fn()}
project={PROJECT}
organization={ORGANIZATION}
/>,
{ router }
)
fireEvent.change(await screen.findByPlaceholderText('Type the project name in here'), {
target: { value: PROJECT.name },
})
fireEvent.click(screen.getByRole('button', { name: 'I understand, delete this project' }))
// Leaving the page unmounts the modal, so its last render still saw the deleted project
unmount()
await act(() => router.navigate({ to: '/project/$ref', params: { ref: 'other-project' } }))
resolveDelete()
await waitFor(() => expect(toast.success).toHaveBeenCalled())
expect(router.state.location.pathname).toBe('/project/other-project')
})
})