Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Add the react-router v7 engine behind a flag (#78020)

Romeo Van Snickf8230a5b5647
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index 29793329f01..13008bab774 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -38,7 +38,12 @@ import { MetabotProvider } from "metabase/metabot/context";
import { PLUGIN_APP_INIT_FUNCTIONS } from "metabase/plugins";
import { MetabaseReduxProvider } from "metabase/redux";
import { refreshSiteSettings } from "metabase/redux/settings";
-import { syncHistoryWithStore, useRouterHistory } from "metabase/router";
+import {
+ getRouterEngine,
+ syncHistoryWithStore,
+ useRouterHistory,
+} from "metabase/router";
+import { createV7Navigator } from "metabase/router/v7/navigator";
import { getUserId } from "metabase/selectors/user";
import { GlobalStyles } from "metabase/styled-components/containers/GlobalStyles";
import { PortalContainer } from "metabase/ui";
@@ -57,17 +62,23 @@ import { OverlayStackProvider } from "./ui/components/overlays/overlay-stack";
setBasename(window.MetabaseRoot);
-// eslint-disable-next-line react-hooks/rules-of-hooks
-const browserHistory = useRouterHistory(createHistory)({
- basename: getBasename(),
-});
+// The v3 engine drives navigation through a `history@3` instance; the v7 engine
+// owns its own history and only needs a navigator adapter for redux. Kept for
+// instant rollback via the `use-v7-router` flag.
+const isV7Router = getRouterEngine() === "v7";
+const browserHistory = isV7Router
+ ? undefined
+ : // eslint-disable-next-line react-hooks/rules-of-hooks
+ useRouterHistory(createHistory)({ basename: getBasename() });
initializePlugins();
function _init(reducers, getRoutes, callback) {
- const store = getStore(reducers, browserHistory);
+ const store = getStore(reducers, browserHistory ?? createV7Navigator());
const routes = getRoutes(store);
- const syncedHistory = syncHistoryWithStore(browserHistory, store);
+ const syncedHistory = browserHistory
+ ? syncHistoryWithStore(browserHistory, store)
+ : undefined;
createSnowplowTracker(() => getUserId(store.getState()));
initMetaplow({
@@ -80,13 +91,28 @@ function _init(reducers, getRoutes, callback) {
initTracing();
// Rotate trace ID on route changes so all API calls within
// a single page view share one trace.
- syncedHistory.listen(() => rotateTraceId());
+ if (syncedHistory) {
+ syncedHistory.listen(() => rotateTraceId());
+ } else {
+ // v7 mirrors the location into state.routing; rotate when it changes.
+ let lastPathname;
+ store.subscribe(() => {
+ const { pathname } =
+ store.getState().routing.locationBeforeTransitions ?? {};
+ if (pathname !== lastPathname) {
+ lastPathname = pathname;
+ rotateTraceId();
+ }
+ });
+ }
}
initializeInteractiveEmbedding(store.dispatch);
const root = createRoot(document.getElementById("root"));
+ const app = <RouterProvider>{routes}</RouterProvider>;
+
root.render(
<MetabaseReduxProvider store={store}>
<EmotionCacheProvider>
@@ -96,9 +122,13 @@ function _init(reducers, getRoutes, callback) {
<GlobalStyles />
{createPortal(<PortalContainer />, document.body)}
<MetabotProvider>
- <HistoryProvider history={syncedHistory}>
- <RouterProvider>{routes}</RouterProvider>
- </HistoryProvider>
+ {syncedHistory ? (
+ <HistoryProvider history={syncedHistory}>
+ {app}
+ </HistoryProvider>
+ ) : (
+ app
+ )}
</MetabotProvider>
</AppThemeProvider>
</OverlayStackProvider>
diff --git a/frontend/src/metabase/router/Outlet.tsx b/frontend/src/metabase/router/Outlet.tsx
index 7140a6f089c..d99655ac979 100644
--- a/frontend/src/metabase/router/Outlet.tsx
+++ b/frontend/src/metabase/router/Outlet.tsx
@@ -3,9 +3,9 @@ import { createContext, useContext } from "react";
import type { Route } from "./route";
-const OutletContext = createContext<ReactNode>(null);
+export const OutletContext = createContext<ReactNode>(null);
-const RouteContext = createContext<Route | null>(null);
+export const RouteContext = createContext<Route | null>(null);
/**
* The route matched for the nearest `element`-based route ancestor. On v3 the
diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsx
index e3d5dc1317a..0546af6826d 100644
--- a/frontend/src/metabase/router/RouterProvider.tsx
+++ b/frontend/src/metabase/router/RouterProvider.tsx
@@ -3,12 +3,14 @@ import { type PropsWithChildren, createContext, useMemo } from "react";
import { useHistory } from "metabase/history";
+import { type RouterEngine, getRouterEngine } from "./engine";
import {
ReactRouterRoute,
Router,
type WithRouterProps,
reactRouterWithRouter,
} from "./react-router";
+import { RouterProviderV7 } from "./v7/RouterProviderV7";
type RouterContextType = WithRouterProps;
@@ -53,7 +55,7 @@ type RouterProviderProps = {
* component that establishes the router context, so it cannot itself consume that
* context through `<Outlet/>`.
*/
-export const RouterProvider = ({
+const RouterProviderV3 = ({
children,
}: PropsWithChildren<RouterProviderProps>) => {
const { history } = useHistory();
@@ -65,3 +67,26 @@ export const RouterProvider = ({
</Router>
);
};
+
+type RouterProviderPropsWithEngine = RouterProviderProps & {
+ /**
+ * Which engine hosts the app. Defaults to the `use-v7-router` flag; tests pass
+ * it explicitly to exercise both engines. Goes away with the v3 engine.
+ */
+ engine?: RouterEngine;
+};
+
+/**
+ * Hosts the app on either engine. On v7 the facade hooks read the same
+ * `RouterContext`, filled per route by the `RouterBridge` instead of v3's
+ * `withRouter`, so nothing downstream changes.
+ */
+export const RouterProvider = ({
+ children,
+ engine = getRouterEngine(),
+}: PropsWithChildren<RouterProviderPropsWithEngine>) => {
+ if (engine === "v7") {
+ return <RouterProviderV7>{children}</RouterProviderV7>;
+ }
+ return <RouterProviderV3>{children}</RouterProviderV3>;
+};
diff --git a/frontend/src/metabase/router/engine.ts b/frontend/src/metabase/router/engine.ts
new file mode 100644
index 00000000000..9db972707cc
--- /dev/null
+++ b/frontend/src/metabase/router/engine.ts
@@ -0,0 +1,14 @@
+export type RouterEngine = "v3" | "v7";
+
+/**
+ * Which router engine to run: the legacy react-router v3 engine, or the v7
+ * engine behind the `use-v7-router` flag.
+ *
+ * Read straight from `window.MetabaseBootstrap` rather than the redux settings
+ * slice so it is available at mount, before the store exists (the router is
+ * wired at the very top of `app.js`). Toggling the setting off is the instant
+ * rollback path.
+ */
+export function getRouterEngine(): RouterEngine {
+ return window.MetabaseBootstrap?.["use-v7-router"] === true ? "v7" : "v3";
+}
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 8eb1c6a7c41..c9eced48a1a 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -1,3 +1,4 @@
+export * from "./engine";
export * from "./Link";
export * from "./middleware";
export * from "./navigation";
diff --git a/frontend/src/metabase/router/middleware.ts b/frontend/src/metabase/router/middleware.ts
index ad0e7a2e4e9..74ae765dae2 100644
--- a/frontend/src/metabase/router/middleware.ts
+++ b/frontend/src/metabase/router/middleware.ts
@@ -7,6 +7,16 @@ import {
type CallHistoryMethodAction,
} from "./navigation";
+/**
+ * The slice of `history` the middleware drives. v3's `History` satisfies it, and
+ * the v7 navigator adapter implements exactly these, so the middleware is engine
+ * agnostic and the engine swap only changes which navigator is passed in.
+ */
+export type RouterNavigator = Pick<
+ History,
+ "push" | "replace" | "go" | "goBack" | "goForward"
+>;
+
function isCallHistoryMethod(
action: unknown,
): action is CallHistoryMethodAction {
@@ -25,18 +35,18 @@ function isCallHistoryMethod(
* the matching method to history. These actions never reach the reducers, just
* like the package it replaces.
*/
-export function routerMiddleware(history: History): Middleware {
+export function routerMiddleware(navigator: RouterNavigator): Middleware {
return () => (next) => (action) => {
if (!isCallHistoryMethod(action)) {
return next(action);
}
match(action.payload)
- .with({ method: "push" }, ({ args }) => history.push(args[0]))
- .with({ method: "replace" }, ({ args }) => history.replace(args[0]))
- .with({ method: "go" }, ({ args }) => history.go(args[0]))
- .with({ method: "goBack" }, () => history.goBack())
- .with({ method: "goForward" }, () => history.goForward())
+ .with({ method: "push" }, ({ args }) => navigator.push(args[0]))
+ .with({ method: "replace" }, ({ args }) => navigator.replace(args[0]))
+ .with({ method: "go" }, ({ args }) => navigator.go(args[0]))
+ .with({ method: "goBack" }, () => navigator.goBack())
+ .with({ method: "goForward" }, () => navigator.goForward())
.exhaustive();
};
}
diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsx
new file mode 100644
index 00000000000..ffddb84d927
--- /dev/null
+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx
@@ -0,0 +1,116 @@
+import type { Location as HistoryLocation, LocationDescriptor } from "history";
+import { type ReactNode, useContext, useMemo } from "react";
+import {
+ UNSAFE_RouteContext,
+ type NavigateFunction as V7NavigateFunction,
+ Outlet as V7Outlet,
+ useNavigationType,
+ useLocation as useV7Location,
+ useNavigate as useV7Navigate,
+ useParams as useV7Params,
+} from "react-router-v7";
+
+import { OutletContext, RouteContext } from "../Outlet";
+import { RouterContext } from "../RouterProvider";
+import type {
+ InjectedRouter,
+ PlainRoute,
+ WithRouterProps,
+} from "../react-router";
+import type { Route } from "../route";
+
+import { toV3Location } from "./location";
+import { toNavigateArgs } from "./navigator";
+
+/**
+ * Runs as the `element` of every v7 route and republishes v7's location,
+ * params, matched-route branch, and an imperative-router shim into the shared
+ * `RouterContext` (and the `Outlet`/`Route` contexts). The facade hooks
+ * (`useLocation`, `useParams`, `useNavigate`, `useRouter`, `withRouteProps`)
+ * read that context unchanged, so nothing downstream can tell which engine it
+ * runs on. Deleted with the v3 engine in Phase 4.
+ */
+export function RouterBridge({
+ v3Element,
+}: {
+ v3Element: ReactNode;
+}): JSX.Element {
+ const v7Location = useV7Location();
+ const navigate = useV7Navigate();
+ const action = useNavigationType();
+ // v7's `useParams` returns v7's readonly `Params`; the context wants v3's shape,
+ // which is structurally the same string map.
+ const params = useV7Params() as WithRouterProps["params"];
+
+ // `useMatches` is data-router-only, so read the matched branch from the route
+ // context that also drives `<Outlet>` (available in declarative mode). Each
+ // route keeps its v3 path on `handle`, which the facade hooks match against.
+ const { matches } = useContext(UNSAFE_RouteContext);
+ const routes = useMemo<PlainRoute[]>(
+ () =>
+ matches.map((match) => {
+ // `handle` is typed `unknown`; we only ever put `{ v3Path }` on it.
+ const handle = match.route.handle as { v3Path?: string } | undefined;
+ // The facade hooks read only `route.path`, so a `{ path }` stub is enough.
+ return { path: handle?.v3Path } as PlainRoute;
+ }),
+ [matches],
+ );
+
+ const location = useMemo<HistoryLocation>(
+ () => toV3Location(v7Location, action),
+ [v7Location, action],
+ );
+
+ const router = useMemo<InjectedRouter>(
+ () => makeRouterShim(navigate),
+ [navigate],
+ );
+
+ const value = useMemo<WithRouterProps>(
+ () => ({ router, location, params, routes }),
+ [router, location, params, routes],
+ );
+
+ // The injected `route` prop / `useRoute()`: consumers only read it to hand back
+ // to `setRouteLeaveHook` (a no-op on v7), so the leaf match's `{ path }` is
+ // enough. Cast because the facade types the injected route object as `Route`.
+ const route = (routes.at(-1) ?? null) as Route | null;
+
+ return (
+ <RouterContext.Provider value={value}>
+ <RouteContext.Provider value={route}>
+ <OutletContext.Provider value={<V7Outlet />}>
+ {v3Element}
+ </OutletContext.Provider>
+ </RouteContext.Provider>
+ </RouterContext.Provider>
+ );
+}
+
+/**
+ * The v3 `InjectedRouter` (`router.push/replace/go/...`) reimplemented over v7's
+ * `navigate`. The facade's `useNavigate` has already resolved relative targets to
+ * absolute paths before calling `push`/`replace`, so these pass straight through.
+ * `setRouteLeaveHook` is a no-op for now: navigation blocking is data-router-only,
+ * restored on the declarative engine via a blocking history in DEV-2374.
+ */
+function makeRouterShim(navigate: V7NavigateFunction): InjectedRouter {
+ const href = (location: LocationDescriptor) =>
+ typeof location === "string"
+ ? location
+ : `${location.pathname ?? ""}${location.search ?? ""}${location.hash ?? ""}`;
+
+ return {
+ push: (location) => navigate(...toNavigateArgs(location)),
+ replace: (location) =>
+ navigate(...toNavigateArgs(location, { replace: true })),
+ go: (n) => navigate(n),
+ goBack: () => navigate(-1),
+ goForward: () => navigate(1),
+ setRouteLeaveHook: () => () => undefined,
+ createPath: href,
+ createHref: href,
+ isActive: () => false,
+ };
+}
diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
new file mode 100644
index 00000000000..2b274cb105a
--- /dev/null
+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
@@ -0,0 +1,50 @@
+import type { PropsWithChildren } from "react";
+import { BrowserRouter, MemoryRouter, Routes } from "react-router-v7";
+
+import { getBasename } from "metabase/utils/basename";
+
+import { V7ReduxBridge } from "./V7ReduxBridge";
+import { mapToV7 } from "./map-to-v7";
+
+/**
+ * The v7 route tree: the facade tree mapped to real v7 routes and rendered by
+ * `<Routes>`, plus the redux bridge that mirrors location into `state.routing`
+ * and lets `dispatch(push(...))` drive the router. Kept separate from the history
+ * provider below so tests can host the same tree under a `<MemoryRouter>`.
+ */
+export function V7RouterTree({ children }: PropsWithChildren): JSX.Element {
+ return (
+ <>
+ <V7ReduxBridge />
+ <Routes>{mapToV7(children)}</Routes>
+ </>
+ );
+}
+
+/**
+ * react-router v7 hosting the app, declarative mode (Phase 3.1). Replaces the v3
+ * `<Router>` + `useRouterHistory` + `syncHistoryWithStore` stack behind the
+ * `use-v7-router` flag.
+ */
+export function RouterProviderV7({ children }: PropsWithChildren): JSX.Element {
+ return (
+ <BrowserRouter basename={getBasename() || undefined}>
+ <V7RouterTree>{children}</V7RouterTree>
+ </BrowserRouter>
+ );
+}
+
+/**
+ * The v7 engine hosted on an in-memory history, for tests. Mirrors what
+ * `renderWithProviders({ routerEngine: "v7" })` mounts.
+ */
+export function RouterProviderV7Memory({
+ children,
+ initialRoute,
+}: PropsWithChildren<{ initialRoute: string }>): JSX.Element {
+ return (
+ <MemoryRouter initialEntries={[initialRoute]}>
+ <V7RouterTree>{children}</V7RouterTree>
+ </MemoryRouter>
+ );
+}
diff --git a/frontend/src/metabase/router/v7/V7ReduxBridge.tsx b/frontend/src/metabase/router/v7/V7ReduxBridge.tsx
new file mode 100644
index 00000000000..206f9e6f775
--- /dev/null
+++ b/frontend/src/metabase/router/v7/V7ReduxBridge.tsx
@@ -0,0 +1,46 @@
+import { useEffect } from "react";
+import {
+ useNavigationType,
+ useLocation as useV7Location,
+ useNavigate as useV7Navigate,
+} from "react-router-v7";
+
+import { useDispatch } from "metabase/redux";
+
+import { LOCATION_CHANGE } from "../routing-reducer";
+
+import { toV3Location } from "./location";
+import { setV7Navigate } from "./navigator";
+
+/**
+ * Bridges the v7 router to redux, replacing what `routerMiddleware` +
+ * `syncHistoryWithStore` did on v3:
+ *
+ * - registers the live `navigate` so the redux navigator adapter (and thus
+ * `dispatch(push(...))`) can drive the v7 router;
+ * - mirrors every location into `state.routing` via LOCATION_CHANGE, so
+ * `getLocation` / `isNavbarOpen` / `errorPage` keep working.
+ *
+ * Rendered inside the router but outside `<Routes>`, so it tracks the location
+ * regardless of which route matches. Deleted with the v3 engine in Phase 4.
+ */
+export function V7ReduxBridge(): null {
+ const navigate = useV7Navigate();
+ const location = useV7Location();
+ const action = useNavigationType();
+ const dispatch = useDispatch();
+
+ useEffect(() => {
+ setV7Navigate(navigate);
+ return () => setV7Navigate(null);
+ }, [navigate]);
+
+ useEffect(() => {
+ dispatch({
+ type: LOCATION_CHANGE,
+ payload: toV3Location(location, action),
+ });
+ }, [dispatch, location, action]);
+
+ return null;
+}
diff --git a/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx b/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx
new file mode 100644
index 00000000000..7b336879641
--- /dev/null
+++ b/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx
@@ -0,0 +1,73 @@
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { Outlet, Route, push, useLocation, useParams } from "metabase/router";
+import { getLocation } from "metabase/selectors/routing";
+
+import type { RouterEngine } from "../engine";
+
+function Home() {
+ const { pathname } = useLocation();
+ return (
+ <div>
+ <span data-testid="location">{pathname}</span>
+ <Outlet />
+ </div>
+ );
+}
+
+function Page() {
+ const { id } = useParams();
+ return <span data-testid="page-id">{id}</span>;
+}
+
+const tree = (
+ <Route path="/" element={<Home />}>
+ <Route path="page/:id" element={<Page />} />
+ <Route path="other" element={<span data-testid="other">other</span>} />
+ </Route>
+);
+
+function setup(routerEngine: RouterEngine, initialRoute: string) {
+ return renderWithProviders(tree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute,
+ });
+}
+
+describe.each<RouterEngine>(["v3", "v7"])(
+ "route tree on the %s engine",
+ (routerEngine) => {
+ it("matches a deep link and reads its params", async () => {
+ setup(routerEngine, "/page/7");
+ expect(await screen.findByTestId("page-id")).toHaveTextContent("7");
+ expect(screen.getByTestId("location")).toHaveTextContent("/page/7");
+ });
+
+ it("navigates via dispatch(push())", async () => {
+ const { store } = setup(routerEngine, "/page/7");
+ expect(await screen.findByTestId("page-id")).toBeInTheDocument();
+
+ store.dispatch(push("/other"));
+
+ expect(await screen.findByTestId("other")).toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent("/other");
+ });
+ },
+);
+
+// v3 tests never wired `syncHistoryWithStore`, so `state.routing` only tracks the
+// location on v7, through the redux bridge. This pins that the bridge feeds it.
+describe("v7 redux bridge", () => {
+ it("mirrors the location into state.routing", async () => {
+ const { store } = setup("v7", "/page/7");
+ await waitFor(() => {
+ expect(getLocation(store.getState())?.pathname).toBe("/page/7");
+ });
+
+ store.dispatch(push("/other"));
+
+ await waitFor(() => {
+ expect(getLocation(store.getState())?.pathname).toBe("/other");
+ });
+ });
+});
diff --git a/frontend/src/metabase/router/v7/location.ts b/frontend/src/metabase/router/v7/location.ts
new file mode 100644
index 00000000000..35ff85953e7
--- /dev/null
+++ b/frontend/src/metabase/router/v7/location.ts
@@ -0,0 +1,39 @@
+import type { Location as HistoryLocation } from "history";
+import type { Location as V7Location } from "react-router-v7";
+
+/**
+ * Parse a search string into v3's `location.query` object: repeated keys become
+ * an array, an empty value stays `""`, matching history@3's default parser that
+ * the `location.query` readers were written against.
+ */
+export function searchToQuery(
+ search: string,
+): Record<string, string | string[]> {
+ const params = new URLSearchParams(search);
+ const query: Record<string, string | string[]> = {};
+ for (const key of new Set(params.keys())) {
+ const values = params.getAll(key);
+ query[key] = values.length > 1 ? values : values[0];
+ }
+ return query;
+}
+
+/**
+ * Build the v3-shaped `history` location the facade context and `state.routing`
+ * expect from a v7 location plus the current navigation type.
+ */
+export function toV3Location(
+ location: V7Location,
+ action: HistoryLocation["action"],
+): HistoryLocation {
+ return {
+ pathname: location.pathname,
+ search: location.search,
+ hash: location.hash,
+ // v3 leaves state `undefined` when absent; v7 uses `null`.
+ state: location.state ?? undefined,
+ key: location.key,
+ query: searchToQuery(location.search),
+ action,
+ };
+}
diff --git a/frontend/src/metabase/router/v7/map-to-v7.tsx b/frontend/src/metabase/router/v7/map-to-v7.tsx
new file mode 100644
index 00000000000..51d1121c04f
--- /dev/null
+++ b/frontend/src/metabase/router/v7/map-to-v7.tsx
@@ -0,0 +1,69 @@
+import {
+ Children,
+ Fragment,
+ type ReactElement,
+ type ReactNode,
+ isValidElement,
+} from "react";
+import { Route as V7Route } from "react-router-v7";
+
+import type { RouteElementProps } from "../route";
+import { Route } from "../route";
+import { translatePatternToV3 } from "../translate-pattern";
+
+import { RouterBridge } from "./RouterBridge";
+
+/**
+ * Rebuild the facade route tree (`<Route path element>` + `<Outlet/>`, authored
+ * in v7 syntax) into a real react-router v7 route tree for `<Routes>`. Paths are
+ * already v7-native, so they pass straight through; each `element` is wrapped in a
+ * `RouterBridge` that republishes v7 state into the shared context. The v3 form of
+ * the path is kept on `handle` so the bridge can hand the facade hooks a v3-shaped
+ * `routes` branch (its matcher is v3's). Throwaway: goes away with the v3 engine.
+ */
+export function mapToV7(node: ReactNode): ReactNode {
+ return Children.map(node, (child) => {
+ if (!isValidElement(child)) {
+ return child;
+ }
+
+ // Fragments group sibling routes (plugin interpolation, conditionals); descend
+ // so the facade routes inside them get converted too.
+ if (child.type === Fragment) {
+ return <Fragment>{mapToV7(child.props.children)}</Fragment>;
+ }
+
+ if (child.type === Route) {
+ // `child.type === Route` guarantees these are the facade Route's props.
+ return toV7Route(child as ReactElement<RouteElementProps>);
+ }
+
+ // Anything else in a route position is passed through unchanged; v7's
+ // `createRoutesFromChildren` validates it.
+ return child;
+ });
+}
+
+function toV7Route(element: ReactElement<RouteElementProps>): ReactElement {
+ const { path, index, element: routeElement, children } = element.props;
+
+ // v7 defaults a route with no `element` to `<Outlet/>`; only wrap (and publish
+ // context) when the facade route actually renders something.
+ const bridged =
+ routeElement !== undefined ? (
+ <RouterBridge v3Element={routeElement} />
+ ) : undefined;
+
+ const handle =
+ path != null ? { v3Path: translatePatternToV3(path) } : undefined;
+
+ if (index) {
+ return <V7Route index element={bridged} handle={handle} />;
+ }
+
+ return (
+ <V7Route path={path} element={bridged} handle={handle}>
+ {mapToV7(children)}
+ </V7Route>
+ );
+}
diff --git a/frontend/src/metabase/router/v7/navigator.ts b/frontend/src/metabase/router/v7/navigator.ts
new file mode 100644
index 00000000000..262266b4268
--- /dev/null
+++ b/frontend/src/metabase/router/v7/navigator.ts
@@ -0,0 +1,62 @@
+import type { LocationDescriptor } from "history";
+import type { NavigateFunction, NavigateOptions, To } from "react-router-v7";
+
+import type { RouterNavigator } from "../middleware";
+
+/**
+ * The live v7 `navigate`, registered by `V7ReduxBridge` once the router mounts.
+ * The redux navigator adapter is built at store creation, before the router
+ * exists, so it reads `navigate` through this holder rather than capturing it.
+ */
+let currentNavigate: NavigateFunction | null = null;
+
+export function setV7Navigate(navigate: NavigateFunction | null): void {
+ currentNavigate = navigate;
+}
+
+/**
+ * Turn a v3 `LocationDescriptor` (string or `{ pathname, search, hash, state }`)
+ * into v7 `navigate(to, options)` arguments. Shared by the imperative-router
+ * shim and the redux navigator so both map descriptors the same way.
+ */
+export function toNavigateArgs(
+ location: LocationDescriptor,
+ options: NavigateOptions = {},
+): [To, NavigateOptions] {
+ if (typeof location === "string") {
+ return [location, options];
+ }
+ return [
+ {
+ pathname: location.pathname,
+ search: location.search,
+ hash: location.hash,
+ },
+ { ...options, state: location.state },
+ ];
+}
+
+/**
+ * A `RouterNavigator` (the subset of `history` that `routerMiddleware` drives)
+ * backed by the live v7 `navigate`. Passed to the store on v7 so
+ * `dispatch(push(...))` navigates the v7 router. Calls before the router mounts
+ * are dropped, matching the pre-mount no-op window on v3.
+ */
+export function createV7Navigator(): RouterNavigator {
+ const navigate = (to: To | number, options?: NavigateOptions) => {
+ if (typeof to === "number") {
+ currentNavigate?.(to);
+ } else {
+ currentNavigate?.(to, options);
+ }
+ };
+
+ return {
+ push: (location) => navigate(...toNavigateArgs(location)),
+ replace: (location) =>
+ navigate(...toNavigateArgs(location, { replace: true })),
+ go: (n) => navigate(n),
+ goBack: () => navigate(-1),
+ goForward: () => navigate(1),
+ };
+}
diff --git a/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
new file mode 100644
index 00000000000..3c475ecc1fe
--- /dev/null
+++ b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
@@ -0,0 +1,87 @@
+import userEvent from "@testing-library/user-event";
+import { MemoryRouter } from "react-router-v7";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import {
+ Outlet,
+ Route,
+ useLocation,
+ useNavigate,
+ useParams,
+ useRouter,
+} from "metabase/router";
+
+import { V7RouterTree } from "./RouterProviderV7";
+
+function Layout() {
+ return (
+ <div>
+ <span data-testid="layout">layout</span>
+ <Outlet />
+ </div>
+ );
+}
+
+function ThingPage() {
+ const { pathname, search } = useLocation();
+ const params = useParams();
+ const navigate = useNavigate();
+ const { location } = useRouter();
+
+ return (
+ <div>
+ <span data-testid="pathname">{pathname}</span>
+ <span data-testid="search">{search}</span>
+ <span data-testid="thing-id">{params.thingId}</span>
+ <span data-testid="query-tab">{String(location.query.tab)}</span>
+ <button onClick={() => navigate("/other")}>go absolute</button>
+ <button onClick={() => navigate("..")}>go up</button>
+ </div>
+ );
+}
+
+const tree = (
+ <Route path="/" element={<Layout />}>
+ <Route path="things/:thingId" element={<ThingPage />} />
+ <Route path="other" element={<span data-testid="other">other page</span>} />
+ </Route>
+);
+
+function setup(initialRoute: string) {
+ renderWithProviders(
+ <MemoryRouter initialEntries={[initialRoute]}>
+ <V7RouterTree>{tree}</V7RouterTree>
+ </MemoryRouter>,
+ );
+}
+
+describe("v7 engine (facade over real react-router v7)", () => {
+ it("resolves location, search, and params through the bridge", () => {
+ setup("/things/42?tab=x");
+
+ expect(screen.getByTestId("layout")).toBeInTheDocument();
+ expect(screen.getByTestId("pathname")).toHaveTextContent("/things/42");
+ expect(screen.getByTestId("search")).toHaveTextContent("?tab=x");
+ expect(screen.getByTestId("thing-id")).toHaveTextContent("42");
+ });
+
+ it("exposes a v3-shaped location.query", () => {
+ setup("/things/42?tab=x");
+ expect(screen.getByTestId("query-tab")).toHaveTextContent("x");
+ });
+
+ it("navigates to an absolute path via useNavigate", async () => {
+ setup("/things/42");
+ await userEvent.click(screen.getByRole("button", { name: "go absolute" }));
+ expect(await screen.findByTestId("other")).toBeInTheDocument();
+ });
+
+ it("resolves relative navigation against the matched route branch", async () => {
+ setup("/things/42");
+ await userEvent.click(screen.getByRole("button", { name: "go up" }));
+ // `..` climbs out of `things/:thingId` to the parent `/`, leaving the layout
+ // with no matched child.
+ expect(screen.getByTestId("layout")).toBeInTheDocument();
+ expect(screen.queryByTestId("thing-id")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index d705bf8f11f..df1af3cb4fd 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -30,11 +30,14 @@ import type { State } from "metabase/redux/store";
import { createMockState } from "metabase/redux/store/mocks";
import {
ReactRouterRoute,
+ type RouterEngine,
RouterProvider,
routerMiddleware,
routing as routingReducer,
useRouterHistory,
} from "metabase/router";
+import { RouterProviderV7Memory } from "metabase/router/v7/RouterProviderV7";
+import { createV7Navigator } from "metabase/router/v7/navigator";
import { getMetabaseCssVariables } from "metabase/styled-components/theme/css-variables";
import type { MantineThemeOverride } from "metabase/ui";
import { PortalContainer, ThemeProvider, useMantineTheme } from "metabase/ui";
@@ -58,6 +61,8 @@ export interface RenderWithProvidersOptions {
initialRoute?: string;
storeInitialState?: Partial<State>;
withRouter?: boolean;
+ /** Which router engine hosts the tree when `withRouter` is set. Defaults to v3. */
+ routerEngine?: RouterEngine;
/** Renders children wrapped with kbar provider */
withKBar?: boolean;
withDND?: boolean;
@@ -78,6 +83,7 @@ export function renderWithProviders(
initialRoute = "/",
storeInitialState = {},
withRouter = false,
+ routerEngine = "v3",
withKBar = false,
withDND = false,
withUndos = false,
@@ -91,6 +97,7 @@ export function renderWithProviders(
initialRoute,
storeInitialState,
withRouter,
+ routerEngine,
withKBar,
withDND,
withUndos,
@@ -117,6 +124,7 @@ export function renderHookWithProviders<TProps, TResult>(
initialRoute = "/",
storeInitialState = {},
withRouter = false,
+ routerEngine = "v3",
withKBar = false,
withDND = false,
withUndos = false,
@@ -134,6 +142,7 @@ export function renderHookWithProviders<TProps, TResult>(
initialRoute,
storeInitialState,
withRouter,
+ routerEngine,
withKBar,
withDND,
withUndos,
@@ -164,12 +173,14 @@ export function getTestStoreAndWrapper({
initialRoute,
storeInitialState,
withRouter,
+ routerEngine = "v3",
withKBar,
withDND,
withUndos,
customReducers,
theme,
}: GetTestStoreAndWrapperOptions) {
+ const isV7Router = withRouter && routerEngine === "v7";
let { routing, ...initialState }: Partial<State> =
createMockState(storeInitialState);
@@ -184,7 +195,8 @@ export function getTestStoreAndWrapper({
const browserHistory = useRouterHistory(createMemoryHistory)({
entries: [initialRoute],
});
- const history = withRouter ? browserHistory : undefined;
+ // v7 owns its own in-memory history; only the v3 engine uses this one.
+ const history = withRouter && !isV7Router ? browserHistory : undefined;
let reducers;
@@ -202,9 +214,15 @@ export function getTestStoreAndWrapper({
reducers = { ...reducers, ...customReducers };
}
+ // Drive navigation through v3 history or the v7 navigator, matching the engine.
+ const routerNavigator = isV7Router
+ ? createV7Navigator()
+ : history
+ ? history
+ : undefined;
const storeMiddleware = _.compact([
Api.middleware,
- history && routerMiddleware(history),
+ routerNavigator && routerMiddleware(routerNavigator),
]);
// Unjustified type cast. FIXME
@@ -222,6 +240,8 @@ export function getTestStoreAndWrapper({
store={store}
history={history}
withRouter={withRouter}
+ routerEngine={routerEngine}
+ initialRoute={initialRoute}
withDND={withDND}
withUndos={withUndos}
theme={theme}
@@ -273,6 +293,8 @@ export function TestWrapper({
store,
history,
withRouter,
+ routerEngine = "v3",
+ initialRoute = "/",
withKBar,
withDND,
withUndos,
@@ -284,6 +306,8 @@ export function TestWrapper({
store: any;
history?: History;
withRouter: boolean;
+ routerEngine?: RouterEngine;
+ initialRoute?: string;
withKBar: boolean;
withDND: boolean;
withUndos?: boolean;
@@ -316,7 +340,12 @@ export function TestWrapper({
{createPortal(<PortalContainer />, document.body)}
<MaybeKBar hasKBar={withKBar}>
- <MaybeRouter hasRouter={withRouter} history={history}>
+ <MaybeRouter
+ hasRouter={withRouter}
+ routerEngine={routerEngine}
+ history={history}
+ initialRoute={initialRoute}
+ >
{children}
</MaybeRouter>
</MaybeKBar>
@@ -333,13 +362,27 @@ export function TestWrapper({
function MaybeRouter({
children,
hasRouter,
+ routerEngine,
history,
+ initialRoute,
}: {
children: React.ReactElement;
hasRouter: boolean;
+ routerEngine: RouterEngine;
history?: History;
+ initialRoute: string;
}): JSX.Element {
- if (!hasRouter || !history) {
+ if (!hasRouter) {
+ return children;
+ }
+ if (routerEngine === "v7") {
+ return (
+ <RouterProviderV7Memory initialRoute={initialRoute}>
+ {children}
+ </RouterProviderV7Memory>
+ );
+ }
+ if (!history) {
return children;
}
return (
diff --git a/src/metabase/appearance/settings.clj b/src/metabase/appearance/settings.clj
index f1c807f5cc6..7d12e43e5cb 100644
--- a/src/metabase/appearance/settings.clj
+++ b/src/metabase/appearance/settings.clj
@@ -46,6 +46,13 @@
:audit :getter
:export? true)
+(defsetting use-v7-router
+ (deferred-tru "Serve the app with the react-router v7 engine instead of the legacy v3 engine. Toggle off for an instant rollback.")
+ :type :boolean
+ :default false
+ :visibility :public
+ :export? false)
+
(defn- coerce-to-relative-url
"Get the path of a given URL if the URL contains an origin.
Otherwise make the landing-page a relative path."