Files
supabase/apps/studio/components/interfaces/Auth/Users/UserPanel.platform.test.tsx
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

229 lines
9.1 KiB
TypeScript

import { QueryClient } from '@tanstack/react-query'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { platformComponents } from 'api-types'
import { FeatureFlagContext, LOCAL_STORAGE_KEYS } from 'common'
import { HttpResponse } from 'msw'
import routerMock from 'next-router-mock'
import { createDynamicRouteParser } from 'next-router-mock/dynamic-routes'
import { ResizablePanelGroup } from 'ui'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { UserPanel } from './UserPanel'
import { FeaturePreviewContextProvider } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import type { User } from '@/data/auth/users-infinite-query'
import { miscKeys } from '@/data/misc/keys'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
import { mockPermissions } from '@/tests/lib/msw-permissions'
import { NO_PERMISSIONS } from '@/tests/lib/permissions-fixtures'
import { createMockProfile, createMockProfileContext } from '@/tests/lib/profile-helpers'
const mockUser: User = {
id: '11111111-1111-1111-1111-111111111111',
email: 'user@example.com',
providers: ['email'],
created_at: '2026-01-01T12:00:00Z',
raw_user_meta_data: { locale: 'en', preferences: { theme: 'dark' } },
raw_app_meta_data: { providers: ['email'] },
}
vi.unmock('common')
const removeRouteParser = routerMock.useParser(
createDynamicRouteParser(['/project/[ref]/auth/users'])
)
afterAll(removeRouteParser)
vi.mock('./UserLogs', () => ({
UserLogs: () => <div data-testid="user-logs" />,
}))
const renderPanel = (
disabledFeatures: string[] = [],
{ otel = false, unifiedLogs = false }: { otel?: boolean | null; unifiedLogs?: boolean } = {}
) => {
localStorage.setItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS, JSON.stringify(unifiedLogs))
mockPermissions(NO_PERMISSIONS)
addAPIMock({
method: 'get',
path: '/platform/auth/:ref/config',
response: () => HttpResponse.json<APIErrorBody>({ message: 'Unavailable' }, { status: 403 }),
})
addAPIMock({
method: 'get',
path: '/platform/projects/:ref',
response: {
cloud_provider: 'AWS',
db_host: 'db.default.supabase.co',
high_availability: false,
id: 1,
inserted_at: '2026-01-01T00:00:00Z',
integration_source: null,
is_branch_enabled: false,
is_physical_backups_enabled: false,
name: 'Test project',
organization_id: 1,
ref: 'default',
region: 'us-east-1',
restUrl: 'https://default.supabase.co',
status: 'ACTIVE_HEALTHY',
subscription_id: 'subscription-1',
updated_at: '2026-01-01T00:00:00Z',
connectionString: 'postgresql://postgres:password@localhost:5432/postgres',
},
})
addAPIMock({
method: 'post',
path: '/platform/pg-meta/:ref/query',
response: () => HttpResponse.json<User[]>([mockUser]),
})
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
queryClient.setQueryData(miscKeys.enabledFeaturesOverride(), { disabled_features: [] })
const content = (backend = otel) => (
<FeatureFlagContext.Provider
value={{
configcat: backend === null ? {} : { otelUnifiedLogs: backend },
posthog: {},
hasLoaded: true,
}}
>
<FeaturePreviewContextProvider>
<ResizablePanelGroup orientation="horizontal">
<UserPanel />
</ResizablePanelGroup>
</FeaturePreviewContextProvider>
</FeatureFlagContext.Provider>
)
const rendered = customRender(content(), {
queryClient,
nuqs: { searchParams: `?show=${mockUser.id}` },
profileContext: createMockProfileContext({
profile: createMockProfile({ disabled_features: disabledFeatures }),
}),
})
return {
...rendered,
queryClient,
updateBackend: (backend: boolean) => rendered.rerender(content(backend)),
}
}
function setIsHoverDevice(isHoverDevice: boolean) {
window.matchMedia = ((query: string) => ({
matches: isHoverDevice && query.includes('hover: hover'),
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => false,
})) as unknown as typeof window.matchMedia
}
describe('UserPanel', () => {
beforeEach(() => routerMock.setCurrentUrl('/project/default/auth/users'))
afterEach(() => {
localStorage.removeItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS)
setIsHoverDevice(false)
})
it('shows the legacy Logs tab when logs are enabled', async () => {
const { queryClient } = renderPanel()
expect(await screen.findByRole('tab', { name: 'Overview' })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Logs' })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Raw JSON' })).toBeInTheDocument()
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
})
it('hides the legacy Logs tab when logs are disabled', async () => {
const { queryClient } = renderPanel(['logs:all'])
expect(await screen.findByRole('tab', { name: 'Overview' })).toBeInTheDocument()
expect(screen.queryByRole('tab', { name: 'Logs' })).not.toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Raw JSON' })).toBeInTheDocument()
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
})
it('keeps the overview copy menu on hover devices', async () => {
const user = userEvent.setup()
const copy = vi.spyOn(navigator.clipboard, 'writeText')
setIsHoverDevice(true)
const { queryClient } = renderPanel()
const emailField = await screen.findByRole('button', { name: 'Email user@example.com' })
emailField.focus()
await user.keyboard('{Enter}')
await user.click(await screen.findByRole('menuitem', { name: 'Copy Email' }))
expect(copy).toHaveBeenLastCalledWith(mockUser.email)
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
})
it('copies overview fields and complete raw JSON from the selected user', async () => {
const user = userEvent.setup()
const copy = vi.spyOn(navigator.clipboard, 'writeText')
const { queryClient } = renderPanel()
expect(
await screen.findByRole('button', { name: 'Email user@example.com' })
).toBeInTheDocument()
const emailField = screen.getByRole('button', { name: 'Email user@example.com' })
emailField.focus()
await user.keyboard('{Enter}')
await user.click(await screen.findByRole('menuitem', { name: 'Copy Email' }))
expect(copy).toHaveBeenLastCalledWith(mockUser.email)
expect(screen.getByText('U')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Close panel' })).toBeInTheDocument()
await user.click(screen.getByRole('tab', { name: 'Raw JSON' }))
await user.click(await screen.findByRole('button', { name: 'Copy user as JSON' }))
expect(copy).toHaveBeenCalledTimes(2)
expect(JSON.parse(copy.mock.calls[1][0])).toEqual(mockUser)
expect(screen.queryByPlaceholderText('Filter...')).not.toBeInTheDocument()
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
})
it.each([true, null])(
'shows recent user logs after Raw JSON with backend flag %s',
async (otel) => {
const user = userEvent.setup()
addAPIMock({
method: 'post',
path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
response: () =>
HttpResponse.json<platformComponents['schemas']['AnalyticsResponse_Output']>({
result: [],
}),
})
const { queryClient } = renderPanel([], { otel, unifiedLogs: true })
await screen.findByRole('tab', { name: 'Logs' })
expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual([
'Overview',
'Raw JSON',
'Logs',
])
await user.click(screen.getByRole('tab', { name: 'Logs' }))
expect(await screen.findByText('No logs in the last 24 hours')).toBeVisible()
expect(screen.queryByRole('link', { name: 'View logs' })).not.toBeInTheDocument()
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
}
)
it('keeps Logs selected when switching between legacy and unified logs', async () => {
const user = userEvent.setup()
addAPIMock({
method: 'post',
path: '/platform/projects/:ref/analytics/endpoints/logs.all.otel',
response: () =>
HttpResponse.json<platformComponents['schemas']['AnalyticsResponse_Output']>({
result: [],
}),
})
const { updateBackend, queryClient } = renderPanel([], { otel: false, unifiedLogs: true })
await user.click(await screen.findByRole('tab', { name: 'Logs' }))
expect(await screen.findByTestId('user-logs')).toBeVisible()
updateBackend(true)
expect(await screen.findByText('No logs in the last 24 hours')).toBeVisible()
expect(screen.getByRole('tab', { name: 'Logs' })).toHaveAttribute('aria-selected', 'true')
updateBackend(false)
expect(await screen.findByTestId('user-logs')).toBeVisible()
expect(screen.getByRole('tab', { name: 'Logs' })).toHaveAttribute('aria-selected', 'true')
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
})
})