The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Collapse the metabase/router facade onto react-router (#79242)
Romeo Van Snick48a01bd3b0cd
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.jsindex c98c812a597..a470452eae6 100644--- a/frontend/src/metabase/app.js+++ b/frontend/src/metabase/app.js@@ -37,7 +37,7 @@ import { initializeInteractiveEmbedding } from "metabase/embedding/interactive-eimport { MetabotProvider } from "metabase/metabot/context";import { PLUGIN_APP_INIT_FUNCTIONS } from "metabase/plugins";import { MetabaseReduxProvider } from "metabase/redux";-import { LOCATION_CHANGE, createV7Navigator } from "metabase/router";+import { LOCATION_CHANGE, createRouterNavigator } from "metabase/router";import { getUserId } from "metabase/selectors/user";import { GlobalStyles } from "metabase/styled-components/containers/GlobalStyles";import { PortalContainer } from "metabase/ui";@@ -80,7 +80,7 @@ function _init(reducers, getRoutes, callback) {const store = getStore(reducers,- createV7Navigator(),+ createRouterNavigator(),undefined,extraMiddlewares,);diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsxindex 185b79d7826..cf06beddeba 100644--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx@@ -11,7 +11,7 @@ import {} from "metabase/redux/store/mocks";import type { Location } from "metabase/router";import { push, replace, useIsNavigationHeld } from "metabase/router";-import { notifyLocationListeners } from "metabase/router/v7/navigator";+import { notifyLocationListeners } from "metabase/router/navigator";import type { ParameterValueOrArray } from "metabase-types/api";import { createMockParameter } from "metabase-types/api/mocks";diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsxindex 0c08250d706..84317fdb2ec 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx@@ -9,7 +9,7 @@ import {setupTableEndpoints,} from "__support__/server-mocks";import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { Route, RouterProviderV7Memory } from "metabase/router";+import { Route, RouterProviderMemory } from "metabase/router";import {createMockCard,createMockCollection,@@ -205,9 +205,9 @@ describe("SmartLink", () => {const props = createProps("dashboard", dashboard);renderWithProviders(- <RouterProviderV7Memory initialRoute="/subpath" basename="/subpath">+ <RouterProviderMemory initialRoute="/subpath" basename="/subpath"><Route path="*" element={<SmartLinkComponent {...props} />} />- </RouterProviderV7Memory>,+ </RouterProviderMemory>,);await waitFor(() => {@@ -231,9 +231,9 @@ describe("SmartLink", () => {const props = createProps("dashboard", dashboard);renderWithProviders(- <RouterProviderV7Memory initialRoute="/">+ <RouterProviderMemory initialRoute="/"><Route path="*" element={<SmartLinkComponent {...props} />} />- </RouterProviderV7Memory>,+ </RouterProviderMemory>,);await waitFor(() => {diff --git a/frontend/src/metabase/router/v7/AppShell.tsx b/frontend/src/metabase/router/AppShell.tsxsimilarity index 89%rename from frontend/src/metabase/router/v7/AppShell.tsxrename to frontend/src/metabase/router/AppShell.tsxindex 4fb9d7d2835..18f1b7f5276 100644--- a/frontend/src/metabase/router/v7/AppShell.tsx+++ b/frontend/src/metabase/router/AppShell.tsx@@ -1,7 +1,7 @@import { useEffect } from "react";import { Outlet, useNavigate } from "react-router";-import { setV7Navigate } from "./navigator";+import { setRouterNavigate } from "./navigator";import { RouteLeaveGuards } from "./route-leave-guards";/**@@ -21,8 +21,8 @@ export function AppShell(): JSX.Element {const navigate = useNavigate();useEffect(() => {- setV7Navigate(navigate);- return () => setV7Navigate(null);+ setRouterNavigate(navigate);+ return () => setRouterNavigate(null);}, [navigate]);return (diff --git a/frontend/src/metabase/router/Navigate.tsx b/frontend/src/metabase/router/Navigate.tsxindex a4405596ed5..6f04152e2b6 100644--- a/frontend/src/metabase/router/Navigate.tsx+++ b/frontend/src/metabase/router/Navigate.tsx@@ -1,8 +1,7 @@import { useEffect } from "react";+import { useLocation, useNavigate } from "react-router";import type { To } from "./types";-import { useLocation } from "./use-location";-import { useNavigate } from "./use-navigate";export interface NavigateProps {to: To;diff --git a/frontend/src/metabase/router/Navigate.unit.spec.tsx b/frontend/src/metabase/router/Navigate.unit.spec.tsxindex ddc4bbb498b..633af683c4e 100644--- a/frontend/src/metabase/router/Navigate.unit.spec.tsx+++ b/frontend/src/metabase/router/Navigate.unit.spec.tsx@@ -2,9 +2,9 @@ import userEvent from "@testing-library/user-event";import { useState } from "react";import { act, renderWithProviders, screen, waitFor } from "__support__/ui";+import { Route } from "metabase/router";import { Navigate } from "./Navigate";-import { Route } from "./route";// Stable references: `<Navigate>` keeps `state` raw in its effect deps (like v7),// so a fresh object literal each render would re-navigate and loop.diff --git a/frontend/src/metabase/router/Outlet.tsx b/frontend/src/metabase/router/Outlet.tsxdeleted file mode 100644index 937a295fdcd..00000000000--- a/frontend/src/metabase/router/Outlet.tsx+++ /dev/null@@ -1,7 +0,0 @@-/**- * react-router v7's `<Outlet>`: renders the matched child route (or nothing when- * there is none).- *- * @see https://reactrouter.com/7.18.1/api/components/Outlet- */-export { Outlet } from "react-router";diff --git a/frontend/src/metabase/router/Outlet.unit.spec.tsx b/frontend/src/metabase/router/Outlet.unit.spec.tsxindex 758d33424d2..f400743b825 100644--- a/frontend/src/metabase/router/Outlet.unit.spec.tsx+++ b/frontend/src/metabase/router/Outlet.unit.spec.tsx@@ -1,6 +1,5 @@import { renderWithProviders, screen } from "__support__/ui";--import { Outlet } from "./Outlet";+import { Outlet } from "metabase/router";describe("router/Outlet", () => {it("renders nothing when there is no matched child", () => {diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsxindex c113c886003..0d1d0e94f57 100644--- a/frontend/src/metabase/router/RouterProvider.tsx+++ b/frontend/src/metabase/router/RouterProvider.tsx@@ -1,20 +1,113 @@import type { PropsWithChildren } from "react";+import { useLayoutEffect, useState } from "react";+import {+ type DataRouter,+ RouterProvider as ReactRouterProvider,+} from "react-router";-import { RouterProviderV7 } from "./v7/RouterProviderV7";-import type { LocationMirror } from "./v7/location-mirror";+import { getBasename } from "metabase/utils/basename";++import {+ type MemoryTestRouterHolder,+ createAppRouter,+ createMemoryAppRouter,+} from "./create-router";+import type { LocationMirror } from "./location-mirror";++/**+ * Mirrors every location out to `onLocationChange`, which is how the app emits+ * LOCATION_CHANGE on navigation (see `createLocationMirror`). Replaces v3's+ * `syncHistoryWithStore`.+ *+ * Subscribing to the router rather than reading the rendered location matters+ * because v3 dispatched LOCATION_CHANGE as part of the transition rather than+ * after a render. Thunks read the store synchronously right after navigating, so+ * a store that lags a render makes them push a stale location and clobber query+ * params that were just set.+ */+function useLocationMirror(+ router: DataRouter,+ onLocationChange?: LocationMirror,+): void {+ useLayoutEffect(() => {+ if (!onLocationChange) {+ return;+ }+ // The router notifies its subscribers on every state update, not only on a+ // location change, and replays the state it initialized with to the first+ // subscriber. Key on the location so neither is mirrored twice.+ let lastKey: string | null = null;++ const mirror = ({ location }: DataRouter["state"]) => {+ if (location.key === lastKey) {+ return;+ }+ lastKey = location.key;+ onLocationChange(location);+ };++ mirror(router.state);+ return router.subscribe(mirror);+ }, [router, onLocationChange]);+}/**- * Hosts the app on react-router v7.+ * Hosts the app as a data router. The whole route tree goes in as real data+ * routes, so there is no descendant `<Routes>` left. No route has a loader,+ * `lazy`, or middleware yet: adding those per subtree is what DEV-2291 does from+ * here.+ *+ * `useTransitions={false}` keeps navigation committing synchronously.+ * react-router otherwise marks its own location update as a transition, which in+ * a production React build deprioritises it so it can commit long after the click+ * that caused it. v3 navigated synchronously, and the app was written against+ * that: a navigation that lands mid-interaction remounts whatever is on screen,+ * which silently discarded state such as the text typed into a modal that was+ * opened right after clicking a link.*- * Pass `createLocationMirror(store.dispatch)` as `onLocationChange` to emit a- * LOCATION_CHANGE for every navigation (the `isNavbarOpen` / `errorPage`- * reducers and trace-id rotation react to it).+ * `onLocationChange` is how the location reaches redux: the app passes+ * `createLocationMirror(store.dispatch)`, so the router itself stays unaware of+ * the store. The `isNavbarOpen` and `errorPage` reducers and trace-id rotation+ * all react to the LOCATION_CHANGE it emits.*/-export const RouterProvider = ({+export function RouterProvider({children,onLocationChange,-}: PropsWithChildren<{ onLocationChange?: LocationMirror }>) => (- <RouterProviderV7 onLocationChange={onLocationChange}>- {children}- </RouterProviderV7>-);+}: PropsWithChildren<{ onLocationChange?: LocationMirror }>): JSX.Element {+ const [router] = useState(() =>+ createAppRouter(children, getBasename() || undefined),+ );+ useLocationMirror(router, onLocationChange);++ return <ReactRouterProvider router={router} useTransitions={false} />;+}++/**+ * The same host on an in-memory history, for tests. Mirrors what+ * `renderWithProviders({ withRouter: true })` mounts, including navigation+ * blocking. Pass `routerHolder` to drive and inspect the router from outside the+ * tree.+ */+export function RouterProviderMemory({+ children,+ initialRoute,+ basename,+ routerHolder,+ onLocationChange,+}: PropsWithChildren<{+ initialRoute: string;+ basename?: string;+ routerHolder?: MemoryTestRouterHolder;+ onLocationChange?: LocationMirror;+}>): JSX.Element {+ const [router] = useState(() => {+ const created = createMemoryAppRouter(children, initialRoute, basename);+ if (routerHolder) {+ routerHolder.current = created;+ }+ return created;+ });+ useLocationMirror(router, onLocationChange);++ return <ReactRouterProvider router={router} useTransitions={false} />;+}diff --git a/frontend/src/metabase/router/RouterProvider.unit.spec.tsx b/frontend/src/metabase/router/RouterProvider.unit.spec.tsxindex a295a8b3903..42ce294f3ac 100644--- a/frontend/src/metabase/router/RouterProvider.unit.spec.tsx+++ b/frontend/src/metabase/router/RouterProvider.unit.spec.tsx@@ -1,10 +1,7 @@import { usePrevious } from "react-use";import { act, renderWithProviders, screen } from "__support__/ui";--import { Route } from "./route";-import { useLocation } from "./use-location";-import { useParams } from "./use-params";+import { Route, useLocation, useParams } from "metabase/router";// Mirrors the document /new -> /new leave prompt: a page that derives transient// state from `usePrevious(location.key)` and expects to stay rendered until thediff --git a/frontend/src/metabase/router/v7/create-router.tsx b/frontend/src/metabase/router/create-router.tsxsimilarity index 100%rename from frontend/src/metabase/router/v7/create-router.tsxrename to frontend/src/metabase/router/create-router.tsxdiff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.tsindex c997c9dab2c..7e5634cce96 100644--- a/frontend/src/metabase/router/index.ts+++ b/frontend/src/metabase/router/index.ts@@ -1,36 +1,32 @@+export {+ Outlet,+ Route,+ useLocation,+ useNavigate,+ useNavigationType,+ useParams,+ useSearchParams,+} from "react-router";export * from "./middleware";export * from "./navigation";export * from "./Navigate";export * from "./redirect";export * from "./router-link";-export * from "./route";-export * from "./Outlet";export * from "./location-change";export * from "./RouterProvider";export * from "./types";-export * from "./use-location";-export * from "./use-navigate";-export * from "./use-navigation-type";-export * from "./use-params";+export * from "./use-maybe-location";export * from "./use-route-leave-blocker";-export * from "./use-search-params";export {createMemoryAppRouter,type MemoryTestRouter,type MemoryTestRouterHolder,-} from "./v7/create-router";-export { queryToSearch, toFacadeLocation } from "./v7/location";-export {- createLocationMirror,- type LocationMirror,-} from "./v7/location-mirror";+} from "./create-router";+export { queryToSearch, toFacadeLocation } from "./location";+export { createLocationMirror, type LocationMirror } from "./location-mirror";export {- createV7Navigator,+ createRouterNavigator,subscribeLocation,toNavigateArgs,-} from "./v7/navigator";-export { getRawBrowserHistory } from "./v7/raw-history";-// The memory-router engine is test-only. It reaches the barrel rather than a-// deep import because `sideEffects: false` lets rspack drop it from the app-// bundles, where nothing references it.-export { RouterProviderV7Memory } from "./v7/RouterProviderV7";+} from "./navigator";+export { getRawBrowserHistory } from "./raw-history";diff --git a/frontend/src/metabase/router/v7/location-mirror.ts b/frontend/src/metabase/router/location-mirror.tssimilarity index 82%rename from frontend/src/metabase/router/v7/location-mirror.tsrename to frontend/src/metabase/router/location-mirror.tsindex 308cd5e2825..ba3b6726781 100644--- a/frontend/src/metabase/router/v7/location-mirror.ts+++ b/frontend/src/metabase/router/location-mirror.ts@@ -1,12 +1,11 @@-import type { Location as V7Location } from "react-router";--import { LOCATION_CHANGE } from "../location-change";-import type { Location } from "../types";+import type { Location as ReactRouterLocation } from "react-router";import { toFacadeLocation } from "./location";+import { LOCATION_CHANGE } from "./location-change";import { notifyLocationListeners } from "./navigator";+import type { Location } from "./types";-export type LocationMirror = (location: V7Location) => void;+export type LocationMirror = (location: ReactRouterLocation) => void;/*** The dispatch half of a redux store, narrowed to what the mirror needs. Takingdiff --git a/frontend/src/metabase/router/v7/location.ts b/frontend/src/metabase/router/location.tssimilarity index 88%rename from frontend/src/metabase/router/v7/location.tsrename to frontend/src/metabase/router/location.tsindex 1ac1e202656..1d6645c0783 100644--- a/frontend/src/metabase/router/v7/location.ts+++ b/frontend/src/metabase/router/location.ts@@ -1,6 +1,6 @@-import type { Location as V7Location } from "react-router";+import type { Location as ReactRouterLocation } from "react-router";-import type { Location as HistoryLocation } from "../types";+import type { Location as HistoryLocation } from "./types";/*** Serialize a query object into the `search` string a navigation target carries.@@ -37,7 +37,9 @@ export function queryToSearch(query: Record<string, unknown>): string {* from a v7 location. All that is left to normalize is `state`, which the legacy* readers treat as absent when it is `undefined`.*/-export function toFacadeLocation(location: V7Location): HistoryLocation {+export function toFacadeLocation(+ location: ReactRouterLocation,+): HistoryLocation {return {pathname: location.pathname,search: location.search,diff --git a/frontend/src/metabase/router/v7/location.unit.spec.ts b/frontend/src/metabase/router/location.unit.spec.tssimilarity index 100%rename from frontend/src/metabase/router/v7/location.unit.spec.tsrename to frontend/src/metabase/router/location.unit.spec.tsdiff --git a/frontend/src/metabase/router/v7/navigator.ts b/frontend/src/metabase/router/navigator.tssimilarity index 94%rename from frontend/src/metabase/router/v7/navigator.tsrename to frontend/src/metabase/router/navigator.tsindex 92ca24b7a6f..934a22e99f7 100644--- a/frontend/src/metabase/router/v7/navigator.ts+++ b/frontend/src/metabase/router/navigator.ts@@ -1,7 +1,7 @@import type { NavigateFunction, NavigateOptions, To } from "react-router";-import type { RouterNavigator } from "../middleware";-import type { Location as HistoryLocation, LocationDescriptor } from "../types";+import type { RouterNavigator } from "./middleware";+import type { Location as HistoryLocation, LocationDescriptor } from "./types";/*** The live v7 `navigate`, registered by the host's `AppShell` once the router mounts.@@ -19,7 +19,7 @@ let currentNavigate: NavigateFunction | null = null;*/let pendingNavigations: Array<(navigate: NavigateFunction) => void> = [];-export function setV7Navigate(navigate: NavigateFunction | null): void {+export function setRouterNavigate(navigate: NavigateFunction | null): void {currentNavigate = navigate;if (!navigate) {// The router unmounted. Anything still buffered was meant for it, not for@@ -86,7 +86,7 @@ export function toNavigateArgs(* `dispatch(push(...))` navigates the v7 router. A call before the router mounts* is buffered and flushed on registration, so a mount-time redirect is not lost.*/-export function createV7Navigator(): RouterNavigator {+export function createRouterNavigator(): RouterNavigator {const navigate = (to: To | number, options?: NavigateOptions) => {const run = (fn: NavigateFunction) =>typeof to === "number" ? fn(to) : fn(to, options);diff --git a/frontend/src/metabase/router/v7/navigator.unit.spec.ts b/frontend/src/metabase/router/navigator.unit.spec.tssimilarity index 80%rename from frontend/src/metabase/router/v7/navigator.unit.spec.tsrename to frontend/src/metabase/router/navigator.unit.spec.tsindex a1523544d2c..c951cbad343 100644--- a/frontend/src/metabase/router/v7/navigator.unit.spec.ts+++ b/frontend/src/metabase/router/navigator.unit.spec.ts@@ -1,4 +1,8 @@-import { createV7Navigator, setV7Navigate, toNavigateArgs } from "./navigator";+import {+ createRouterNavigator,+ setRouterNavigate,+ toNavigateArgs,+} from "./navigator";describe("toNavigateArgs", () => {it("maps a descriptor's URL parts onto a v7 target", () => {@@ -35,39 +39,39 @@ describe("toNavigateArgs", () => {// registers its `navigate`. A navigation dispatched in that window (a guard// redirecting from a mount layout effect) must not be lost, but it also must not// leak into a later router once this one is gone.-describe("createV7Navigator pre-mount buffering", () => {+describe("createRouterNavigator pre-mount buffering", () => {afterEach(() => {- setV7Navigate(null);+ setRouterNavigate(null);});it("buffers a navigation made before the router mounts and flushes it on register", () => {- const navigator = createV7Navigator();+ const navigator = createRouterNavigator();navigator.replace("/target");const navigate = jest.fn();- setV7Navigate(navigate);+ setRouterNavigate(navigate);expect(navigate).toHaveBeenCalledWith("/target", { replace: true });});it("navigates immediately once the router is registered", () => {const navigate = jest.fn();- setV7Navigate(navigate);+ setRouterNavigate(navigate);- createV7Navigator().push("/now");+ createRouterNavigator().push("/now");expect(navigate).toHaveBeenCalledTimes(1);});it("drops a buffered navigation when the router unmounts before it flushes", () => {- const navigator = createV7Navigator();+ const navigator = createRouterNavigator();navigator.replace("/stale");// Router unmounts without ever registering; the next one must not inherit it.- setV7Navigate(null);+ setRouterNavigate(null);const navigate = jest.fn();- setV7Navigate(navigate);+ setRouterNavigate(navigate);expect(navigate).not.toHaveBeenCalled();});diff --git a/frontend/src/metabase/router/v7/raw-history.ts b/frontend/src/metabase/router/raw-history.tssimilarity index 100%rename from frontend/src/metabase/router/v7/raw-history.tsrename to frontend/src/metabase/router/raw-history.tsdiff --git a/frontend/src/metabase/router/redirect.unit.spec.tsx b/frontend/src/metabase/router/redirect.unit.spec.tsxindex 8ea025224f8..f8034b644c9 100644--- a/frontend/src/metabase/router/redirect.unit.spec.tsx+++ b/frontend/src/metabase/router/redirect.unit.spec.tsx@@ -1,8 +1,7 @@import { renderWithProviders, screen, waitFor } from "__support__/ui";+import { Outlet, Route } from "metabase/router";-import { Outlet } from "./Outlet";import { redirect } from "./redirect";-import { Route } from "./route";const Parent = () => (<div>diff --git a/frontend/src/metabase/router/v7/route-leave-guards.tsx b/frontend/src/metabase/router/route-leave-guards.tsxsimilarity index 100%rename from frontend/src/metabase/router/v7/route-leave-guards.tsxrename to frontend/src/metabase/router/route-leave-guards.tsxdiff --git a/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx b/frontend/src/metabase/router/route-leave-scope.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsxrename to frontend/src/metabase/router/route-leave-scope.unit.spec.tsxdiff --git a/frontend/src/metabase/router/route.tsx b/frontend/src/metabase/router/route.tsxdeleted file mode 100644index b7c987d2b52..00000000000--- a/frontend/src/metabase/router/route.tsx+++ /dev/null@@ -1,11 +0,0 @@-/**- * react-router v7's `<Route>`. It is route configuration and never renders:- * `createRoutesFromElements` reads its props to build the route tree.- *- * The app has authored routes in v7 syntax since the start of the migration, so- * they now go in as they are, with no translation step. A route can therefore- * carry any prop v7 reads, `lazy` and `loader` included.- *- * @see https://reactrouter.com/7.18.1/api/components/Route- */-export { Route } from "react-router";diff --git a/frontend/src/metabase/router/route.unit.spec.tsx b/frontend/src/metabase/router/route.unit.spec.tsxindex 636745b9f11..3f3bc1bd2d7 100644--- a/frontend/src/metabase/router/route.unit.spec.tsx+++ b/frontend/src/metabase/router/route.unit.spec.tsx@@ -1,10 +1,9 @@import { useEffect } from "react";import { act, renderWithProviders, screen } from "__support__/ui";+import { Outlet, Route } from "metabase/router";import { checkNotNull } from "metabase/utils/types";-import { Outlet } from "./Outlet";-import { Route } from "./route";import { useRoutePathname } from "./use-route-leave-blocker";const Parent = () => (diff --git a/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx b/frontend/src/metabase/router/router-engine.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/router/v7/v7-engine.unit.spec.tsxrename to frontend/src/metabase/router/router-engine.unit.spec.tsxdiff --git a/frontend/src/metabase/router/router-link.tsx b/frontend/src/metabase/router/router-link.tsxindex 01cb5385128..a2d28060e40 100644--- a/frontend/src/metabase/router/router-link.tsx+++ b/frontend/src/metabase/router/router-link.tsx@@ -1,14 +1,14 @@import { type Ref, forwardRef } from "react";import {- Link as V7Link,- type LinkProps as V7LinkProps,- NavLink as V7NavLink,+ Link as ReactRouterLink,+ type LinkProps as ReactRouterLinkProps,+ NavLink as ReactRouterNavLink,useInRouterContext,} from "react-router";import type { RouterLinkProps } from "./types";-function hrefFor(target: V7LinkProps["to"]): string {+function hrefFor(target: ReactRouterLinkProps["to"]): string {if (typeof target === "string") {return target;}@@ -35,7 +35,10 @@ function toRootRelative(pathname: string): string {return isAlreadyAnchored || hasScheme ? pathname : `/${pathname}`;}-function toV7Target(to: V3To): { to: V7LinkProps["to"]; state?: unknown } {+function toReactRouterTarget(to: V3To): {+ to: ReactRouterLinkProps["to"];+ state?: unknown;+} {if (to == null) {return { to: "" };}@@ -83,14 +86,14 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>(return <a {...rest} ref={linkRef} />;}- const { to: v7To, state } = toV7Target(to);+ const { to: reactRouterTo, state } = toReactRouterTarget(to);// v7's `<Link>` reads router context and throws without one. A component// rendered in isolation (common in unit tests) has no router, so fall back to// a plain anchor with the resolved href. The real app always mounts a router,// so this path never runs there.if (!inRouter) {- return <a {...rest} href={hrefFor(v7To)} ref={linkRef} />;+ return <a {...rest} href={hrefFor(reactRouterTo)} ref={linkRef} />;}// v3's `<Link>` highlighted itself when its route was active via@@ -100,9 +103,9 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>(if (activeClassName != null || activeStyle != null) {const { className, style, ...navRest } = rest;return (- <V7NavLink+ <ReactRouterNavLink{...navRest}- to={v7To}+ to={reactRouterTo}state={state}ref={linkRef}end={onlyActiveOnIndex}@@ -118,6 +121,13 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>();}- return <V7Link {...rest} to={v7To} state={state} ref={linkRef} />;+ return (+ <ReactRouterLink+ {...rest}+ to={reactRouterTo}+ state={state}+ ref={linkRef}+ />+ );},);diff --git a/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx b/frontend/src/metabase/router/router-listen.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/router/v7/router-listen.unit.spec.tsxrename to frontend/src/metabase/router/router-listen.unit.spec.tsxdiff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.tsindex 07198a7cd6d..8fc58ab0bed 100644--- a/frontend/src/metabase/router/types.ts+++ b/frontend/src/metabase/router/types.ts@@ -4,25 +4,19 @@ import type {FunctionComponent,HTMLProps,} from "react";+import type { Location, Path } from "react-router";-/**- * The pathname, search, and hash values of a URL.- *- * @see https://api.reactrouter.com/v7/interfaces/react-router.Path.html- */-export interface Path {- pathname: string;- search: string;- hash: string;-}--/**- * Describes a location that is the destination of some navigation, used in- * Link, useNavigate, etc.- *- * @see https://api.reactrouter.com/v7/types/react-router.To.html- */-export type To = string | Partial<Path>;+export type {+ Location,+ NavigateFunction,+ NavigateOptions,+ Params,+ Path,+ RelativeRoutingType,+ SetURLSearchParams,+ To,+ URLSearchParamsInit,+} from "react-router";/*** The navigation action that produced a location.@@ -36,29 +30,12 @@ export type Action = "POP" | "PUSH" | "REPLACE";*/export type LocationState = any;-/**- * An entry in a history stack. Read the query string off `search`, either with- * the `useSearchParams` hook or by constructing a `URLSearchParams`.- *- * @see https://api.reactrouter.com/v7/interfaces/react-router.Location.html- */-export interface Location {- pathname: string;- search: string;- hash: string;- state: LocationState;- key: string;-}-/*** A location to navigate to, as an object. Carries the query as a `search`* string, the only form v7 reads; call sites that hold a query object serialize* it with `queryToSearch` first.*/-export interface LocationDescriptorObject {- pathname?: string;- search?: string;- hash?: string;+export interface LocationDescriptorObject extends Partial<Path> {state?: LocationState;}@@ -98,86 +75,18 @@ export interface History {getCurrentLocation(): Location;}-/**- * Whether a relative `to` is resolved against the route hierarchy or against- * the current URL path.- *- * @see https://api.reactrouter.com/v7/types/react-router.RelativeRoutingType.html- */-export type RelativeRoutingType = "route" | "path";--/**- * Options for the `navigate` function, mirroring react-router v7's- * `NavigateOptions`.- *- * @see https://api.reactrouter.com/v7/interfaces/react-router.NavigateOptions.html- */-export interface NavigateOptions {- replace?: boolean;- state?: unknown;- relative?: RelativeRoutingType;-}--/**- * The interface for the `navigate` function returned from `useNavigate`.- *- * @see https://api.reactrouter.com/v7/interfaces/react-router.NavigateFunction.html- */-export interface NavigateFunction {- (to: To, options?: NavigateOptions): void;- (delta: number): void;-}--/**- * The parameters that were parsed from the URL path.- *- * @see https://api.reactrouter.com/v7/types/react-router.Params.html- */-export type Params<Key extends string = string> = {- readonly [key in Key]: string | undefined;-};--/**- * Accepted inputs for building search params, mirroring react-router v7's- * `URLSearchParamsInit`.- *- * @see https://api.reactrouter.com/v7/types/react-router.URLSearchParamsInit.html- */-export type URLSearchParamsInit =- | string- | URLSearchParams- | [string, string][]- | Record<string, string | string[]>;--/**- * Sets new search params and causes a navigation when called.- *- * @see https://api.reactrouter.com/v7/types/react-router.SetURLSearchParams.html- */-export type SetURLSearchParams = (- nextInit?:- | URLSearchParamsInit- | ((prev: URLSearchParams) => URLSearchParamsInit),- navigateOptions?: NavigateOptions,-) => void;-/*** A route's component. v3 accepted a class or function component; kept for the* call sites that annotate the injected `route` / `routes` props.*/export type RouteComponent = ComponentClass<any> | FunctionComponent<any>;-/**- * v3's function form of a `<Link to>`, kept because `RouterLink` still handles it.- */-type ToLocationFunction = (location: Location) => LocationDescriptor;-/*** Props of the app's `<Link>`, re-homed from v3's `LinkProps`. `RouterLink` reads* `to` (and the active-styling props) and forwards the rest to the anchor.*/export interface RouterLinkProps extends HTMLProps<any> {- to: LocationDescriptor | ToLocationFunction;+ to: LocationDescriptor;activeClassName?: string;activeStyle?: CSSProperties;onlyActiveOnIndex?: boolean;diff --git a/frontend/src/metabase/router/use-location.unit.spec.tsx b/frontend/src/metabase/router/use-location.unit.spec.tsxindex 2fe292901ae..cec940581ca 100644--- a/frontend/src/metabase/router/use-location.unit.spec.tsx+++ b/frontend/src/metabase/router/use-location.unit.spec.tsx@@ -1,9 +1,7 @@import { MemoryRouter } from "react-router";import { renderWithProviders, screen } from "__support__/ui";--import { Route } from "./route";-import { useLocation } from "./use-location";+import { Route, useLocation } from "metabase/router";function LocationProbe() {const location = useLocation();diff --git a/frontend/src/metabase/router/use-location.ts b/frontend/src/metabase/router/use-maybe-location.tssimilarity index 55%rename from frontend/src/metabase/router/use-location.tsrename to frontend/src/metabase/router/use-maybe-location.tsindex c5706270f9a..45232850510 100644--- a/frontend/src/metabase/router/use-location.ts+++ b/frontend/src/metabase/router/use-maybe-location.ts@@ -1,21 +1,10 @@import { useContext } from "react";-import {- type Location,- UNSAFE_LocationContext,- useLocation,-} from "react-router";--/**- * react-router v7's `useLocation`.- *- * @see https://reactrouter.com/7.18.1/api/hooks/useLocation- */-export { useLocation };+import { type Location, UNSAFE_LocationContext } from "react-router";/*** Like `useLocation`, but returns `null` when rendered outside a router instead* of throwing. For code shared between the routed app and the SDK, where the- * facade router may be absent.+ * app's router may be absent.*/export function useMaybeLocation(): Location | null {return useContext(UNSAFE_LocationContext)?.location ?? null;diff --git a/frontend/src/metabase/router/use-navigate.ts b/frontend/src/metabase/router/use-navigate.tsdeleted file mode 100644index f6a36d63011..00000000000--- a/frontend/src/metabase/router/use-navigate.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * react-router v7's `useNavigate`.- *- * - `navigate(to, { replace?, state?, relative? })` pushes (or replaces) the location.- * - `navigate(delta)` moves through the history stack (e.g. `navigate(-1)`).- *- * A relative `to` (`".."`, `"child"`) resolves against the route the calling- * component renders in. The facade used to resolve it against the deepest- * matched route instead, so a component rendered by a parent route climbed from- * the leaf; v7 climbs from the component's own route.- *- * @see https://reactrouter.com/7.18.1/api/hooks/useNavigate- */-export { useNavigate } from "react-router";diff --git a/frontend/src/metabase/router/use-navigate.unit.spec.tsx b/frontend/src/metabase/router/use-navigate.unit.spec.tsxindex c9b1b755a91..0b656911e01 100644--- a/frontend/src/metabase/router/use-navigate.unit.spec.tsx+++ b/frontend/src/metabase/router/use-navigate.unit.spec.tsx@@ -2,9 +2,7 @@ import userEvent from "@testing-library/user-event";import { useState } from "react";import { renderWithProviders, screen } from "__support__/ui";--import { Route } from "./route";-import { useNavigate } from "./use-navigate";+import { Route, useNavigate } from "metabase/router";function NavigateProbe() {const navigate = useNavigate();diff --git a/frontend/src/metabase/router/use-navigation-type.ts b/frontend/src/metabase/router/use-navigation-type.tsdeleted file mode 100644index 49a8bd42ad0..00000000000--- a/frontend/src/metabase/router/use-navigation-type.ts+++ /dev/null@@ -1,13 +0,0 @@-import { useNavigationType as useV7NavigationType } from "react-router";--import type { Action } from "./types";--/**- * react-router v7's `useNavigationType`: the navigation that produced the- * current location. Replaces v3's `location.action`.- *- * @see https://reactrouter.com/7.18.1/api/hooks/useNavigationType- */-export function useNavigationType(): Action {- return useV7NavigationType();-}diff --git a/frontend/src/metabase/router/use-params.ts b/frontend/src/metabase/router/use-params.tsdeleted file mode 100644index 390818d99a8..00000000000--- a/frontend/src/metabase/router/use-params.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * react-router v7's `useParams`. Values are URI-decoded and the wildcard match is- * exposed under v7's `*` key (v3 called it `splat`).- *- * @see https://reactrouter.com/7.18.1/api/hooks/useParams- */-export { useParams } from "react-router";diff --git a/frontend/src/metabase/router/use-params.unit.spec.tsx b/frontend/src/metabase/router/use-params.unit.spec.tsxindex 53c38601406..7aabe06bf05 100644--- a/frontend/src/metabase/router/use-params.unit.spec.tsx+++ b/frontend/src/metabase/router/use-params.unit.spec.tsx@@ -1,13 +1,11 @@import {MemoryRouter,- Route as V7Route,- Routes as V7Routes,+ Route as ReactRouterRoute,+ Routes as ReactRouterRoutes,} from "react-router";import { renderWithProviders, screen } from "__support__/ui";--import { Route } from "./route";-import { useParams } from "./use-params";+import { Route, useParams } from "metabase/router";function ParamsProbe() {const { segmentId, fieldId } = useParams();@@ -59,9 +57,9 @@ describe("router/useParams", () => {it("works outside the facade route tree, reading the host's own match", () => {renderWithProviders(<MemoryRouter initialEntries={["/files/a/b"]}>- <V7Routes>- <V7Route path="files/*" element={<SplatProbe />} />- </V7Routes>+ <ReactRouterRoutes>+ <ReactRouterRoute path="files/*" element={<SplatProbe />} />+ </ReactRouterRoutes></MemoryRouter>,);diff --git a/frontend/src/metabase/router/use-route-leave-blocker.ts b/frontend/src/metabase/router/use-route-leave-blocker.tsindex 30f8d982b78..3da6b0f539b 100644--- a/frontend/src/metabase/router/use-route-leave-blocker.ts+++ b/frontend/src/metabase/router/use-route-leave-blocker.ts@@ -2,9 +2,9 @@ import { useContext, useId, useRef } from "react";import type { Blocker, BlockerFunction } from "react-router";import { UNSAFE_RouteContext } from "react-router";-import { useGuardedBlocker } from "./v7/route-leave-guards";+import { useGuardedBlocker } from "./route-leave-guards";-export { useIsNavigationHeld } from "./v7/route-leave-guards";+export { useIsNavigationHeld } from "./route-leave-guards";/*** Block navigation that leaves the route this component renders in, replacingdiff --git a/frontend/src/metabase/router/use-route-leave-blocker.unit.spec.tsx b/frontend/src/metabase/router/use-route-leave-blocker.unit.spec.tsxindex 77bb38b0047..a1b0af3a40a 100644--- a/frontend/src/metabase/router/use-route-leave-blocker.unit.spec.tsx+++ b/frontend/src/metabase/router/use-route-leave-blocker.unit.spec.tsx@@ -2,9 +2,9 @@ import userEvent from "@testing-library/user-event";import type { PropsWithChildren } from "react";import { act, renderWithProviders, screen } from "__support__/ui";+import { Route } from "metabase/router";import { checkNotNull } from "metabase/utils/types";-import { Route } from "./route";import { useRouteLeaveBlocker } from "./use-route-leave-blocker";const shouldBlock = jest.fn();diff --git a/frontend/src/metabase/router/use-search-params.ts b/frontend/src/metabase/router/use-search-params.tsdeleted file mode 100644index 3924745a80e..00000000000--- a/frontend/src/metabase/router/use-search-params.ts+++ /dev/null@@ -1,64 +0,0 @@-import { useCallback, useMemo, useRef } from "react";--import type { SetURLSearchParams, URLSearchParamsInit } from "./types";-import { useLocation } from "./use-location";-import { useNavigate } from "./use-navigate";-import { createSearchParams, getSearchParamsForLocation } from "./utils";--/**- * react-router v7's `useSearchParams`, implemented over the v3 location's query- * string. Returns a `URLSearchParams` view plus a setter that navigates to the- * current path with the updated query string (a push by default).- *- * Like v7, the setter navigates to search only, so any existing hash is dropped.- * v7 does this by navigating to `"?" + params`, which resolves to the current- * path with an empty hash.- *- * `defaultInit` fills in keys the current URL is missing, matching v7. As in v7,- * the defaults are captured once and stop being merged once `setSearchParams`- * has been called, so a value can then be removed with `setSearchParams({})`.- *- * @see https://reactrouter.com/7.18.1/api/hooks/useSearchParams- */-export function useSearchParams(- defaultInit?: URLSearchParamsInit,-): readonly [URLSearchParams, SetURLSearchParams] {- const location = useLocation();- const navigate = useNavigate();-- const defaultSearchParamsRef = useRef(createSearchParams(defaultInit));- const hasSetSearchParamsRef = useRef(false);-- const searchParams = useMemo(- () =>- getSearchParamsForLocation(- location.search,- hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current,- ),- [location.search],- );-- const setSearchParams = useCallback<SetURLSearchParams>(- (nextInit, navigateOptions) => {- const params = createSearchParams(- typeof nextInit === "function"- ? // Hand the updater a clone so it cannot mutate the instance the- // component currently holds (matching v7).- nextInit(new URLSearchParams(searchParams))- : nextInit,- );- hasSetSearchParamsRef.current = true;- const search = params.toString();- navigate(- {- pathname: location.pathname,- search: search ? `?${search}` : "",- },- navigateOptions,- );- },- [navigate, location.pathname, searchParams],- );-- return [searchParams, setSearchParams] as const;-}diff --git a/frontend/src/metabase/router/use-search-params.unit.spec.tsx b/frontend/src/metabase/router/use-search-params.unit.spec.tsxindex 0ce857b294d..fb1a3a6bf63 100644--- a/frontend/src/metabase/router/use-search-params.unit.spec.tsx+++ b/frontend/src/metabase/router/use-search-params.unit.spec.tsx@@ -1,9 +1,7 @@import userEvent from "@testing-library/user-event";import { act, renderWithProviders, screen } from "__support__/ui";--import { Route } from "./route";-import { useSearchParams } from "./use-search-params";+import { Route, useSearchParams } from "metabase/router";function SearchParamsProbe() {const [searchParams, setSearchParams] = useSearchParams();diff --git a/frontend/src/metabase/router/utils.ts b/frontend/src/metabase/router/utils.tsdeleted file mode 100644index 8baee041086..00000000000--- a/frontend/src/metabase/router/utils.ts+++ /dev/null@@ -1,50 +0,0 @@-import type { URLSearchParamsInit } from "./types";--/**- * Build a `URLSearchParams`, mirroring react-router v7's `createSearchParams`.- */-export function createSearchParams(- init: URLSearchParamsInit = "",-): URLSearchParams {- if (- typeof init === "string" ||- Array.isArray(init) ||- init instanceof URLSearchParams- ) {- return new URLSearchParams(init);- }-- const params = new URLSearchParams();- Object.entries(init).forEach(([key, value]) => {- if (Array.isArray(value)) {- value.forEach((entry) => params.append(key, entry));- } else {- params.append(key, value);- }- });- return params;-}--/**- * Build the search params for a location, filling in any default key the- * location does not already carry, mirroring react-router v7's- * `getSearchParamsForLocation`.- */-export function getSearchParamsForLocation(- locationSearch: string,- defaultSearchParams: URLSearchParams | null,-): URLSearchParams {- const searchParams = createSearchParams(locationSearch);-- if (defaultSearchParams) {- defaultSearchParams.forEach((_value, key) => {- if (!searchParams.has(key)) {- defaultSearchParams.getAll(key).forEach((value) => {- searchParams.append(key, value);- });- }- });- }-- return searchParams;-}diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsxdeleted file mode 100644index 9d12d71e992..00000000000--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx+++ /dev/null@@ -1,108 +0,0 @@-import type { PropsWithChildren } from "react";-import { useLayoutEffect, useState } from "react";-import { type DataRouter, RouterProvider } from "react-router";--import { getBasename } from "metabase/utils/basename";--import {- type MemoryTestRouterHolder,- createAppRouter,- createMemoryAppRouter,-} from "./create-router";-import type { LocationMirror } from "./location-mirror";--/**- * Mirrors every location out to `onLocationChange`, which is how the app emits- * LOCATION_CHANGE on navigation (see `createLocationMirror`). Replaces v3's- * `syncHistoryWithStore`.- *- * Subscribing to the router rather than reading the rendered location matters- * because v3 dispatched LOCATION_CHANGE as part of the transition rather than- * after a render. Thunks read the store synchronously right after navigating, so- * a store that lags a render makes them push a stale location and clobber query- * params that were just set.- */-function useLocationMirror(- router: DataRouter,- onLocationChange?: LocationMirror,-): void {- useLayoutEffect(() => {- if (!onLocationChange) {- return;- }- // The router notifies its subscribers on every state update, not only on a- // location change, and replays the state it initialized with to the first- // subscriber. Key on the location so neither is mirrored twice.- let lastKey: string | null = null;-- const mirror = ({ location }: DataRouter["state"]) => {- if (location.key === lastKey) {- return;- }- lastKey = location.key;- onLocationChange(location);- };-- mirror(router.state);- return router.subscribe(mirror);- }, [router, onLocationChange]);-}--/**- * react-router v7 hosting the app as a data router. The whole facade tree goes- * in as real data routes, so there is no descendant `<Routes>` left. No route- * has a loader, `lazy`, or middleware yet: adding those per subtree is what- * DEV-2291 does from here.- *- * `useTransitions={false}` keeps navigation committing synchronously.- * react-router otherwise marks its own location update as a transition, which in- * a production React build deprioritises it so it can commit long after the click- * that caused it. v3 navigated synchronously, and the app was written against- * that: a navigation that lands mid-interaction remounts whatever is on screen,- * which silently discarded state such as the text typed into a modal that was- * opened right after clicking a link.- *- * `onLocationChange` is how the location reaches redux: the app passes- * `createLocationMirror(store.dispatch)`, so the router itself stays unaware of- * the store.- */-export function RouterProviderV7({- children,- onLocationChange,-}: PropsWithChildren<{ onLocationChange?: LocationMirror }>): JSX.Element {- const [router] = useState(() =>- createAppRouter(children, getBasename() || undefined),- );- useLocationMirror(router, onLocationChange);-- return <RouterProvider router={router} useTransitions={false} />;-}--/**- * The v7 engine hosted on an in-memory history, for tests. Mirrors what- * `renderWithProviders({ withRouter: true })` mounts, including navigation- * blocking. Pass `router` to drive and inspect it from outside the tree.- */-export function RouterProviderV7Memory({- children,- initialRoute,- basename,- routerHolder,- onLocationChange,-}: PropsWithChildren<{- initialRoute: string;- basename?: string;- routerHolder?: MemoryTestRouterHolder;- onLocationChange?: LocationMirror;-}>): JSX.Element {- const [router] = useState(() => {- const created = createMemoryAppRouter(children, initialRoute, basename);- if (routerHolder) {- routerHolder.current = created;- }- return created;- });- useLocationMirror(router, onLocationChange);-- return <RouterProvider router={router} useTransitions={false} />;-}diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsxindex 79589b54c4c..5a95e23da3d 100644--- a/frontend/test/__support__/ui.tsx+++ b/frontend/test/__support__/ui.tsx@@ -46,9 +46,9 @@ import {type LocationDescriptor,type MemoryTestRouterHolder,Route,- RouterProviderV7Memory,+ RouterProviderMemory,createLocationMirror,- createV7Navigator,+ createRouterNavigator,routerMiddleware,toFacadeLocation,toNavigateArgs,@@ -216,7 +216,7 @@ export function getTestStoreAndWrapper({reducers = { ...reducers, ...customReducers };}- const routerNavigator = withRouter ? createV7Navigator() : undefined;+ const routerNavigator = withRouter ? createRouterNavigator() : undefined;const storeMiddleware = _.compact([Api.middleware,routerNavigator && routerMiddleware(routerNavigator),@@ -425,7 +425,7 @@ function childrenAreRouteTree(children: React.ReactNode): boolean {return true;}// Routes are often grouped in a fragment (`<><Route/><Route/></>`); descend- // so the tree is still recognized, matching how `mapToV7` unwraps fragments.+ // so the tree is still recognized, matching how react-router unwraps fragments.if (child.type === Fragment) {return childrenAreRouteTree(child.props.children);}@@ -462,13 +462,13 @@ function MaybeRouter({<Route path="*" element={children} />);return (- <RouterProviderV7Memory+ <RouterProviderMemoryinitialRoute={initialRoute}routerHolder={routerHolder}onLocationChange={onLocationChange}>{content}- </RouterProviderV7Memory>+ </RouterProviderMemory>);}