Skip to content

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

Build the metabase/router facade for react-router v7 (#76859)

Romeo Van Snickb2d81611cc92
diff --git a/frontend/src/metabase/admin/ai/AISettingsPage.tsx b/frontend/src/metabase/admin/ai/AISettingsPage.tsx
index 2f4fcf0dd8d..6b6170e0c1f 100644
--- a/frontend/src/metabase/admin/ai/AISettingsPage.tsx
+++ b/frontend/src/metabase/admin/ai/AISettingsPage.tsx
@@ -17,7 +17,7 @@ import {
PLUGIN_EMBEDDING_IFRAME_SDK,
PLUGIN_EMBEDDING_SDK,
} from "metabase/plugins";
-import { useRouter } from "metabase/router/useRouter";
+import { useRouter } from "metabase/router";
import { Divider, Flex, Stack, Switch, Tabs } from "metabase/ui";
import { AIProviderSettingsSection } from "./AIProviderSettingsSection";
diff --git a/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx b/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx
index ebd4b8e671b..affe78cf40b 100644
--- a/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx
+++ b/frontend/src/metabase/admin/components/AdminLayout/AdminSettingsLayout.tsx
@@ -3,7 +3,7 @@ import { useEffect, useRef } from "react";
import ErrorBoundary from "metabase/ErrorBoundary";
import { NotFound } from "metabase/common/components/ErrorPages";
-import { useRouter } from "metabase/router/useRouter";
+import { useRouter } from "metabase/router";
import { Box } from "metabase/ui";
import S from "./AdminSettingsLayout.module.css";
diff --git a/frontend/src/metabase/router/Link.ts b/frontend/src/metabase/router/Link.ts
new file mode 100644
index 00000000000..bbdc749cac2
--- /dev/null
+++ b/frontend/src/metabase/router/Link.ts
@@ -0,0 +1,4 @@
+// The single `to`-based Link, mirroring react-router v7's `<Link>`.
+// @see https://reactrouter.com/7.18.1/api/components/Link
+export { Link } from "metabase/common/components/Link";
+export type { LinkProps } from "metabase/common/components/Link";
diff --git a/frontend/src/metabase/router/Link.unit.spec.tsx b/frontend/src/metabase/router/Link.unit.spec.tsx
new file mode 100644
index 00000000000..acbf5bd2c15
--- /dev/null
+++ b/frontend/src/metabase/router/Link.unit.spec.tsx
@@ -0,0 +1,19 @@
+import { Route } from "react-router";
+
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { Link } from "./Link";
+
+describe("router/Link", () => {
+ it("re-exports the to-based Link", () => {
+ const Host = () => <Link to="/foo">go</Link>;
+ renderWithProviders(<Route path="*" component={Host} />, {
+ withRouter: true,
+ });
+
+ expect(screen.getByRole("link", { name: "go" })).toHaveAttribute(
+ "href",
+ "/foo",
+ );
+ });
+});
diff --git a/frontend/src/metabase/router/Navigate.tsx b/frontend/src/metabase/router/Navigate.tsx
new file mode 100644
index 00000000000..2653230d126
--- /dev/null
+++ b/frontend/src/metabase/router/Navigate.tsx
@@ -0,0 +1,34 @@
+import { useEffect } from "react";
+
+import type { To } from "./types";
+import { useNavigate } from "./use-navigate";
+
+export interface NavigateProps {
+ to: To;
+ replace?: boolean;
+ state?: unknown;
+}
+
+/**
+ * react-router v7's `<Navigate>`: navigates to `to` on mount, and again whenever
+ * `to`/`replace`/`state` change. Defaults to a push, pass `replace` to replace
+ * the current history entry.
+ *
+ * @see https://reactrouter.com/7.18.1/api/components/Navigate
+ */
+export function Navigate({ to, replace = false, state }: NavigateProps): null {
+ const navigate = useNavigate();
+
+ // Key the effect on the serialized path (always string-valued, so safe to
+ // stringify) so an equal `to` object recreated each render does not
+ // re-navigate. `state` stays raw in the deps and is passed by reference, both
+ // matching v7's <Navigate>.
+ const jsonTo = JSON.stringify(to);
+
+ useEffect(() => {
+ navigate(to, { replace, state });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [navigate, jsonTo, replace, state]);
+
+ return null;
+}
diff --git a/frontend/src/metabase/router/Navigate.unit.spec.tsx b/frontend/src/metabase/router/Navigate.unit.spec.tsx
new file mode 100644
index 00000000000..9083c7dd6f5
--- /dev/null
+++ b/frontend/src/metabase/router/Navigate.unit.spec.tsx
@@ -0,0 +1,106 @@
+import userEvent from "@testing-library/user-event";
+import { useState } from "react";
+import { Route } from "react-router";
+
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
+
+import { Navigate } from "./Navigate";
+
+// Stable references: `<Navigate>` keeps `state` raw in its effect deps (like v7),
+// so a fresh object literal each render would re-navigate and loop.
+const HOME_STATE = { from: "home" };
+const RICH_STATE = { when: new Date(0), n: NaN };
+
+describe("router/Navigate", () => {
+ it("pushes to the destination on mount, re-asserting it on back", async () => {
+ const Host = () => <Navigate to="/dest" />;
+ const { history } = renderWithProviders(
+ <Route path="*" component={Host} />,
+ {
+ withRouter: true,
+ initialRoute: "/home",
+ },
+ );
+
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/dest"),
+ );
+
+ // Like v7: `navigate`'s identity changes with each navigation, so a mounted
+ // <Navigate> re-fires on the way back and snaps forward to its target again.
+ act(() => history?.goBack());
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/dest"),
+ );
+ });
+
+ it("replaces the current entry and carries state when asked", async () => {
+ const Host = () => <Navigate to="/dest" replace state={HOME_STATE} />;
+ const { history } = renderWithProviders(
+ <Route path="*" component={Host} />,
+ {
+ withRouter: true,
+ initialRoute: "/home",
+ },
+ );
+
+ await waitFor(() => {
+ const location = history?.getCurrentLocation();
+ expect(location?.pathname).toBe("/dest");
+ expect(location?.state).toEqual({ from: "home" });
+ });
+
+ // The replace dropped /home, so there is nothing earlier to go back to.
+ act(() => history?.goBack());
+ expect(history?.getCurrentLocation().pathname).toBe("/dest");
+ });
+
+ it("re-navigates when the target prop changes", async () => {
+ const Host = () => {
+ const [to, setTo] = useState("/first");
+ return (
+ <>
+ <Navigate to={to} />
+ <button onClick={() => setTo("/second")}>change</button>
+ </>
+ );
+ };
+ const { history } = renderWithProviders(
+ <Route path="*" component={Host} />,
+ {
+ withRouter: true,
+ initialRoute: "/home",
+ },
+ );
+
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/first"),
+ );
+
+ await userEvent.click(screen.getByRole("button", { name: "change" }));
+
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/second"),
+ );
+ });
+
+ it("passes state through by reference without serializing it", async () => {
+ const Host = () => <Navigate to="/dest" state={RICH_STATE} />;
+ const { history } = renderWithProviders(
+ <Route path="*" component={Host} />,
+ {
+ withRouter: true,
+ initialRoute: "/home",
+ },
+ );
+
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe("/dest"),
+ );
+
+ const state = history?.getCurrentLocation().state as typeof RICH_STATE;
+ // Serializing would turn the Date into a string and NaN into null.
+ expect(state.when).toBe(RICH_STATE.when);
+ expect(Number.isNaN(state.n)).toBe(true);
+ });
+});
diff --git a/frontend/src/metabase/router/Outlet.tsx b/frontend/src/metabase/router/Outlet.tsx
new file mode 100644
index 00000000000..f2bd3fcea30
--- /dev/null
+++ b/frontend/src/metabase/router/Outlet.tsx
@@ -0,0 +1,33 @@
+import type { ComponentType, ReactNode } from "react";
+import { createContext, useContext } from "react";
+
+const OutletContext = createContext<ReactNode>(null);
+
+/**
+ * react-router v7's `<Outlet>`: renders the matched child route (or nothing when
+ * there is none). On v3 the child is injected as `props.children`, which
+ * `withOutlet` exposes through context.
+ *
+ * @see https://reactrouter.com/7.18.1/api/components/Outlet
+ */
+export function Outlet(): JSX.Element {
+ const child = useContext(OutletContext);
+ return <>{child}</>;
+}
+
+/**
+ * Wraps a v7-style component so it can be used as a react-router v3 route
+ * `component`. The child route that v3 injects as `props.children` is exposed
+ * through context, letting the wrapped component render it with `<Outlet/>`.
+ */
+export function withOutlet(
+ Component: ComponentType,
+): ComponentType<{ children?: ReactNode }> {
+ return function RouteWithOutlet({ children }) {
+ return (
+ <OutletContext.Provider value={children}>
+ <Component />
+ </OutletContext.Provider>
+ );
+ };
+}
diff --git a/frontend/src/metabase/router/Outlet.unit.spec.tsx b/frontend/src/metabase/router/Outlet.unit.spec.tsx
new file mode 100644
index 00000000000..bb56570abd3
--- /dev/null
+++ b/frontend/src/metabase/router/Outlet.unit.spec.tsx
@@ -0,0 +1,28 @@
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { Outlet, withOutlet } from "./Outlet";
+
+function ParentPage() {
+ return (
+ <div>
+ <span>parent chrome</span>
+ <Outlet />
+ </div>
+ );
+}
+
+describe("router/Outlet", () => {
+ it("renders the matched child exposed by withOutlet", () => {
+ const RoutedParent = withOutlet(ParentPage);
+
+ renderWithProviders(<RoutedParent>child content</RoutedParent>);
+
+ expect(screen.getByText("parent chrome")).toBeInTheDocument();
+ expect(screen.getByText("child content")).toBeInTheDocument();
+ });
+
+ it("renders nothing when there is no matched child", () => {
+ renderWithProviders(<Outlet />);
+ expect(screen.queryByText("child content")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index d13f0355f5c..acb62de5de0 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -1,2 +1,10 @@
-export * from "./useRouter";
+export * from "./Link";
+export * from "./Navigate";
+export * from "./Outlet";
export * from "./RouterProvider";
+export * from "./types";
+export * from "./use-location";
+export * from "./use-navigate";
+export * from "./use-params";
+export * from "./use-router";
+export * from "./use-search-params";
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
new file mode 100644
index 00000000000..2a346ef1b2c
--- /dev/null
+++ b/frontend/src/metabase/router/types.ts
@@ -0,0 +1,86 @@
+/**
+ * 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>;
+
+/**
+ * An entry in a history stack. A location contains information about the URL
+ * path, as well as possibly some arbitrary state and a key.
+ *
+ * @see https://api.reactrouter.com/v7/interfaces/react-router.Location.html
+ */
+export interface Location<State = unknown> {
+ pathname: string;
+ search: string;
+ hash: string;
+ state: State;
+ key: string;
+}
+
+/**
+ * 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;
+}
+
+/**
+ * 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;
diff --git a/frontend/src/metabase/router/use-location.ts b/frontend/src/metabase/router/use-location.ts
new file mode 100644
index 00000000000..9c46083a1fa
--- /dev/null
+++ b/frontend/src/metabase/router/use-location.ts
@@ -0,0 +1,33 @@
+import { useMemo } from "react";
+
+import type { Location } from "./types";
+import { useRouter } from "./use-router";
+
+/**
+ * react-router v7's `useLocation`, implemented over the v3 location injected
+ * into the router context (mirrored into redux `state.routing`). Returns the v7
+ * `Location` shape (no v3 `query` field).
+ *
+ * @see https://reactrouter.com/7.18.1/api/hooks/useLocation
+ */
+export function useLocation(): Location {
+ const { location } = useRouter();
+
+ return useMemo(
+ () => ({
+ pathname: location.pathname,
+ search: location.search,
+ hash: location.hash,
+ // v3 leaves state `undefined` when absent, v7 uses `null`.
+ state: location.state ?? null,
+ key: location.key,
+ }),
+ [
+ location.pathname,
+ location.search,
+ location.hash,
+ location.state,
+ location.key,
+ ],
+ );
+}
diff --git a/frontend/src/metabase/router/use-location.unit.spec.tsx b/frontend/src/metabase/router/use-location.unit.spec.tsx
new file mode 100644
index 00000000000..67bd17d91c0
--- /dev/null
+++ b/frontend/src/metabase/router/use-location.unit.spec.tsx
@@ -0,0 +1,52 @@
+import { Route } from "react-router";
+
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { useLocation } from "./use-location";
+
+function LocationProbe() {
+ const location = useLocation();
+ return (
+ <div>
+ <span data-testid="pathname">{location.pathname}</span>
+ <span data-testid="search">{location.search}</span>
+ <span data-testid="hash">{location.hash}</span>
+ <span data-testid="keys">{Object.keys(location).sort().join(",")}</span>
+ <span data-testid="state">{JSON.stringify(location.state)}</span>
+ </div>
+ );
+}
+
+describe("router/useLocation", () => {
+ it("exposes the current location in v7 shape", () => {
+ renderWithProviders(<Route path="foo/bar" component={LocationProbe} />, {
+ withRouter: true,
+ initialRoute: "/foo/bar?x=1&y=2#section",
+ });
+
+ expect(screen.getByTestId("pathname")).toHaveTextContent("/foo/bar");
+ expect(screen.getByTestId("search")).toHaveTextContent("?x=1&y=2");
+ expect(screen.getByTestId("hash")).toHaveTextContent("#section");
+ });
+
+ it("returns exactly the v7 Location fields, without v3's `query`", () => {
+ renderWithProviders(<Route path="foo/bar" component={LocationProbe} />, {
+ withRouter: true,
+ initialRoute: "/foo/bar?x=1",
+ });
+
+ // v7's Location is exactly { pathname, search, hash, state, key }, no `query`.
+ expect(screen.getByTestId("keys")).toHaveTextContent(
+ /^hash,key,pathname,search,state$/,
+ );
+ });
+
+ it("defaults state to null like v7 (not v3's undefined)", () => {
+ renderWithProviders(<Route path="foo/bar" component={LocationProbe} />, {
+ withRouter: true,
+ initialRoute: "/foo/bar",
+ });
+
+ expect(screen.getByTestId("state")).toHaveTextContent(/^null$/);
+ });
+});
diff --git a/frontend/src/metabase/router/use-navigate.ts b/frontend/src/metabase/router/use-navigate.ts
new file mode 100644
index 00000000000..8eb471f49fb
--- /dev/null
+++ b/frontend/src/metabase/router/use-navigate.ts
@@ -0,0 +1,59 @@
+import type { LocationDescriptor } from "history";
+import { useCallback } from "react";
+
+import type { NavigateFunction, NavigateOptions, To } from "./types";
+import { useRouter } from "./use-router";
+import { parsePath } from "./utils";
+
+function toLocationDescriptor(to: To, state: unknown): LocationDescriptor {
+ if (typeof to === "string" && state === undefined) {
+ return to;
+ }
+ if (typeof to === "string") {
+ return { ...parsePath(to), state };
+ }
+ return { ...to, state };
+}
+
+/**
+ * react-router v7's `useNavigate`, implemented over react-router v3's imperative
+ * router (`router.push/replace/go`).
+ *
+ * - `navigate(to, { replace?, state? })` pushes (or replaces) the location.
+ * - `navigate(delta)` moves through the history stack (e.g. `navigate(-1)`).
+ *
+ * Absolute paths only: v7's relative `to` (`".."`, `"child"`) is not resolved on
+ * v3, that lands with the engine swap and modal routes (Phase 1.3).
+ *
+ * The returned function gets a new identity whenever the pathname changes, like
+ * v7 (whose callback depends on the current pathname). Keeping it stable would
+ * be nicer, but it would diverge: a mounted `<Navigate>` would stop re-asserting
+ * its target, and effects keyed on `navigate` would run a different number of
+ * times, so code written against the facade would behave differently after the
+ * swap.
+ *
+ * @see https://reactrouter.com/7.18.1/api/hooks/useNavigate
+ */
+export function useNavigate(): NavigateFunction {
+ const { router, location } = useRouter();
+
+ return useCallback(
+ (to: To | number, options: NavigateOptions = {}) => {
+ if (typeof to === "number") {
+ router.go(to);
+ return;
+ }
+
+ const descriptor = toLocationDescriptor(to, options.state);
+ if (options.replace) {
+ router.replace(descriptor);
+ } else {
+ router.push(descriptor);
+ }
+ },
+ // location.pathname does not affect a single call, it is here to give
+ // `navigate` a new identity per navigation, matching v7.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [router, location.pathname],
+ ) as NavigateFunction;
+}
diff --git a/frontend/src/metabase/router/use-navigate.unit.spec.tsx b/frontend/src/metabase/router/use-navigate.unit.spec.tsx
new file mode 100644
index 00000000000..d84f1b43746
--- /dev/null
+++ b/frontend/src/metabase/router/use-navigate.unit.spec.tsx
@@ -0,0 +1,87 @@
+import userEvent from "@testing-library/user-event";
+import { Route } from "react-router";
+
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { useNavigate } from "./use-navigate";
+
+function NavigateProbe() {
+ const navigate = useNavigate();
+ return (
+ <div>
+ <button onClick={() => navigate("/foo")}>push</button>
+ <button onClick={() => navigate("/bar", { state: { from: "here" } })}>
+ push-state
+ </button>
+ <button onClick={() => navigate({ pathname: "/obj", search: "?x=1" })}>
+ push-object
+ </button>
+ <button onClick={() => navigate("/bar?x=1", { state: { from: "here" } })}>
+ push-string-query-state
+ </button>
+ <button onClick={() => navigate("/baz", { replace: true })}>
+ replace
+ </button>
+ <button onClick={() => navigate(-1)}>back</button>
+ </div>
+ );
+}
+
+function setup(initialRoute = "/") {
+ return renderWithProviders(<Route path="*" component={NavigateProbe} />, {
+ withRouter: true,
+ initialRoute,
+ });
+}
+
+const click = (name: string) =>
+ userEvent.click(screen.getByRole("button", { name }));
+
+describe("router/useNavigate", () => {
+ it("pushes a string destination", async () => {
+ const { history } = setup();
+ await click("push");
+ expect(history?.getCurrentLocation().pathname).toBe("/foo");
+ });
+
+ it("attaches history state to the destination", async () => {
+ const { history } = setup();
+ await click("push-state");
+ const location = history?.getCurrentLocation();
+ expect(location?.pathname).toBe("/bar");
+ expect(location?.state).toEqual({ from: "here" });
+ });
+
+ it("navigates to an object destination", async () => {
+ const { history } = setup();
+ await click("push-object");
+ const location = history?.getCurrentLocation();
+ expect(location?.pathname).toBe("/obj");
+ expect(location?.search).toBe("?x=1");
+ });
+
+ it("splits a string destination carrying both a query and state", async () => {
+ const { history } = setup();
+ await click("push-string-query-state");
+ const location = history?.getCurrentLocation();
+ // The query must land in `search`, not be left glued onto `pathname`.
+ expect(location?.pathname).toBe("/bar");
+ expect(location?.search).toBe("?x=1");
+ expect(location?.state).toEqual({ from: "here" });
+ });
+
+ it("replaces the current entry instead of pushing", async () => {
+ const { history } = setup("/start");
+ await click("push"); // /foo
+ await click("replace"); // replaces /foo with /baz
+ await click("back");
+ expect(history?.getCurrentLocation().pathname).toBe("/start");
+ });
+
+ it("moves through the history stack with a numeric delta", async () => {
+ const { history } = setup("/start");
+ await click("push"); // /foo
+ await click("back"); // navigate(-1)
+ expect(history?.getCurrentLocation().pathname).toBe("/start");
+ });
+});
diff --git a/frontend/src/metabase/router/use-params.ts b/frontend/src/metabase/router/use-params.ts
new file mode 100644
index 00000000000..d7bd8e6c699
--- /dev/null
+++ b/frontend/src/metabase/router/use-params.ts
@@ -0,0 +1,28 @@
+import type { Params } from "./types";
+import { useRouter } from "./use-router";
+
+/**
+ * react-router v7's `useParams`, implemented over the params injected by
+ * react-router v3 into the router context. Values are URI-decoded like v7, and
+ * the v3 splat param (`splat`) is exposed under v7's `*` key.
+ *
+ * @see https://reactrouter.com/7.18.1/api/hooks/useParams
+ */
+export function useParams<
+ ParamsOrKey extends string | Record<string, string | undefined> = string,
+>(): Readonly<
+ [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>
+> {
+ type Result = Readonly<
+ [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>
+ >;
+ const params = useRouter().params;
+
+ if (!("splat" in params)) {
+ return params as Result;
+ }
+
+ const { splat, ...rest } = params;
+ const remapped: typeof params = { ...rest, "*": splat };
+ return remapped as Result;
+}
diff --git a/frontend/src/metabase/router/use-params.unit.spec.tsx b/frontend/src/metabase/router/use-params.unit.spec.tsx
new file mode 100644
index 00000000000..f30284cdb16
--- /dev/null
+++ b/frontend/src/metabase/router/use-params.unit.spec.tsx
@@ -0,0 +1,53 @@
+import { Route } from "react-router";
+
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { useParams } from "./use-params";
+
+function ParamsProbe() {
+ const { segmentId, fieldId } = useParams();
+ return (
+ <div>
+ <span data-testid="segment">{segmentId}</span>
+ <span data-testid="field">{fieldId}</span>
+ </div>
+ );
+}
+
+function SplatProbe() {
+ const params = useParams();
+ return (
+ <div>
+ <span data-testid="splat">{params["*"]}</span>
+ <span data-testid="has-splat-key">{String("splat" in params)}</span>
+ </div>
+ );
+}
+
+describe("router/useParams", () => {
+ it("returns the params matched by the v3 route", () => {
+ renderWithProviders(
+ <Route
+ path="reference/segments/:segmentId/fields/:fieldId"
+ component={ParamsProbe}
+ />,
+ {
+ withRouter: true,
+ initialRoute: "/reference/segments/42/fields/7",
+ },
+ );
+
+ expect(screen.getByTestId("segment")).toHaveTextContent("42");
+ expect(screen.getByTestId("field")).toHaveTextContent("7");
+ });
+
+ it("exposes the splat under v7's `*` key, not v3's `splat`", () => {
+ renderWithProviders(<Route path="files/**" component={SplatProbe} />, {
+ withRouter: true,
+ initialRoute: "/files/a/b",
+ });
+
+ expect(screen.getByTestId("splat")).toHaveTextContent("a/b");
+ expect(screen.getByTestId("has-splat-key")).toHaveTextContent("false");
+ });
+});
diff --git a/frontend/src/metabase/router/useRouter.tsx b/frontend/src/metabase/router/use-router.tsx
similarity index 100%
rename from frontend/src/metabase/router/useRouter.tsx
rename to frontend/src/metabase/router/use-router.tsx
diff --git a/frontend/src/metabase/router/use-search-params.ts b/frontend/src/metabase/router/use-search-params.ts
new file mode 100644
index 00000000000..3924745a80e
--- /dev/null
+++ b/frontend/src/metabase/router/use-search-params.ts
@@ -0,0 +1,64 @@
+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.tsx
new file mode 100644
index 00000000000..6c88b76dc74
--- /dev/null
+++ b/frontend/src/metabase/router/use-search-params.unit.spec.tsx
@@ -0,0 +1,176 @@
+import userEvent from "@testing-library/user-event";
+import { Route } from "react-router";
+
+import { act, renderWithProviders, screen } from "__support__/ui";
+
+import { useSearchParams } from "./use-search-params";
+
+function SearchParamsProbe() {
+ const [searchParams, setSearchParams] = useSearchParams();
+ return (
+ <div>
+ <span data-testid="x">{searchParams.get("x")}</span>
+ <span data-testid="y">{searchParams.get("y")}</span>
+ <span data-testid="brand">{searchParams.getAll("brand").join(",")}</span>
+ <span data-testid="is-url-search-params">
+ {String(searchParams instanceof URLSearchParams)}
+ </span>
+ <button onClick={() => setSearchParams({ x: "2", y: "9" })}>set</button>
+ <button onClick={() => setSearchParams({ brand: ["nike", "reebok"] })}>
+ set-array
+ </button>
+ <button onClick={() => setSearchParams()}>clear</button>
+ <button
+ onClick={() =>
+ setSearchParams((prev) => {
+ prev.set("x", "3");
+ return prev;
+ })
+ }
+ >
+ update
+ </button>
+ </div>
+ );
+}
+
+function setup(initialRoute: string) {
+ return renderWithProviders(
+ <Route path="foo" component={SearchParamsProbe} />,
+ {
+ withRouter: true,
+ initialRoute,
+ },
+ );
+}
+
+const click = (name: string) =>
+ userEvent.click(screen.getByRole("button", { name }));
+
+describe("router/useSearchParams", () => {
+ it("reads the current query string as a URLSearchParams", () => {
+ setup("/foo?x=1");
+
+ expect(screen.getByTestId("x")).toHaveTextContent("1");
+ expect(screen.getByTestId("is-url-search-params")).toHaveTextContent(
+ "true",
+ );
+ });
+
+ it("navigates to the new query string when set", async () => {
+ const { history } = setup("/foo?x=1");
+
+ await click("set");
+
+ expect(screen.getByTestId("x")).toHaveTextContent("2");
+ expect(screen.getByTestId("y")).toHaveTextContent("9");
+ expect(history?.getCurrentLocation().pathname).toBe("/foo");
+ expect(history?.getCurrentLocation().search).toBe("?x=2&y=9");
+ });
+
+ it("pushes by default so the previous query stays in history", async () => {
+ const { history } = setup("/foo?x=1");
+
+ await click("set");
+ expect(screen.getByTestId("x")).toHaveTextContent("2");
+
+ act(() => history?.goBack());
+ expect(screen.getByTestId("x")).toHaveTextContent("1");
+ });
+
+ it("expands array values into repeated params", async () => {
+ setup("/foo");
+
+ await click("set-array");
+
+ expect(screen.getByTestId("brand")).toHaveTextContent("nike,reebok");
+ });
+
+ it("supports a functional updater over the previous params", async () => {
+ setup("/foo?x=1");
+
+ await click("update");
+
+ expect(screen.getByTestId("x")).toHaveTextContent("3");
+ });
+
+ it("clears the query when called without an argument", async () => {
+ const { history } = setup("/foo?x=1");
+
+ await click("clear");
+
+ expect(screen.getByTestId("x")).toBeEmptyDOMElement();
+ expect(history?.getCurrentLocation().search).toBe("");
+ });
+
+ it("gives the functional updater a clone, not the held instance", async () => {
+ let held: URLSearchParams | undefined;
+ const MutatingProbe = () => {
+ const [searchParams, setSearchParams] = useSearchParams();
+ held = searchParams;
+ return (
+ <button
+ onClick={() =>
+ setSearchParams((prev) => {
+ prev.set("x", "mutated");
+ return prev;
+ })
+ }
+ >
+ mutate
+ </button>
+ );
+ };
+ renderWithProviders(<Route path="foo" component={MutatingProbe} />, {
+ withRouter: true,
+ initialRoute: "/foo?x=1",
+ });
+
+ const before = held;
+ await userEvent.click(screen.getByRole("button", { name: "mutate" }));
+
+ // The instance the component held is untouched: the updater mutated a clone.
+ expect(before?.get("x")).toBe("1");
+ });
+});
+
+function DefaultProbe() {
+ const [searchParams, setSearchParams] = useSearchParams({ page: "1" });
+ return (
+ <div>
+ <span data-testid="page">{searchParams.get("page")}</span>
+ <span data-testid="q">{searchParams.get("q")}</span>
+ <button onClick={() => setSearchParams({ q: "x" })}>set-other</button>
+ </div>
+ );
+}
+
+function setupDefault(initialRoute: string) {
+ return renderWithProviders(<Route path="foo" component={DefaultProbe} />, {
+ withRouter: true,
+ initialRoute,
+ });
+}
+
+describe("router/useSearchParams defaultInit", () => {
+ it("fills in a default the URL is missing", () => {
+ setupDefault("/foo");
+ expect(screen.getByTestId("page")).toHaveTextContent("1");
+ });
+
+ it("lets the URL value win over the default", () => {
+ setupDefault("/foo?page=5");
+ expect(screen.getByTestId("page")).toHaveTextContent("5");
+ });
+
+ it("stops merging the default once params have been set", async () => {
+ setupDefault("/foo");
+ expect(screen.getByTestId("page")).toHaveTextContent("1");
+
+ await userEvent.click(screen.getByRole("button", { name: "set-other" }));
+
+ // Once set, the default no longer reappears, so it does not stick forever.
+ expect(screen.getByTestId("q")).toHaveTextContent("x");
+ expect(screen.getByTestId("page")).toBeEmptyDOMElement();
+ });
+});
diff --git a/frontend/src/metabase/router/utils.ts b/frontend/src/metabase/router/utils.ts
new file mode 100644
index 00000000000..9014cf55069
--- /dev/null
+++ b/frontend/src/metabase/router/utils.ts
@@ -0,0 +1,75 @@
+import type { Path, URLSearchParamsInit } from "./types";
+
+/**
+ * Split a path string into `pathname`, `search`, and `hash`, mirroring
+ * react-router v7's `parsePath`. Used when a string destination has to be
+ * combined with history `state` into a v3 location descriptor.
+ */
+export function parsePath(path: string): Path {
+ let pathname = path;
+ let search = "";
+ let hash = "";
+
+ const hashIndex = pathname.indexOf("#");
+ if (hashIndex >= 0) {
+ hash = pathname.slice(hashIndex);
+ pathname = pathname.slice(0, hashIndex);
+ }
+
+ const searchIndex = pathname.indexOf("?");
+ if (searchIndex >= 0) {
+ search = pathname.slice(searchIndex);
+ pathname = pathname.slice(0, searchIndex);
+ }
+
+ return { pathname, search, hash };
+}
+
+/**
+ * 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;
+}