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

337 lines
10 KiB
TypeScript

import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PlanUpdateSidePanel } from './PlanUpdateSidePanel'
import { MANAGED_BY } from '@/lib/constants/infrastructure'
import { createMockOrganization } from '@/tests/helpers'
import { customRender } from '@/tests/lib/custom-render'
const mockSelectedOrganization = vi.hoisted(() => vi.fn())
const mockPartnerManagedResource = vi.hoisted(() => vi.fn())
const mockTrack = vi.hoisted(() => vi.fn())
const mockSubscriptionPlan = vi.hoisted(() => ({ id: 'free', name: 'Free' }))
vi.mock('common', async (importOriginal) => {
const original = (await importOriginal()) as typeof import('common')
return {
...original,
useParams: () => ({ slug: 'stripe-org' }),
}
})
const render = (ui: React.ReactElement) =>
customRender(ui, { nuqs: { searchParams: '?panel=subscriptionPlan' } })
vi.mock('shared-data/plans', () => ({
plans: [
{
id: 'tier_free',
planId: 'free',
name: 'Free',
costUnit: '/ month',
features: ['Unlimited API requests'],
description: 'Perfect for passion projects & simple websites.',
preface: 'Get started with:',
footer: 'Free projects are paused after 1 week of inactivity. Limit of 2 active projects.',
},
{
id: 'tier_pro',
planId: 'pro',
name: 'Pro',
nameBadge: 'Most Popular',
costUnit: '/ month',
features: ['Email support'],
description: 'For production applications with the power to scale.',
preface: 'Everything in the Free Plan, plus:',
},
],
}))
vi.mock('@/hooks/misc/useSelectedOrganization', () => ({
useSelectedOrganizationQuery: () => ({ data: mockSelectedOrganization() }),
}))
vi.mock('@/lib/telemetry/track', () => ({
useTrack: () => mockTrack,
}))
vi.mock('@/hooks/misc/useCheckPermissionsV2', async (importOriginal) => ({
...(await importOriginal<typeof import('@/hooks/misc/useCheckPermissionsV2')>()),
useAsyncCheckPermissionsV2: () => ({ can: true }),
}))
vi.mock('@/data/projects/org-projects-infinite-query', () => ({
useOrgProjectsInfiniteQuery: () => ({ data: undefined }),
}))
vi.mock('@/data/organizations/free-project-limit-check-query', () => ({
useFreeProjectLimitCheckQuery: () => ({ data: [] }),
}))
vi.mock('@/data/organizations/organization-query', () => ({
useOrganizationQuery: () => ({ data: { has_oriole_project: false } }),
}))
vi.mock('@/data/subscriptions/org-subscription-query', () => ({
useOrgSubscriptionQuery: () => ({
data: { plan: { ...mockSubscriptionPlan }, billing_via_partner: false },
isSuccess: true,
}),
}))
vi.mock('@/data/subscriptions/org-plans-query', () => ({
useOrgPlansQuery: () => ({
data: {
plans: [
{ id: 'free', price: 0 },
{ id: 'pro', price: 25 },
],
},
isPending: false,
}),
}))
vi.mock('@/data/organizations/organization-billing-subscription-preview', () => ({
useOrganizationBillingSubscriptionPreview: () => ({}),
}))
vi.mock('@/components/ui/PartnerManagedResource', () => ({
default: (props: any) => {
mockPartnerManagedResource(props)
return <div data-testid="partner-managed-resource">{props.details}</div>
},
}))
vi.mock('./EnterpriseCard', () => ({
EnterpriseCard: () => <div>Enterprise</div>,
}))
vi.mock('./DowngradeModal', () => ({
DowngradeModal: () => null,
}))
vi.mock('./ExitSurveyModal', () => ({
ExitSurveyModal: () => null,
}))
vi.mock('./UpgradeModal', () => ({
default: () => null,
}))
vi.mock('./MembersExceedLimitModal', () => ({
MembersExceedLimitModal: () => null,
}))
vi.mock('./SubscriptionPlanUpdateView', () => ({
SubscriptionPlanUpdateView: ({
onSuccess,
}: {
onSuccess: (result: { changeType: 'upgrade' }) => void
}) => (
<div data-testid="plan-update-view">
<button tabIndex={0} onClick={() => onSuccess({ changeType: 'upgrade' })}>
Complete upgrade
</button>
</div>
),
}))
vi.mock('./PlanUpgradeSuccessView', () => ({
PlanUpgradeSuccessView: ({
planId,
previousPlanId,
}: {
planId: string
previousPlanId?: string
}) => (
<div data-testid="plan-upgrade-success">
{previousPlanId} to {planId}
</div>
),
}))
describe('PlanUpdateSidePanel', () => {
beforeEach(() => {
mockTrack.mockClear()
Object.assign(mockSubscriptionPlan, { id: 'free', name: 'Free' })
mockSelectedOrganization.mockReturnValue(
createMockOrganization({
slug: 'stripe-org',
billing_partner: null,
integration_source: 'stripe_projects',
managed_by: MANAGED_BY.STRIPE_PROJECTS,
})
)
})
it('shows Stripe-managed messaging without treating Stripe orgs as partner-billed', () => {
render(<PlanUpdateSidePanel />)
expect(screen.getByTestId('partner-managed-resource')).toBeInTheDocument()
expect(screen.getByText('stripe projects upgrade supabase/free')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Upgrade to Pro' })).toBeInTheDocument()
})
it('uses the current plan in the Stripe Projects upgrade command', () => {
mockSelectedOrganization.mockReturnValue(
createMockOrganization({
slug: 'stripe-org',
billing_partner: null,
integration_source: 'stripe_projects',
managed_by: MANAGED_BY.STRIPE_PROJECTS,
plan: { id: 'pro', name: 'Pro' },
})
)
render(<PlanUpdateSidePanel />)
expect(screen.getByText('stripe projects upgrade supabase/pro')).toBeInTheDocument()
})
it('uses the Stripe Projects downgrade command for team plans', () => {
mockSelectedOrganization.mockReturnValue(
createMockOrganization({
slug: 'stripe-org',
billing_partner: null,
integration_source: 'stripe_projects',
managed_by: MANAGED_BY.STRIPE_PROJECTS,
plan: { id: 'team', name: 'Team' },
})
)
render(<PlanUpdateSidePanel />)
expect(screen.getByText('stripe projects downgrade supabase/team')).toBeInTheDocument()
})
it('still shows partner-managed messaging for billing-partner orgs', () => {
mockSelectedOrganization.mockReturnValue(
createMockOrganization({
slug: 'aws-org',
billing_partner: 'aws_marketplace',
managed_by: MANAGED_BY.AWS_MARKETPLACE,
})
)
render(<PlanUpdateSidePanel />)
expect(screen.getByTestId('partner-managed-resource')).toBeInTheDocument()
})
describe('plan presentation', () => {
beforeEach(() => {
mockSelectedOrganization.mockReturnValue(
createMockOrganization({ slug: 'test-org', billing_partner: null })
)
})
it('renders the full-screen shell', () => {
render(<PlanUpdateSidePanel />)
expect(screen.getByRole('button', { name: /Back/ })).toBeInTheDocument()
expect(screen.getByRole('link', { name: /Compare plans/ })).toBeInTheDocument()
})
it('renders pricing-page style cards with description and preface', () => {
render(<PlanUpdateSidePanel />)
expect(
screen.getByText('Perfect for passion projects & simple websites.')
).toBeInTheDocument()
expect(screen.getByText('Everything in the Free Plan, plus:')).toBeInTheDocument()
})
it('offers AWS Marketplace as a separate purchasing route', () => {
render(<PlanUpdateSidePanel />)
expect(screen.getByText('Prefer purchasing through AWS Marketplace?')).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'View options' })).toHaveAttribute(
'href',
'https://supabase.com/aws-marketplace'
)
})
it('does not offer AWS Marketplace for partner-billed organizations', () => {
mockSelectedOrganization.mockReturnValue(
createMockOrganization({
slug: 'aws-org',
billing_partner: 'aws_marketplace',
managed_by: MANAGED_BY.AWS_MARKETPLACE,
})
)
render(<PlanUpdateSidePanel />)
expect(
screen.queryByText('Prefer purchasing through AWS Marketplace?')
).not.toBeInTheDocument()
})
it('does not render gap rows', () => {
render(<PlanUpdateSidePanel />)
expect(screen.queryByText('Not included')).not.toBeInTheDocument()
expect(screen.queryByText('Plan limits')).not.toBeInTheDocument()
})
})
it('sends the panel opened event once, after the organization has loaded', () => {
mockSelectedOrganization.mockReturnValue(undefined)
const { rerender } = render(<PlanUpdateSidePanel />)
expect(mockTrack).not.toHaveBeenCalled()
mockSelectedOrganization.mockReturnValue(
createMockOrganization({ slug: 'test-org', billing_partner: null })
)
rerender(<PlanUpdateSidePanel />)
rerender(<PlanUpdateSidePanel />)
expect(mockTrack).toHaveBeenCalledTimes(1)
expect(mockTrack).toHaveBeenCalledWith('studio_pricing_side_panel_opened', {
currentPlan: 'Free',
})
})
describe('plan change surface', () => {
beforeEach(() => {
mockSelectedOrganization.mockReturnValue(
createMockOrganization({ slug: 'test-org', billing_partner: null })
)
})
const selectPro = async () => {
render(<PlanUpdateSidePanel />)
await userEvent.click(screen.getByRole('button', { name: 'Upgrade to Pro' }))
}
it('shows the full-screen plan update view', async () => {
await selectPro()
expect(screen.getByTestId('plan-update-view')).toBeInTheDocument()
})
it('remembers the plan from before the upgrade after the subscription refetches', async () => {
const { rerender } = render(<PlanUpdateSidePanel />)
await userEvent.click(screen.getByRole('button', { name: 'Upgrade to Pro' }))
// The upgrade refetches the subscription before the success screen opens.
Object.assign(mockSubscriptionPlan, { id: 'pro', name: 'Pro' })
rerender(<PlanUpdateSidePanel />)
await userEvent.click(screen.getByRole('button', { name: 'Complete upgrade' }))
expect(await screen.findByTestId('plan-upgrade-success')).toHaveTextContent('free to pro')
})
it('reads the previous plan from the URL when the success screen loads fresh', async () => {
Object.assign(mockSubscriptionPlan, { id: 'team', name: 'Team' })
customRender(<PlanUpdateSidePanel />, {
nuqs: { searchParams: '?panel=planUpgraded&upgradedFrom=free' },
})
expect(await screen.findByTestId('plan-upgrade-success')).toHaveTextContent('free to team')
})
})
})