mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
Moves the remaining `next/navigation` imports in Studio onto TanStack
Router hooks (and `useParams` from `common`), finishes migrating the
remaining `next/link` and `next/router` usages in the touched
components, and removes the `compat/next/navigation.ts` shim and its
Vite alias. Shared packages (`packages/**`) no longer import
`next/navigation`, so the alias can be dropped now.
**Removed:**
- `apps/studio/compat/next/navigation.ts` and the `'next/navigation'`
entry in `apps/studio/vite.config.ts`
- Global `next/navigation` mock in `apps/studio/tests/vitestSetup.ts`
and the obsolete `apps/studio/tests/lib/route-mock.test.tsx`
**Changed:**
- Replaced `usePathname` (12 files) and `useSearchParams` (3 files) with
`useLocation({ select })` from `@tanstack/react-router`
- Replaced `useRouter` in Storage bucket tables, SQL Editor commands,
and `SignInMfaForm` with `useNavigate` from `@tanstack/react-router`,
and updated `createNavigationHandler` in `lib/navigation.ts` to accept
either `NextRouter` or TanStack's `useNavigate`
- Replaced remaining `next/link` imports in touched components
(`SignInMfaForm`, `Restriction`, `DownloadLogsButton`,
`DownloadResultsButton`, `AuthEmailsLayout`, `AuthProvidersLayout`,
`JWTKeysLayout`, `StorageBucketsLayout`) with TanStack Router's `Link`
- Replaced `useParams` in `CreatePublishableAPIKeyDialog` with
`useParams` from `common` (matching `CreateSecretAPIKeyDialog`)
- Wrapped `CustomWrapper` (`tests/lib/custom-render.tsx`) in a default
TanStack `RouterContextProvider` (with optional `router` / `initialUrl`
overrides) and updated affected component tests to drop their
`next/navigation` mocks
Addresses
[FE-5110](https://linear.app/supabase/issue/FE-5110/replace-the-nextnavigation-shim-with-tanstack-router-hooks)
## To test
1. Check active tab highlighting and navigation across Auth Emails, Auth
Providers, JWT Keys, Storage Buckets, and Editor layouts
2. Verify clicking, Cmd/Ctrl-clicking, middle-clicking, and pressing
Enter on Storage bucket rows (Files, Analytics, Vector) navigates as
before
3. Run "Query a table..." and open SQL snippets from the Command Menu
and confirm `/project/$ref/sql/$id` opens with multi-line SQL preserved
in `?content=`
4. In the MFA sign-in flow, verify the recovery code link and
`forgot-password` completion preserve query params (`returnTo`,
`context=forgot-password`), and Cancel signs out and replaces history
with `/sign-in`
5. Confirm Table Editor sort/filter URL sync persists filters per table
without leaking across table switches
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
101 lines
3.6 KiB
TypeScript
101 lines
3.6 KiB
TypeScript
import {
|
|
createMemoryHistory,
|
|
createRootRoute,
|
|
createRoute,
|
|
createRouter,
|
|
Outlet,
|
|
RouterProvider,
|
|
type AnyRoute,
|
|
} from '@tanstack/react-router'
|
|
import { act, render, type RenderOptions } from '@testing-library/react'
|
|
|
|
import { CustomWrapper } from './custom-render'
|
|
import { RenderedRouteContext } from './route-aware-hooks'
|
|
import { StudioFrameworkProvider } from '@/components/interfaces/App/StudioFrameworkProvider'
|
|
import { parseSearch, stringifySearch } from '@/lib/router-search-params'
|
|
|
|
type RouteNode = { id: string } | { path: string }
|
|
|
|
type RenderRouteOptions = Omit<
|
|
Parameters<typeof CustomWrapper>[0],
|
|
'children' | 'router' | 'initialUrl'
|
|
> & {
|
|
routeId: string
|
|
url: string
|
|
renderOptions?: RenderOptions
|
|
}
|
|
|
|
const RenderedRouteRoot = () => (
|
|
<RenderedRouteContext.Provider value={true}>
|
|
<StudioFrameworkProvider>
|
|
<Outlet />
|
|
</StudioFrameworkProvider>
|
|
</RenderedRouteContext.Provider>
|
|
)
|
|
|
|
// `/_app/org/$slug/general` → [{ id: '_app' }, { path: 'org/$slug/general' }]
|
|
// `/project/$ref/` → [{ path: 'project/$ref' }, { path: '/' }]
|
|
function toRouteNodes(routeId: string): RouteNode[] {
|
|
const segments = routeId.split('/').slice(1)
|
|
const isIndexRoute = routeId.endsWith('/')
|
|
const { nodes, pending } = segments.reduce<{ nodes: RouteNode[]; pending: string[] }>(
|
|
(acc, segment) => {
|
|
if (!segment) return acc
|
|
const isPathless = segment.startsWith('_') && segment.length > 1
|
|
if (!isPathless) return { ...acc, pending: [...acc.pending, segment] }
|
|
const pathNodes = acc.pending.length ? [{ path: acc.pending.join('/') }] : []
|
|
return { nodes: [...acc.nodes, ...pathNodes, { id: segment }], pending: [] }
|
|
},
|
|
{ nodes: [], pending: [] }
|
|
)
|
|
const pathNodes = pending.length ? [{ path: pending.join('/') }] : []
|
|
return [...nodes, ...pathNodes, ...(isIndexRoute ? [{ path: '/' }] : [])]
|
|
}
|
|
|
|
// Mounts the real file route under a bare root, rebuilding its id chain the way
|
|
// routeTree.gen.ts does, so `Route.useParams()` and friends resolve without
|
|
// loading the app's real layouts.
|
|
function buildRouteTree(route: AnyRoute, routeId: string) {
|
|
const rootRoute = createRootRoute({ component: RenderedRouteRoot })
|
|
const nodes = toRouteNodes(routeId)
|
|
const parents = nodes.slice(0, -1).reduce<AnyRoute[]>((acc, node) => {
|
|
const parent = acc.at(-1) ?? rootRoute
|
|
return [...acc, createRoute({ getParentRoute: () => parent, ...node })]
|
|
}, [])
|
|
const leafParent = parents.at(-1) ?? rootRoute
|
|
Object.assign(route.options, { getParentRoute: () => leafParent, ...nodes.at(-1) })
|
|
;[...parents, route].reduceRight<AnyRoute | undefined>((child, parent) => {
|
|
if (child) parent.addChildren([child])
|
|
return parent
|
|
}, undefined)
|
|
return rootRoute.addChildren([parents[0] ?? route])
|
|
}
|
|
|
|
/**
|
|
* Renders a file route at `url` inside a memory router, wrapped in the same providers as
|
|
* `customRender`. `routeId` is the id passed to `createFileRoute`. Returns the router so
|
|
* tests can assert on navigation.
|
|
*/
|
|
export async function renderRoute(
|
|
route: AnyRoute,
|
|
{ routeId, url, renderOptions, ...wrapper }: RenderRouteOptions
|
|
) {
|
|
const router = createRouter({
|
|
routeTree: buildRouteTree(route, routeId),
|
|
history: createMemoryHistory({ initialEntries: [url] }),
|
|
parseSearch,
|
|
stringifySearch,
|
|
defaultNotFoundComponent: () => null,
|
|
})
|
|
await act(() => router.load())
|
|
const result = render(<RouterProvider router={router} />, {
|
|
wrapper: ({ children }) => (
|
|
<CustomWrapper {...wrapper} router={router}>
|
|
{children}
|
|
</CustomWrapper>
|
|
),
|
|
...renderOptions,
|
|
})
|
|
return { ...result, router }
|
|
}
|