mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 00:19:08 +00:00
Part 1 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 ← this PR** | **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 | Remaining `components/interfaces/**` and `QueryInsightsTable` router events | | 6 | #54058 | Remove `next/router` & `next/compat/router` shims, `_router-events.ts`, Vite aliases, and test mocks | Introduces the shared TanStack navigation helpers needed across the stack and migrates `hooks/**`, `lib/**`, and `data/prefetchers/**` off `next/router`. **Added:** - `navigateToUrl` in `apps/studio/lib/navigation.ts` (plus unit tests in `lib/navigation.test.ts`): shared helper for navigating to internal string URLs via TanStack's `useNavigate` (splitting pathname, search params, and hash via `splitInternalUrl`, and handling external/protocol-relative URLs) - `useRoutePattern` in `apps/studio/hooks/misc/useRoutePattern.ts` (plus `useRoutePattern.test.tsx`): returns the active matched TanStack route template (e.g. `/project/$ref/editor/$id`) as the replacement for Next's `router.pathname` **Changed:** - Migrated `hooks/misc/*` (`useHydratedQuery`, `useStudioCommandMenuTelemetry`, `useTableEditorFiltersSort`, `withAuth`) and `hooks/use-check-latest-deploy.tsx` to TanStack's `useLocation`, `useNavigate`, `useRoutePattern`, and `useParams` from `common` - Migrated `lib/profile.tsx` and `lib/telemetry/track.ts` off `next/router` - Migrated `data/prefetchers/project.$ref.tsx`, `project.$ref.editor.tsx`, and `project.$ref.editor.$id.tsx` to `useRouter().preloadRoute` - Wrapped `ReactQueryTestConfig` in `apps/studio/tests/helpers.tsx` with `RouterContextProvider` and updated hook/navigation tests (`useTableEditorFiltersSort*.test.*`, `useFilterLifeCycle.navigation.test.tsx`, `useTableFilter.navigation.test.tsx`, `useInboundBranding.test.ts`, `state/tabs.test.ts`) **Simplified:** - `navigateToUrl` passes `replace` straight through and documents that `url` must be an app-relative path or an external URL. `StudioFrameworkProvider`'s `push` now reuses it. - `useRoutePattern` reads matches and location in a single `useRouterState` subscription - `useTrack` and `useStudioCommandMenuTelemetry` take the pathname from `useFramework()`, the same source as pageviews, so custom events and pageviews always send the same pattern (e.g. `/project/[ref]/sql/[id]`). New tests pin the strings sent, and `toRoutePattern` now has its own unit tests. - Removed `useCurrentPath` (a one-line wrapper with one consumer): `OrganizationSettingsLayout` calls `useLocation` directly - Dropped the no-op `.catch(() => {})` on `preloadRoute` in the prefetchers (`preloadRoute` never rejects) - `useTableEditorFiltersSort` builds the next search with a spread instead of a delete loop - Added `createTestRouter()` to `tests/lib/custom-render.tsx`, and `customRender`/`customRenderHook` now return the `router`. The rest of the stack uses these instead of hand-copied `createRouter` setups. Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Auth redirect flow (`withAuth`) still preserves `returnTo` query parameters when redirecting unauthenticated users to `/sign-in` - [ ] Table Editor sort and filter URL sync (`useTableEditorFiltersSort`) persists and clears `?sort=` / `?filter=` across table switches - [ ] Hovering project and table editor links still triggers route/data prefetching without console errors - [ ] Page view and command menu telemetry still records route patterns and paths accurately --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
149 lines
4.4 KiB
TypeScript
149 lines
4.4 KiB
TypeScript
import {
|
|
Link as TanStackLink,
|
|
useMatches,
|
|
useRouterState,
|
|
useSearch,
|
|
useParams as useTanStackParams,
|
|
useRouter as useTanStackRouter,
|
|
type AnyRouter,
|
|
} from '@tanstack/react-router'
|
|
import {
|
|
DefaultFrameworkImage,
|
|
DefaultFrameworkLink,
|
|
FrameworkProvider,
|
|
resolveStaticImageSrc,
|
|
type FrameworkContextValue,
|
|
type FrameworkImageProps,
|
|
type FrameworkLinkProps,
|
|
} from 'common'
|
|
import { forwardRef, useMemo, type ForwardedRef, type ReactNode } from 'react'
|
|
|
|
import { applyBasePath, isAbsoluteUrl, splitInternalUrl, toRoutePattern } from '@/lib/internal-url'
|
|
import { navigateToUrl } from '@/lib/navigation'
|
|
|
|
function normalizeParams(
|
|
search: Record<string, unknown> | undefined,
|
|
params: Record<string, unknown> | undefined
|
|
): Record<string, string | string[] | undefined> {
|
|
const merged = { ...search, ...params }
|
|
const normalized: Record<string, string | string[] | undefined> = {}
|
|
for (const [key, value] of Object.entries(merged)) {
|
|
if (typeof value === 'string') {
|
|
normalized[key] = value
|
|
} else if (Array.isArray(value)) {
|
|
normalized[key] = value.map(String)
|
|
} else if (value !== undefined && value !== null) {
|
|
normalized[key] = String(value)
|
|
}
|
|
}
|
|
return normalized
|
|
}
|
|
|
|
function resolveSearchOrHashOnlyTarget(
|
|
target: string,
|
|
currentPathname: string,
|
|
currentSearch: string
|
|
): string {
|
|
if (target.startsWith('?')) {
|
|
return `${currentPathname}${target}`
|
|
}
|
|
if (target.startsWith('#')) {
|
|
return `${currentPathname}${currentSearch}${target}`
|
|
}
|
|
return target
|
|
}
|
|
|
|
const StudioLink = forwardRef(function StudioLink(
|
|
props: FrameworkLinkProps,
|
|
ref: ForwardedRef<HTMLAnchorElement>
|
|
) {
|
|
const { href, prefetch, replace, scroll: _scroll, shallow: _shallow, children, ...rest } = props
|
|
const { currentPathname, currentSearch } = useRouterState({
|
|
select: (state) => {
|
|
const committed = state.resolvedLocation ?? state.location
|
|
return {
|
|
currentPathname: committed.pathname,
|
|
currentSearch: committed.searchStr,
|
|
}
|
|
},
|
|
})
|
|
const resolvedHref = resolveSearchOrHashOnlyTarget(href, currentPathname, currentSearch)
|
|
const { to, search, hash } = splitInternalUrl(resolvedHref)
|
|
|
|
if (isAbsoluteUrl(to)) {
|
|
return <DefaultFrameworkLink ref={ref} {...props} />
|
|
}
|
|
|
|
const preload = prefetch === false ? false : prefetch ? 'intent' : undefined
|
|
|
|
return (
|
|
<TanStackLink<AnyRouter, string>
|
|
to={to}
|
|
search={search as never}
|
|
hash={hash}
|
|
replace={replace}
|
|
preload={preload}
|
|
ref={ref}
|
|
{...rest}
|
|
>
|
|
{children}
|
|
</TanStackLink>
|
|
)
|
|
})
|
|
|
|
function StudioImage({ src, ...props }: FrameworkImageProps) {
|
|
return <DefaultFrameworkImage {...props} src={applyBasePath(resolveStaticImageSrc(src))} />
|
|
}
|
|
|
|
export function StudioFrameworkProvider({ children }: { children: ReactNode }) {
|
|
const router = useTanStackRouter()
|
|
const committedLocation = useRouterState({
|
|
select: (state) => state.resolvedLocation ?? state.location,
|
|
})
|
|
// `resolvedLocation` stays unset until the first load commits. Before then `location` can already
|
|
// point at a redirect target while the initial matches are still pending.
|
|
const isReady = useRouterState({ select: (state) => state.resolvedLocation !== undefined })
|
|
const leafRouteId =
|
|
useMatches({ select: (matches) => matches[matches.length - 1]?.routeId }) ??
|
|
committedLocation.pathname
|
|
const routeParams = useTanStackParams({ strict: false })
|
|
const searchParams = useSearch({ strict: false })
|
|
|
|
const value = useMemo<FrameworkContextValue>(() => {
|
|
const pathname = toRoutePattern(leafRouteId)
|
|
const asPath = committedLocation.href
|
|
const currentPathname = committedLocation.pathname
|
|
const currentSearch = committedLocation.searchStr
|
|
const params = normalizeParams(
|
|
searchParams as Record<string, unknown> | undefined,
|
|
routeParams as Record<string, unknown> | undefined
|
|
)
|
|
|
|
return {
|
|
Link: StudioLink,
|
|
Image: StudioImage,
|
|
pathname,
|
|
asPath,
|
|
isReady,
|
|
params,
|
|
push: async (path: string) => {
|
|
await navigateToUrl(
|
|
router.navigate,
|
|
resolveSearchOrHashOnlyTarget(path, currentPathname, currentSearch)
|
|
)
|
|
},
|
|
}
|
|
}, [
|
|
committedLocation.href,
|
|
committedLocation.pathname,
|
|
committedLocation.searchStr,
|
|
isReady,
|
|
leafRouteId,
|
|
routeParams,
|
|
router,
|
|
searchParams,
|
|
])
|
|
|
|
return <FrameworkProvider value={value}>{children}</FrameworkProvider>
|
|
}
|