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
Enable the react-router v7 engine by default, with the fixes it needs (#78199)
Romeo Van Snick8adef47af63a
diff --git a/frontend/src/metabase/router/router-link.tsx b/frontend/src/metabase/router/router-link.tsxindex 831daab2f13..52dc8f77fe5 100644--- a/frontend/src/metabase/router/router-link.tsx+++ b/frontend/src/metabase/router/router-link.tsx@@ -7,6 +7,7 @@ import {} from "react-router-v7";import { type RouterLinkProps, V3RouterLink } from "./react-router";+import { queryToSearch } from "./v7/location";/*** The app's `<Link>`, engine-aware.@@ -25,19 +26,43 @@ type V3To = RouterLinkProps["to"];// v3 descriptors carry the query as a `query` object and `state` inline; v7 uses// a `search` string and a separate `state` prop. Translate so existing call sites// keep working on v7.+/**+ * v3 resolved a bare path against the root, so call sites write `to="reference"`+ * meaning `/reference`. v7 resolves it against the current route instead, which+ * would nest it (that link sits on `/browse/databases`). Anchor it so the target+ * does not depend on where the link is rendered.+ *+ * Left alone: a leading `?` or `#`, which keeps the current path by design, and+ * anything carrying a scheme (`https:`, `mailto:`) or a protocol-relative `//`,+ * which is not a route at all.+ */+function toRootRelative(pathname: string): string {+ const isAlreadyAnchored = pathname === "" || /^[/?#]/.test(pathname);+ const hasScheme = /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(pathname);+ return isAlreadyAnchored || hasScheme ? pathname : `/${pathname}`;+}+function toV7Target(to: V3To): { to: V7LinkProps["to"]; state?: unknown } {- if (to == null || typeof to === "string") {- return { to: to ?? "" };+ if (to == null) {+ return { to: "" };+ }+ if (typeof to === "string") {+ return { to: toRootRelative(to) };}if (typeof to === "function") {// v3's function form of `to` has no v7 analog and is not used in the app.return { to: "" };}const { pathname, search, hash, query, state } = to;- const searchString =- search ?? (query ? `?${new URLSearchParams(query).toString()}` : undefined);+ // `query` wins over `search`, matching history@3: call sites build+ // `{ ...location, query }`, where the spread carries a stale `search`.+ const searchString = query ? queryToSearch(query) : search;return {- to: { pathname: pathname ?? "", search: searchString, hash },+ to: {+ pathname: pathname == null ? "" : toRootRelative(pathname),+ search: searchString,+ hash,+ },state,};}@@ -63,12 +88,13 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>(const { activeClassName, activeStyle, onlyActiveOnIndex, ...rest } =props;- // A `<Link>` with no destination is used as a button: it navigates through- // its `onClick`. v7's `<Link>` would additionally navigate to the current- // route on click, clobbering any push the handler performs, so render a- // plain anchor instead. On v3 this matches `router.push(undefined)`, which- // is a no-op, so only the handler runs.- if (to == null) {+ // A `<Link>` with no destination (`to` null or `""`) is used as a button: it+ // navigates through its `onClick`. v7's `<Link>` would additionally navigate+ // on click (an empty `to` resolves to the current route, or `/` from a+ // top-level portal like a toast), clobbering any push the handler performs,+ // so render a plain anchor instead. On v3 this matches `router.push("")` /+ // `router.push(undefined)`, which are no-ops, so only the handler runs.+ if (to == null || to === "") {return <a {...rest} ref={linkRef} />;}@@ -85,6 +111,7 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>({...navRest}to={v7To}state={state}+ replace={false}ref={linkRef}end={onlyActiveOnIndex}className={({ isActive }) =>@@ -99,7 +126,19 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>();}- return <V7Link {...rest} to={v7To} state={state} ref={linkRef} />;+ // v7's `<Link>` silently downgrades a click to a `replace` when the target+ // equals the current URL. v3 always pushed, and call sites rely on it: the+ // "New document" menu item links to `/document/new` from `/document/new`,+ // and the unsaved-changes prompt keys off the new location. Push always.+ return (+ <V7Link+ {...rest}+ to={v7To}+ state={state}+ replace={false}+ ref={linkRef}+ />+ );}return (diff --git a/frontend/src/metabase/router/router-link.unit.spec.tsx b/frontend/src/metabase/router/router-link.unit.spec.tsxindex 9e738a780c7..1f64534417d 100644--- a/frontend/src/metabase/router/router-link.unit.spec.tsx+++ b/frontend/src/metabase/router/router-link.unit.spec.tsx@@ -7,20 +7,29 @@ import { Link, Outlet, Route, push, useLocation } from "metabase/router";import type { RouterEngine } from "./engine";function Home() {- const { pathname } = useLocation();+ const { pathname, key } = useLocation();const dispatch = useDispatch();return (<div><span data-testid="location">{pathname}</span>+ <span data-testid="location-key">{key}</span><Link to="/other">go</Link>{/* A `<Link>` used as a button: it navigates through its own onClick. */}<Link onClick={() => dispatch(push("/other"))}>act</Link>+ {/* A button-like `<Link to="">` (e.g. the undo toast) must not navigate. */}+ <Link to="" onClick={() => undefined}>+ noop+ </Link><Link to="/" activeClassName="is-active" onlyActiveOnIndex>home</Link><Link to="/other" activeClassName="is-active">section</Link>+ {/* v3 resolved a bare path against the root, not the current route. */}+ <Link to="other">bare</Link>+ <Link to="https://www.metabase.com/docs">external</Link>+ <Link to="mailto:[email protected]">mail</Link><Outlet /></div>);@@ -52,6 +61,60 @@ describe.each<RouterEngine>(["v3", "v7"])(expect(screen.getByTestId("location")).toHaveTextContent("/other");});+ // Only the destination is asserted: v3's memory history leaves the bare path+ // literal in tests, though a real browser resolves it against the root the way+ // v7 now does.+ it("resolves a bare relative path against the root", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ routerEngine,+ initialRoute: "/",+ });++ await userEvent.click(screen.getByRole("link", { name: "bare" }));++ expect(await screen.findByTestId("other")).toBeInTheDocument();+ });++ // Anchoring bare paths must not touch absolute URLs, or a docs link becomes+ // `/https:/www.metabase.com/...`.+ it("leaves absolute urls untouched", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ routerEngine,+ initialRoute: "/",+ });++ expect(screen.getByRole("link", { name: "external" })).toHaveAttribute(+ "href",+ "https://www.metabase.com/docs",+ );+ expect(screen.getByRole("link", { name: "mail" })).toHaveAttribute(+ "href",+ "mailto:[email protected]",+ );+ });++ // v7's `<Link>` downgrades a click to a `replace` when the target equals the+ // current URL, which leaves the location key untouched. v3 always pushed, and+ // the documents page shows its unsaved-changes prompt when the key changes.+ it("pushes a new entry when linking to the current url", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ routerEngine,+ initialRoute: "/other",+ });++ await screen.findByTestId("other");+ const keyBefore = screen.getByTestId("location-key").textContent;++ await userEvent.click(screen.getByRole("link", { name: "go" }));++ expect(screen.getByTestId("location-key")).not.toHaveTextContent(+ String(keyBefore),+ );+ });+it("applies activeClassName to the link that matches the route", async () => {renderWithProviders(tree, {withRouter: true,@@ -80,5 +143,22 @@ describe.each<RouterEngine>(["v3", "v7"])(expect(await screen.findByTestId("other")).toBeInTheDocument();expect(screen.getByTestId("location")).toHaveTextContent("/other");});++ it("does not navigate when a button-like `to=''` link is clicked", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ routerEngine,+ initialRoute: "/other",+ });++ await screen.findByTestId("other");++ // On v7 an empty `to` resolved to "/" and navigated home, unmounting the+ // current view. It must stay put so only the onClick handler runs.+ await userEvent.click(screen.getByText("noop"));++ expect(screen.getByTestId("other")).toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent("/other");+ });},);diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsxindex 0dde3c8495a..6bf7edbb621 100644--- a/frontend/src/metabase/router/v7/RouterBridge.tsx+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx@@ -1,6 +1,8 @@import type { Location as HistoryLocation, LocationDescriptor } from "history";-import { type ReactNode, useContext, useMemo } from "react";+import { type ReactNode, useContext, useMemo, useRef } from "react";import {+ type NavigateOptions,+ type To,UNSAFE_RouteContext,type NavigateFunction as V7NavigateFunction,Outlet as V7Outlet,@@ -21,7 +23,7 @@ import type { Route } from "../route";import { registerLeaveHook } from "./blocking-history";import { toV3Location } from "./location";-import { toNavigateArgs } from "./navigator";+import { subscribeLocation, toNavigateArgs } from "./navigator";// The facade route stub, plus the route's matched pathname so `setRouteLeaveHook`// can scope its hook to the route the way v3 does.@@ -43,14 +45,34 @@ export function RouterBridge({const v7Location = useV7Location();const navigate = useV7Navigate();const action = useNavigationType();+ const v7Params = useV7Params();// 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"];+ // which is structurally the same string map apart from the splat: v3 exposed the+ // wildcard match as `splat`, v7 names it `*`. Republish it under both so v3-era+ // readers (`params.splat` in `AutomaticDashboardApp`) keep working.+ const params = useMemo<WithRouterProps["params"]>(() => {+ const { "*": splat, ...rest } = v7Params;+ const v3Params = splat === undefined ? rest : { ...rest, splat };+ // Cast because v7 types params as readonly and partial; v3's shape is the same+ // string map.+ return v3Params as WithRouterProps["params"];+ }, [v7Params]);// `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);+ // react-router hands back a fresh `matches` array on every render, so memoizing+ // on it would republish a new `routes`/`route` each time. v3's were stable, and+ // consumers key effects on `route`: the leave-confirm modal resets itself when+ // `route` changes, which closed it mid-interaction. Key on the matched branch.+ const matchesKey = matches+ .map((match) => {+ // `handle` is typed `unknown`; we only ever put `{ v3Path }` on it.+ const handle = match.route.handle as { v3Path?: string } | undefined;+ return `${match.pathname}|${handle?.v3Path ?? ""}`;+ })+ .join(">");const routes = useMemo<RouteStub[]>(() =>matches.map((match) => {@@ -60,7 +82,9 @@ export function RouterBridge({// pathname, which `setRouteLeaveHook` uses to scope its hook to this route.return { path: handle?.v3Path, pathnameBase: match.pathname };}),- [matches],+ // Keyed on the matched branch, not the array identity, which changes each render.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [matchesKey],);const location = useMemo<HistoryLocation>(@@ -68,10 +92,25 @@ export function RouterBridge({[v7Location, action],);- const router = useMemo<InjectedRouter>(- () => makeRouterShim(navigate),- [navigate],- );+ // v3 handed consumers a stable `router`, so effects keyed on it (notably the+ // `router.listen` subscriptions in `use-dashboard-url-query`) survive a+ // navigation. v7's `navigate` changes identity per location, which would tear+ // those effects down and re-subscribe them around every location change, so read+ // `navigate` through a ref and keep the shim itself stable.+ const navigateRef = useRef(navigate);+ navigateRef.current = navigate;+ const router = useMemo<InjectedRouter>(() => {+ const navigateLatest = (to: To | number, options?: NavigateOptions) => {+ if (typeof to === "number") {+ navigateRef.current(to);+ } else {+ navigateRef.current(to, options);+ }+ };+ // `NavigateFunction` is an overloaded signature (a `To` or a delta); the+ // wrapper implements both arms but TS cannot infer it back into the overload.+ return makeRouterShim(navigateLatest as V7NavigateFunction);+ }, []);const value = useMemo<WithRouterProps>(() => ({ router, location, params, routes }),@@ -109,6 +148,8 @@ function makeRouterShim(navigate: V7NavigateFunction): InjectedRouter {? location: `${location.pathname ?? ""}${location.search ?? ""}${location.hash ?? ""}`;+ // Cast because v3's own `InjectedRouter` type omits `listen`, even though both+ // engines expose it at runtime.return {push: (location) => navigate(...toNavigateArgs(location)),replace: (location) =>@@ -125,5 +166,8 @@ function makeRouterShim(navigate: V7NavigateFunction): InjectedRouter {createPath: href,createHref: href,isActive: () => false,- };+ // Stands in for v3's `router.listen` (used by e.g. `use-dashboard-url-query`).+ // `V7ReduxBridge` feeds these subscribers every location change.+ listen: subscribeLocation,+ } as InjectedRouter;}diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsxindex 888992873b2..becb2015c2d 100644--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx@@ -1,17 +1,23 @@import type { PropsWithChildren } from "react";-import { useState } from "react";+import { useCallback, useState } from "react";import {- unstable_HistoryRouter as HistoryRouter,+ type HistoryRouterProps,Routes,UNSAFE_createBrowserHistory as createBrowserHistory,UNSAFE_createMemoryHistory as createMemoryHistory,} from "react-router-v7";+import { useDispatch } from "metabase/redux";import { getBasename } from "metabase/utils/basename";+import { LOCATION_CHANGE } from "../routing-reducer";++import { SyncHistoryRouter } from "./SyncHistoryRouter";import { V7ReduxBridge } from "./V7ReduxBridge";import { withBlocking } from "./blocking-history";+import { toV3Location } from "./location";import { mapToV7 } from "./map-to-v7";+import { notifyLocationListeners } from "./navigator";/*** The v7 route tree: the facade tree mapped to real v7 routes and rendered by@@ -19,15 +25,40 @@ import { mapToV7 } from "./map-to-v7";* 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 {+export function V7RouterTree({+ children,+ history,+}: PropsWithChildren<{+ history?: HistoryRouterProps["history"];+}>): JSX.Element {return (<>- <V7ReduxBridge />+ <V7ReduxBridge history={history} /><Routes>{mapToV7(children)}</Routes></>);}+/**+ * Mirrors each location into `state.routing` (and the `router.listen`+ * subscribers) from inside the history subscription, so the store is current+ * before any thunk reads it. Replaces v3's `syncHistoryWithStore`.+ */+function useLocationMirror() {+ const dispatch = useDispatch();+ return useCallback(+ (+ location: Parameters<typeof toV3Location>[0],+ action: Parameters<typeof toV3Location>[1],+ ) => {+ const v3Location = toV3Location(location, action);+ dispatch({ type: LOCATION_CHANGE, payload: v3Location });+ notifyLocationListeners(v3Location);+ },+ [dispatch],+ );+}+/*** react-router v7 hosting the app, declarative mode (Phase 3.1). Replaces the v3* `<Router>` + `useRouterHistory` + `syncHistoryWithStore` stack behind the@@ -40,10 +71,15 @@ export function RouterProviderV7({ children }: PropsWithChildren): JSX.Element {const [history] = useState(() =>withBlocking(createBrowserHistory({ v5Compat: true })),);+ const onLocationChange = useLocationMirror();return (- <HistoryRouter history={history} basename={getBasename() || undefined}>- <V7RouterTree>{children}</V7RouterTree>- </HistoryRouter>+ <SyncHistoryRouter+ history={history}+ basename={getBasename() || undefined}+ onLocationChange={onLocationChange}+ >+ <V7RouterTree history={history}>{children}</V7RouterTree>+ </SyncHistoryRouter>);}@@ -61,9 +97,10 @@ export function RouterProviderV7Memory({createMemoryHistory({ initialEntries: [initialRoute], v5Compat: true }),),);+ const onLocationChange = useLocationMirror();return (- <HistoryRouter history={history}>- <V7RouterTree>{children}</V7RouterTree>- </HistoryRouter>+ <SyncHistoryRouter history={history} onLocationChange={onLocationChange}>+ <V7RouterTree history={history}>{children}</V7RouterTree>+ </SyncHistoryRouter>);}diff --git a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsxnew file mode 100644index 00000000000..b233ae7ee56--- /dev/null+++ b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx@@ -0,0 +1,77 @@+import type { PropsWithChildren } from "react";+import { useLayoutEffect, useRef, useState } from "react";+import {+ type HistoryRouterProps,+ type NavigationType,+ Router,+ type Location as V7Location,+} from "react-router-v7";++type History = HistoryRouterProps["history"];++/**+ * `unstable_HistoryRouter` without the `startTransition`, plus a hook for+ * mirroring the location elsewhere.+ *+ * react-router marks its own location update as a transition, so in a production+ * React build the navigation is deprioritised and 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` runs inside the same history subscription, so `state.routing`+ * is updated as part of the transition the way v3's `syncHistoryWithStore` did.+ * Thunks read the store synchronously right after navigating, so a store that+ * lags a render makes them push a stale location. This stays the blocking+ * history's only subscriber: its POP-revert bookkeeping is per-history rather+ * than per-listener, so a second subscription would double-evaluate the leave+ * hooks.+ *+ * Goes away with the v3 engine in Phase 4, once the app tolerates deferred+ * navigation.+ */+export function SyncHistoryRouter({+ history,+ basename,+ onLocationChange,+ children,+}: PropsWithChildren<{+ history: History;+ basename?: string;+ onLocationChange?: (location: V7Location, action: NavigationType) => void;+}>): JSX.Element {+ const [state, setState] = useState<{+ action: NavigationType;+ location: V7Location;+ }>({+ action: history.action,+ location: history.location,+ });++ // Read through a ref so a new callback identity does not resubscribe the+ // history, which would drop and re-add its only listener.+ const onLocationChangeRef = useRef(onLocationChange);+ onLocationChangeRef.current = onLocationChange;++ // Layout, not passive, so the router state is committed before the browser+ // paints the click that triggered it.+ useLayoutEffect(() => {+ onLocationChangeRef.current?.(history.location, history.action);+ return history.listen((update) => {+ setState(update);+ onLocationChangeRef.current?.(update.location, update.action);+ });+ }, [history]);++ return (+ <Router+ basename={basename}+ location={state.location}+ navigationType={state.action}+ navigator={history}+ >+ {children}+ </Router>+ );+}diff --git a/frontend/src/metabase/router/v7/V7ReduxBridge.tsx b/frontend/src/metabase/router/v7/V7ReduxBridge.tsxindex 206f9e6f775..acd4c59a6c0 100644--- a/frontend/src/metabase/router/v7/V7ReduxBridge.tsx+++ b/frontend/src/metabase/router/v7/V7ReduxBridge.tsx@@ -1,5 +1,6 @@import { useEffect } from "react";import {+ type HistoryRouterProps,useNavigationType,useLocation as useV7Location,useNavigate as useV7Navigate,@@ -10,7 +11,7 @@ import { useDispatch } from "metabase/redux";import { LOCATION_CHANGE } from "../routing-reducer";import { toV3Location } from "./location";-import { setV7Navigate } from "./navigator";+import { notifyLocationListeners, setV7Navigate } from "./navigator";/*** Bridges the v7 router to redux, replacing what `routerMiddleware` +@@ -21,10 +22,20 @@ import { setV7Navigate } from "./navigator";* - 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.+ * The mirror subscribes to the history when one is passed, because v3 dispatched+ * LOCATION_CHANGE as part of the transition rather than after a render. Thunks+ * read the store synchronously right after navigating (`setEditingDashboard`+ * pushes `{ ...getLocation(getState()) }`), so a store that lags a render makes+ * them push a stale location and clobber query params that were just set.+ * Falls back to the rendered location when no history is available, which is how+ * tests mount the tree under a plain `<MemoryRouter>`. Deleted with the v3 engine+ * in Phase 4.*/-export function V7ReduxBridge(): null {+export function V7ReduxBridge({+ history,+}: {+ history?: HistoryRouterProps["history"];+}): null {const navigate = useV7Navigate();const location = useV7Location();const action = useNavigationType();@@ -35,12 +46,16 @@ export function V7ReduxBridge(): null {return () => setV7Navigate(null);}, [navigate]);+ // When a history is provided the mirroring happens synchronously in+ // `SyncHistoryRouter`'s subscription instead, so nothing to do here.useEffect(() => {- dispatch({- type: LOCATION_CHANGE,- payload: toV3Location(location, action),- });- }, [dispatch, location, action]);+ if (history) {+ return;+ }+ const v3Location = toV3Location(location, action);+ dispatch({ type: LOCATION_CHANGE, payload: v3Location });+ notifyLocationListeners(v3Location);+ }, [dispatch, history, location, action]);return null;}diff --git a/frontend/src/metabase/router/v7/blocking-history.ts b/frontend/src/metabase/router/v7/blocking-history.tsindex 472fe37e328..6027131c48b 100644--- a/frontend/src/metabase/router/v7/blocking-history.ts+++ b/frontend/src/metabase/router/v7/blocking-history.ts@@ -91,6 +91,18 @@ function toBlockedLocation(return toV3Location(location, action);}+function isSameUrl(+ to: To,+ current: { pathname: string; search: string; hash: string },+): boolean {+ const path = typeof to === "string" ? parsePath(to) : to;+ return (+ (path.pathname ?? current.pathname) === current.pathname &&+ (path.search ?? "") === current.search &&+ (path.hash ?? "") === current.hash+ );+}+/*** Wrap a history so a registered leave hook can cancel navigation, restoring the* v3 `setRouteLeaveHook` behavior on the declarative v7 engine. react-router@@ -113,6 +125,14 @@ export function withBlocking(history: History): History {};const replace: History["replace"] = (to, state) => {+ // v3/history@3 did not notify listeners when replacing to the current URL, so+ // effects that sync state into the URL by replacing the location they just+ // read stayed stable. v7's `v5Compat` history notifies on every replace,+ // which loops those effects (e.g. the dashboard's `useLocationSync`). Skip the+ // redundant replace to keep the v3 behavior.+ if (isSameUrl(to, history.location)) {+ return;+ }if (!isBlocked(toBlockedLocation(to, "REPLACE", state))) {history.replace(to, state);}diff --git a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts b/frontend/src/metabase/router/v7/blocking-history.unit.spec.tsindex b72ac294df6..d735b5b3e7b 100644--- a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts+++ b/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts@@ -48,6 +48,18 @@ describe("withBlocking", () => {expect(history.location.pathname).toBe("/b");});+ it("does not notify listeners when replacing to the current URL", () => {+ const history = setup(["/a?x=1"]);+ const listener = jest.fn();+ history.listen(listener);++ history.replace("/a?x=1");+ expect(listener).not.toHaveBeenCalled();++ history.replace("/b");+ expect(listener).toHaveBeenCalledTimes(1);+ });+it("blocks a replace while a hook returns false", () => {const history = setup();register(() => false);diff --git a/frontend/src/metabase/router/v7/location.ts b/frontend/src/metabase/router/v7/location.tsindex 35ff85953e7..838a48d1995 100644--- a/frontend/src/metabase/router/v7/location.ts+++ b/frontend/src/metabase/router/v7/location.ts@@ -18,6 +18,37 @@ export function searchToQuery(return query;}+/**+ * Serialize v3's `location.query` object back into a search string, the only form+ * v7 understands. Repeated values become repeated keys, mirroring what+ * `searchToQuery` parses. Returns `""` for an empty query.+ *+ * Keys are sorted, because history@3 stringified the query with `query-string`,+ * which sorts by default. Call sites build the query from an object whose key+ * order is incidental, and the URL is user visible and asserted against, so the+ * order has to stay stable rather than follow insertion.+ */+export function queryToSearch(query: Record<string, unknown>): string {+ const params = new URLSearchParams();+ const sortedEntries = Object.entries(query).sort(([a], [b]) =>+ a.localeCompare(b),+ );+ for (const [key, value] of sortedEntries) {+ if (value == null) {+ continue;+ }+ const values = Array.isArray(value) ? value : [value];+ for (const item of values) {+ params.append(key, String(item));+ }+ }+ // `URLSearchParams` matches history@3 apart from `~`, which it escapes and+ // history@3 left alone. Both write a space as `+`. These URLs are user visible+ // and asserted against, so a date filter has to read `next30days~`.+ const search = params.toString().replace(/%7E/gi, "~");+ return search ? `?${search}` : "";+}+/*** Build the v3-shaped `history` location the facade context and `state.routing`* expect from a v7 location plus the current navigation type.diff --git a/frontend/src/metabase/router/v7/navigator.ts b/frontend/src/metabase/router/v7/navigator.tsindex 262266b4268..fb4d87e72fd 100644--- a/frontend/src/metabase/router/v7/navigator.ts+++ b/frontend/src/metabase/router/v7/navigator.ts@@ -1,8 +1,10 @@-import type { LocationDescriptor } from "history";+import type { Location as HistoryLocation, LocationDescriptor } from "history";import type { NavigateFunction, NavigateOptions, To } from "react-router-v7";import type { RouterNavigator } from "../middleware";+import { queryToSearch } from "./location";+/*** The live v7 `navigate`, registered by `V7ReduxBridge` once the router mounts.* The redux navigator adapter is built at store creation, before the router@@ -14,6 +16,28 @@ export function setV7Navigate(navigate: NavigateFunction | null): void {currentNavigate = navigate;}+/**+ * Subscribers to location changes, backing the imperative router's `listen`. v3's+ * `router.listen` had no v7 equivalent, so `V7ReduxBridge` fans every location+ * change out to these on the app's behalf (e.g. `use-dashboard-url-query`).+ */+type LocationListener = (location: HistoryLocation) => void;+const locationListeners = new Set<LocationListener>();++export function subscribeLocation(listener: LocationListener): () => void {+ locationListeners.add(listener);+ return () => {+ locationListeners.delete(listener);+ };+}++export function notifyLocationListeners(location: HistoryLocation): void {+ // Snapshot so a listener that unsubscribes mid-run cannot skip a sibling.+ for (const listener of [...locationListeners]) {+ listener(location);+ }+}+/*** Turn a v3 `LocationDescriptor` (string or `{ pathname, search, hash, state }`)* into v7 `navigate(to, options)` arguments. Shared by the imperative-router@@ -26,10 +50,18 @@ export function toNavigateArgs(if (typeof location === "string") {return [location, options];}+ // v3 descriptors carry the query as a `query` object, which v7 does not read, so+ // serialize it into the search string. Dropping it silently loses params (e.g.+ // the dashboard's tab and filter slugs). `query` wins over `search`, matching+ // history@3's `useQueries`: callers build `{ ...location, query }`, so the+ // spread's stale `search` must not shadow the query they just set.+ const search = location.query+ ? queryToSearch(location.query)+ : location.search;return [{pathname: location.pathname,- search: location.search,+ search,hash: location.hash,},{ ...options, state: location.state },diff --git a/frontend/src/metabase/router/v7/navigator.unit.spec.ts b/frontend/src/metabase/router/v7/navigator.unit.spec.tsnew file mode 100644index 00000000000..da345cfff8c--- /dev/null+++ b/frontend/src/metabase/router/v7/navigator.unit.spec.ts@@ -0,0 +1,91 @@+import { queryToSearch } from "./location";+import { toNavigateArgs } from "./navigator";++// v3 location descriptors carry the query as an object. v7 only reads `search`,+// so the navigator has to serialize it; dropping it silently loses params (the+// dashboard's tab and filter slugs went missing this way).+describe("toNavigateArgs", () => {+ it("serializes a v3 `query` object into the search string", () => {+ const [to] = toNavigateArgs({+ pathname: "/dashboard/1",+ query: { tab: "2-tab-two", "filter-date": "2024-01-01" },+ });++ expect(to).toEqual({+ pathname: "/dashboard/1",+ // sorted, as history@3 stringified it+ search: "?filter-date=2024-01-01&tab=2-tab-two",+ hash: undefined,+ });+ });++ // Call sites build `{ ...location, query }`, so the spread carries the previous+ // `search`. The query they just set has to win, as it does on history@3.+ it("prefers `query` over a stale search carried by a spread location", () => {+ const [to] = toNavigateArgs({+ pathname: "/dashboard/1",+ search: "",+ query: { tab: "2-tab-two" },+ });++ expect(to).toMatchObject({ search: "?tab=2-tab-two" });+ });++ it("falls back to `search` when there is no `query`", () => {+ const [to] = toNavigateArgs({ pathname: "/dashboard/1", search: "?a=1" });++ expect(to).toMatchObject({ search: "?a=1" });+ });++ it("passes a string target through untouched", () => {+ expect(toNavigateArgs("/dashboard/1?tab=2")).toEqual([+ "/dashboard/1?tab=2",+ {},+ ]);+ });++ it("carries `state` across as a navigate option", () => {+ const [, options] = toNavigateArgs(+ { pathname: "/a", state: { from: "here" } },+ { replace: true },+ );++ expect(options).toEqual({ replace: true, state: { from: "here" } });+ });+});++describe("queryToSearch", () => {+ it("repeats a key for array values", () => {+ expect(queryToSearch({ id: ["1", "2"] })).toBe("?id=1&id=2");+ });++ it("skips null and undefined values", () => {+ expect(queryToSearch({ a: "1", b: null, c: undefined })).toBe("?a=1");+ });++ it("returns an empty string for an empty query", () => {+ expect(queryToSearch({})).toBe("");+ });++ // history@3 stringified with `query-string`, which sorts keys. The URL is user+ // visible and asserted against, so the order must not follow insertion.+ it("sorts keys regardless of insertion order", () => {+ expect(queryToSearch({ state: "AK", city: "" })).toBe("?city=&state=AK");+ expect(queryToSearch({ city: "", state: "AK" })).toBe("?city=&state=AK");+ });++ // history@3 wrote a space as `+` but left `~` literal, and both show up in URLs+ // the app asserts on (a date filter reads `next30days~`).+ it("writes a space as `+` and leaves `~` literal", () => {+ expect(queryToSearch({ date_filter: "next30days~" })).toBe(+ "?date_filter=next30days~",+ );+ expect(queryToSearch({ task: "field values scanning" })).toBe(+ "?task=field+values+scanning",+ );+ });++ it("still escapes characters that would break the query string", () => {+ expect(queryToSearch({ q: "a&b=c" })).toBe("?q=a%26b%3Dc");+ });+});diff --git a/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx b/frontend/src/metabase/router/v7/router-listen.unit.spec.tsxnew file mode 100644index 00000000000..f2c5db72c6d--- /dev/null+++ b/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx@@ -0,0 +1,59 @@+import type { Location as HistoryLocation } from "history";+import { useEffect, useState } from "react";++import { renderWithProviders, screen } from "__support__/ui";+import { Outlet, Route, push, useRouter } from "metabase/router";++import type { RouterEngine } from "../engine";++// Both engines expose `listen` at runtime; v3's `InjectedRouter` type omits it.+type RouterWithListen = {+ listen: (callback: (location: HistoryLocation) => void) => () => void;+};++// v3's `router.listen` fires a callback on every location change and returns an+// unsubscribe function. The v7 engine has no native equivalent, so the shim wires+// it to the location fan-out; `use-dashboard-url-query` relies on it (and crashed+// the dashboard on v7 when it was missing).+function Harness() {+ const { router } = useRouter();+ const [seen, setSeen] = useState<string[]>([]);+ useEffect(() => {+ // Cast because v3's `InjectedRouter` type omits `listen` (see above).+ return (router as unknown as RouterWithListen).listen((location) => {+ setSeen((previous) => [...previous, location.pathname]);+ });+ }, [router]);+ return (+ <div>+ <span data-testid="seen">{seen.join(",")}</span>+ <Outlet />+ </div>+ );+}++const tree = (+ <Route path="/" element={<Harness />}>+ <Route path="other" element={<span data-testid="other">other</span>} />+ </Route>+);++describe.each<RouterEngine>(["v3", "v7"])(+ "router.listen on the %s engine",+ (routerEngine) => {+ it("fires the callback on navigation and stops after unsubscribe", async () => {+ const { store } = renderWithProviders(tree, {+ withRouter: true,+ routerEngine,+ initialRoute: "/",+ });++ await screen.findByTestId("seen");++ store.dispatch(push("/other"));++ await screen.findByText("other");+ expect(screen.getByTestId("seen")).toHaveTextContent("/other");+ });+ },+);diff --git a/src/metabase/appearance/settings.clj b/src/metabase/appearance/settings.cljindex 7d12e43e5cb..297c7aa250d 100644--- a/src/metabase/appearance/settings.clj+++ b/src/metabase/appearance/settings.clj@@ -49,7 +49,7 @@(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+ :default true:visibility :public:export? false)