mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 23:49:03 +00:00
Part 2 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 ← this PR** | **`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 | 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 15 `apps/studio/components/ui/**` files off `next/router`. **Changed:** - Replaced `useRouter` across `AIAssistantPanel` (`AIAssistant`, `ModelSelector`), `Charts/ComposedChartHandler`, `EditorPanel`, `ErrorBoundary` (`ClientSideExceptionHandler`, `GlobalErrorBoundaryState`, `InsertBeforeRemoveChildErrorHandler`), `GlobalShortcuts/ShortcutsReferenceSheet`, `HelpPanel` (`HelpOptionsList`, `HelpPanel`), `ProductMenu/ProductMenuShortcuts`, `QueryBlock/EditQueryButton`, and `ResourceExhaustionWarningBanner` with TanStack's `useNavigate`, `useLocation`, `useRoutePattern`, and `useParams` from `common` - Updated `AIAssistant.test.tsx`, `HelpOptionsList.test.tsx`, and `ProductMenuShortcuts.test.tsx` to use TanStack Router instead of `next/router` mocks **Simplified:** - `EditQueryButton` and `ShortcutsReferenceSheet` match against `useRoutePattern()` instead of the real pathname, as `router.pathname` did before. A ref or slug containing `sql` or `advisors` no longer misfires. - Removed the unused `restrictToRoutes` field from `ResourceExhaustionWarningBanner` (no warning sets it) - `AIAssistant` clears the handoff param with `navigate({ to: '.' })`, dropping a pathname subscription and an `AnyRouter` cast - `ProductMenuShortcuts` inlines its handler (`useShortcut` always calls the latest callback) - Moved the `AdvisorsNavigationShortcuts.test.tsx` fix into this PR so it passes on its own - Tests use the shared `createTestRouter` and `customRender` router Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] AI Assistant panel links, model selector navigation, and "Edit in SQL Editor" (`EditQueryButton`) navigate cleanly - [ ] Keyboard shortcuts in `ProductMenuShortcuts` and the shortcuts reference sheet (`?`) match the active section and navigate as expected - [ ] Error boundary recovery ("Reload page" / navigation actions) and Help panel links still work - [ ] Resource exhaustion warning banner matches project routes as before --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
185 lines
5.9 KiB
TypeScript
185 lines
5.9 KiB
TypeScript
import { SupportCategories } from '@supabase/shared-types/out/constants'
|
|
import { createRootRoute, createRoute, RouterContextProvider } from '@tanstack/react-router'
|
|
import { render, waitFor } from '@testing-library/react'
|
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
import { AIAssistant } from './AIAssistant'
|
|
import {
|
|
ASSISTANT_HANDOFF_QUERY_PARAM,
|
|
storeAssistantHandoff,
|
|
} from '@/components/interfaces/Support/SupportAssistant.utils'
|
|
import type { SubmittedSupportRequest } from '@/components/interfaces/Support/SupportForm.state'
|
|
import { createTestRouter } from '@/tests/lib/custom-render'
|
|
|
|
// Every hook this component depends on is mocked directly below (no React Query hooks,
|
|
// no network calls) — this targets the handoff effect's internal logic, not data fetching,
|
|
// so plain `render` is used here rather than `customRender`/`addAPIMock` (same pattern as
|
|
// the neighboring SupportAssistantSuccessCard.test.tsx).
|
|
const { chats, mockNewChat, mockSelectChat, mockSyncSupportChatToFront, mockToastError, routeRef } =
|
|
vi.hoisted(() => ({
|
|
chats: {} as Record<string, { supportMetadata?: unknown }>,
|
|
mockNewChat: vi.fn(),
|
|
mockSelectChat: vi.fn(),
|
|
mockSyncSupportChatToFront: vi.fn(),
|
|
mockToastError: vi.fn(),
|
|
routeRef: { current: 'project-a' as string | undefined },
|
|
}))
|
|
|
|
vi.mock('sonner', () => ({
|
|
toast: { error: mockToastError },
|
|
}))
|
|
|
|
vi.mock('common/hooks', () => ({
|
|
useParams: () => ({ id: undefined, source: undefined, ref: routeRef.current }),
|
|
}))
|
|
|
|
vi.mock('@/state/ai-assistant-state', () => ({
|
|
useAiAssistantStateSnapshot: () => ({
|
|
activeChatId: undefined,
|
|
isInitialized: true,
|
|
initialInput: '',
|
|
sqlSnippets: undefined,
|
|
suggestions: undefined,
|
|
}),
|
|
useAiAssistantState: () => ({
|
|
chats,
|
|
newChat: mockNewChat,
|
|
selectChat: mockSelectChat,
|
|
branchChat: vi.fn(),
|
|
setSqlSnippets: vi.fn(),
|
|
clearSqlSnippets: vi.fn(),
|
|
sqlSnippets: undefined,
|
|
}),
|
|
}))
|
|
|
|
vi.mock('@/state/ai-chat-front-sync', () => ({
|
|
syncSupportChatToFront: mockSyncSupportChatToFront,
|
|
}))
|
|
|
|
vi.mock('@/state/sql-editor/sql-editor-state', () => ({
|
|
useSqlEditorV2StateSnapshot: () => ({ snippets: {} }),
|
|
}))
|
|
|
|
vi.mock('@/state/sidebar-manager-state', () => ({
|
|
useSidebarManagerSnapshot: () => ({ activeSidebar: undefined, closeSidebar: vi.fn() }),
|
|
}))
|
|
|
|
vi.mock('@/state/shortcuts/useShortcut', () => ({
|
|
useShortcut: () => {},
|
|
}))
|
|
|
|
vi.mock('./AssistantChat', () => ({
|
|
AssistantChat: () => null,
|
|
}))
|
|
|
|
const supportRequest: SubmittedSupportRequest = {
|
|
organizationSlug: 'org-1',
|
|
projectRef: 'project-a',
|
|
category: SupportCategories.PROBLEM,
|
|
severity: 'Normal',
|
|
subject: 'API requests fail',
|
|
message: 'Requests fail with 500s',
|
|
affectedServices: 'api',
|
|
library: 'javascript',
|
|
allowSupportAccess: true,
|
|
dashboardLogs: undefined,
|
|
threadRef: 'thread-ref-1',
|
|
frontConversationId: 'front-conversation-1',
|
|
}
|
|
|
|
const renderAssistant = (initialUrl = '/project/project-a') => {
|
|
const rootRoute = createRootRoute()
|
|
const projectRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: '/project/$ref',
|
|
})
|
|
const router = createTestRouter(initialUrl, rootRoute.addChildren([projectRoute]))
|
|
const navigateSpy = vi.spyOn(router, 'navigate')
|
|
const view = render(
|
|
<RouterContextProvider router={router}>
|
|
<AIAssistant />
|
|
</RouterContextProvider>
|
|
)
|
|
return { ...view, router, navigateSpy }
|
|
}
|
|
|
|
describe('AIAssistant handoff', () => {
|
|
beforeEach(() => {
|
|
Object.keys(chats).forEach((key) => delete chats[key])
|
|
mockNewChat.mockReset()
|
|
mockSelectChat.mockReset()
|
|
mockSyncSupportChatToFront.mockReset()
|
|
mockToastError.mockReset()
|
|
routeRef.current = 'project-a'
|
|
sessionStorage.clear()
|
|
|
|
mockNewChat.mockImplementation(() => {
|
|
chats['chat-1'] = {}
|
|
return 'chat-1'
|
|
})
|
|
})
|
|
|
|
it('creates and selects the chat when the handoff project matches the route', async () => {
|
|
storeAssistantHandoff('token-1', supportRequest)
|
|
|
|
const { router } = renderAssistant(
|
|
`/project/project-a?${ASSISTANT_HANDOFF_QUERY_PARAM}=token-1`
|
|
)
|
|
|
|
await waitFor(() => {
|
|
expect(mockNewChat).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
expect(mockSelectChat).toHaveBeenCalledWith('chat-1')
|
|
expect(chats['chat-1'].supportMetadata).toMatchObject({
|
|
projectRef: 'project-a',
|
|
isSupportChat: true,
|
|
})
|
|
await waitFor(() => {
|
|
expect(router.state.location.href).toBe('/project/project-a')
|
|
})
|
|
})
|
|
|
|
it('starts a new chat and shows a toast when the handoff project does not match the route', async () => {
|
|
routeRef.current = 'project-b'
|
|
storeAssistantHandoff('token-1', supportRequest)
|
|
|
|
const { router } = renderAssistant(
|
|
`/project/project-b?${ASSISTANT_HANDOFF_QUERY_PARAM}=token-1`
|
|
)
|
|
|
|
await waitFor(() => {
|
|
expect(router.state.location.href).toBe('/project/project-b')
|
|
})
|
|
|
|
expect(mockNewChat).toHaveBeenCalledWith()
|
|
expect(mockSelectChat).not.toHaveBeenCalled()
|
|
expect(mockToastError).toHaveBeenCalledWith(
|
|
"Couldn't load your ticket context here — started a new chat instead."
|
|
)
|
|
})
|
|
|
|
it('does nothing when there is no handoff param', async () => {
|
|
const { navigateSpy } = renderAssistant('/project/project-a')
|
|
|
|
expect(mockNewChat).not.toHaveBeenCalled()
|
|
expect(navigateSpy).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('cleans up the URL and falls back to a new chat with a toast when the token has no matching sessionStorage entry (e.g. link opened in a new tab)', async () => {
|
|
const { router } = renderAssistant(
|
|
`/project/project-a?${ASSISTANT_HANDOFF_QUERY_PARAM}=token-never-stored`
|
|
)
|
|
|
|
await waitFor(() => {
|
|
expect(router.state.location.href).toBe('/project/project-a')
|
|
})
|
|
|
|
expect(mockNewChat).toHaveBeenCalledWith()
|
|
expect(mockSelectChat).not.toHaveBeenCalled()
|
|
expect(mockToastError).toHaveBeenCalledWith(
|
|
"Couldn't load your ticket context here — started a new chat instead."
|
|
)
|
|
})
|
|
})
|