Skip to content

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

Host the app on the react-router data router (#78655)

Romeo Van Snick9a3add685a71
diff --git a/frontend/src/metabase/router/Navigate.tsx b/frontend/src/metabase/router/Navigate.tsx
index 2653230d126..a4405596ed5 100644
--- a/frontend/src/metabase/router/Navigate.tsx
+++ b/frontend/src/metabase/router/Navigate.tsx
@@ -1,6 +1,7 @@
import { useEffect } from "react";
import type { To } from "./types";
+import { useLocation } from "./use-location";
import { useNavigate } from "./use-navigate";
export interface NavigateProps {
@@ -18,6 +19,13 @@ export interface NavigateProps {
*/
export function Navigate({ to, replace = false, state }: NavigateProps): null {
const navigate = useNavigate();
+ // A mounted `<Navigate>` re-asserts its target when the location moves out
+ // from under it, so going back lands forward again. That used to fall out of
+ // `navigate`'s identity churning per location, which only the declarative
+ // `useNavigate` does: inside a data router it is stable across navigations.
+ // Depend on the pathname directly so the behavior does not rest on which
+ // variant is in play.
+ const { pathname } = useLocation();
// Key the effect on the serialized path (always string-valued, so safe to
// stringify) so an equal `to` object recreated each render does not
@@ -28,7 +36,7 @@ export function Navigate({ to, replace = false, state }: NavigateProps): null {
useEffect(() => {
navigate(to, { replace, state });
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [navigate, jsonTo, replace, state]);
+ }, [navigate, pathname, jsonTo, replace, state]);
return null;
}
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 7831e7948b9..cfe6e1ba8e5 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -14,7 +14,11 @@ export * from "./use-navigation-type";
export * from "./use-params";
export * from "./use-route-leave-hook";
export * from "./use-search-params";
-export { getRawBrowserHistory } from "./v7/blocking-history";
+export {
+ createMemoryAppRouter,
+ type MemoryTestRouter,
+ type MemoryTestRouterHolder,
+} from "./v7/create-router";
export { queryToSearch, toFacadeLocation } from "./v7/location";
export {
createLocationMirror,
@@ -25,11 +29,8 @@ export {
subscribeLocation,
toNavigateArgs,
} from "./v7/navigator";
-// The memory-history engine is test-only. It reaches the barrel rather than a
+export { getRawBrowserHistory } from "./v7/raw-history";
+// The memory-router engine is test-only. It reaches the barrel rather than a
// deep import because `sideEffects: false` lets rspack drop it from the app
// bundles, where nothing references it.
-export {
- createMemoryTestHistory,
- type MemoryTestHistory,
- RouterProviderV7Memory,
-} from "./v7/RouterProviderV7";
+export { RouterProviderV7Memory } from "./v7/RouterProviderV7";
diff --git a/frontend/src/metabase/router/use-route-leave-hook.ts b/frontend/src/metabase/router/use-route-leave-hook.ts
index 9ef079e0058..63a138040a3 100644
--- a/frontend/src/metabase/router/use-route-leave-hook.ts
+++ b/frontend/src/metabase/router/use-route-leave-hook.ts
@@ -2,7 +2,7 @@ import { useContext, useEffect, useRef } from "react";
import { UNSAFE_RouteContext } from "react-router";
import type { RouteHook } from "./types";
-import { registerLeaveHook } from "./v7/blocking-history";
+import { registerLeaveHook } from "./v7/leave-hooks";
/**
* Register a hook that runs before a navigation leaves the route this component
diff --git a/frontend/src/metabase/router/v7/AppShell.tsx b/frontend/src/metabase/router/v7/AppShell.tsx
new file mode 100644
index 00000000000..6c1aaf0826e
--- /dev/null
+++ b/frontend/src/metabase/router/v7/AppShell.tsx
@@ -0,0 +1,26 @@
+import { useEffect } from "react";
+import { Outlet, useNavigate } from "react-router";
+
+import { setV7Navigate } from "./navigator";
+
+/**
+ * The element of the host's pathless layout route.
+ *
+ * It registers the router's `navigate` for the redux navigator adapter, so
+ * `dispatch(push(...))` drives the router. Registering from here rather than
+ * from the router object matters for a relative target: `router.navigate`
+ * resolves it against the deepest matched route, while this route contributes no
+ * path and so resolves from the root. Redux navigation carries no route context
+ * of its own, and history@3 resolved a relative push against the root, so root
+ * is the behavior to keep (`SearchBar` pushes `{ pathname: "search" }`).
+ */
+export function AppShell(): JSX.Element {
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ setV7Navigate(navigate);
+ return () => setV7Navigate(null);
+ }, [navigate]);
+
+ return <Outlet />;
+}
diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
index 670d28d78b8..9d12d71e992 100644
--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx
+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
@@ -1,46 +1,66 @@
import type { PropsWithChildren } from "react";
-import { useState } from "react";
-import {
- type HistoryRouterProps,
- Routes,
- UNSAFE_createBrowserHistory as createBrowserHistory,
- UNSAFE_createMemoryHistory as createMemoryHistory,
-} from "react-router";
+import { useLayoutEffect, useState } from "react";
+import { type DataRouter, RouterProvider } from "react-router";
import { getBasename } from "metabase/utils/basename";
-import { SyncHistoryRouter } from "./SyncHistoryRouter";
-import { V7RouterBridge } from "./V7RouterBridge";
-import { withBlocking } from "./blocking-history";
+import {
+ type MemoryTestRouterHolder,
+ createAppRouter,
+ createMemoryAppRouter,
+} from "./create-router";
import type { LocationMirror } from "./location-mirror";
-import { mapToV7 } from "./map-to-v7";
/**
- * The v7 route tree: the facade tree mapped to real v7 routes and rendered by
- * `<Routes>`, plus the bridge that publishes the live `navigate` and mirrors the
- * location out to `onLocationChange`. Kept separate from the history provider
- * below so tests can host the same tree under a `<MemoryRouter>`.
+ * Mirrors every location out to `onLocationChange`, which is how the app emits
+ * LOCATION_CHANGE on navigation (see `createLocationMirror`). Replaces v3's
+ * `syncHistoryWithStore`.
+ *
+ * Subscribing to the router rather than reading the rendered location matters
+ * because v3 dispatched LOCATION_CHANGE as part of the transition rather than
+ * after a render. Thunks read the store synchronously right after navigating, so
+ * a store that lags a render makes them push a stale location and clobber query
+ * params that were just set.
*/
-export function V7RouterTree({
- children,
- history,
- onLocationChange,
-}: PropsWithChildren<{
- history?: HistoryRouterProps["history"];
- onLocationChange?: LocationMirror;
-}>): JSX.Element {
- return (
- <>
- <V7RouterBridge history={history} onLocationChange={onLocationChange} />
- <Routes>{mapToV7(children)}</Routes>
- </>
- );
+function useLocationMirror(
+ router: DataRouter,
+ onLocationChange?: LocationMirror,
+): void {
+ useLayoutEffect(() => {
+ if (!onLocationChange) {
+ return;
+ }
+ // The router notifies its subscribers on every state update, not only on a
+ // location change, and replays the state it initialized with to the first
+ // subscriber. Key on the location so neither is mirrored twice.
+ let lastKey: string | null = null;
+
+ const mirror = ({ location }: DataRouter["state"]) => {
+ if (location.key === lastKey) {
+ return;
+ }
+ lastKey = location.key;
+ onLocationChange(location);
+ };
+
+ mirror(router.state);
+ return router.subscribe(mirror);
+ }, [router, onLocationChange]);
}
/**
- * react-router v7 hosting the app, declarative mode. Replaces the v3 `<Router>` +
- * `useRouterHistory` + `syncHistoryWithStore` stack. Hosted on a blocking history
- * so a registered leave hook cancels navigation the way it did on v3.
+ * react-router v7 hosting the app as a data router. The whole facade tree goes
+ * in as real data routes, so there is no descendant `<Routes>` left. No route
+ * has a loader, `lazy`, or middleware yet: adding those per subtree is what
+ * DEV-2291 does from here.
+ *
+ * `useTransitions={false}` keeps navigation committing synchronously.
+ * react-router otherwise marks its own location update as a transition, which in
+ * a production React build deprioritises it so it can commit long after the click
+ * that caused it. v3 navigated synchronously, and the app was written against
+ * that: a navigation that lands mid-interaction remounts whatever is on screen,
+ * which silently discarded state such as the text typed into a modal that was
+ * opened right after clicking a link.
*
* `onLocationChange` is how the location reaches redux: the app passes
* `createLocationMirror(store.dispatch)`, so the router itself stays unaware of
@@ -50,72 +70,39 @@ export function RouterProviderV7({
children,
onLocationChange,
}: PropsWithChildren<{ onLocationChange?: LocationMirror }>): JSX.Element {
- // `v5Compat` makes the history notify its listeners on push/replace, which is
- // what `unstable_HistoryRouter` and the blocking wrapper both rely on.
- const [history] = useState(() =>
- withBlocking(createBrowserHistory({ v5Compat: true })),
- );
- return (
- <SyncHistoryRouter
- history={history}
- basename={getBasename() || undefined}
- onLocationChange={onLocationChange}
- >
- <V7RouterTree history={history} onLocationChange={onLocationChange}>
- {children}
- </V7RouterTree>
- </SyncHistoryRouter>
+ const [router] = useState(() =>
+ createAppRouter(children, getBasename() || undefined),
);
-}
+ useLocationMirror(router, onLocationChange);
-/**
- * The in-memory blocking history the test engine runs on. Exposed so the test
- * harness can own the instance and hand tests a handle on it, rather than it
- * being created (and trapped) inside the provider.
- */
-export function createMemoryTestHistory(initialRoute: string) {
- // history@3 resolved a relative initial entry against the root; v7 keeps it
- // relative, and a location without a leading slash then matches no route. Specs
- // written against v3 pass both forms, so normalize.
- const entry = initialRoute.startsWith("/")
- ? initialRoute
- : `/${initialRoute}`;
- return withBlocking(
- createMemoryHistory({ initialEntries: [entry], v5Compat: true }),
- );
+ return <RouterProvider router={router} useTransitions={false} />;
}
-export type MemoryTestHistory = ReturnType<typeof createMemoryTestHistory>;
-
/**
* The v7 engine hosted on an in-memory history, for tests. Mirrors what
- * `renderWithProviders({ routerEngine: "v7" })` mounts, including navigation
- * blocking. Pass `history` to drive and inspect it from outside the tree.
+ * `renderWithProviders({ withRouter: true })` mounts, including navigation
+ * blocking. Pass `router` to drive and inspect it from outside the tree.
*/
export function RouterProviderV7Memory({
children,
initialRoute,
basename,
- history: providedHistory,
+ routerHolder,
onLocationChange,
}: PropsWithChildren<{
initialRoute: string;
basename?: string;
- history?: MemoryTestHistory;
+ routerHolder?: MemoryTestRouterHolder;
onLocationChange?: LocationMirror;
}>): JSX.Element {
- const [history] = useState(
- () => providedHistory ?? createMemoryTestHistory(initialRoute),
- );
- return (
- <SyncHistoryRouter
- history={history}
- basename={basename}
- onLocationChange={onLocationChange}
- >
- <V7RouterTree history={history} onLocationChange={onLocationChange}>
- {children}
- </V7RouterTree>
- </SyncHistoryRouter>
- );
+ const [router] = useState(() => {
+ const created = createMemoryAppRouter(children, initialRoute, basename);
+ if (routerHolder) {
+ routerHolder.current = created;
+ }
+ return created;
+ });
+ useLocationMirror(router, onLocationChange);
+
+ return <RouterProvider router={router} useTransitions={false} />;
}
diff --git a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
deleted file mode 100644
index 1592da47417..00000000000
--- a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import type { PropsWithChildren } from "react";
-import { useLayoutEffect, useRef, useState } from "react";
-import {
- type HistoryRouterProps,
- type NavigationType,
- Router,
- type Location as V7Location,
-} from "react-router";
-
-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 LOCATION_CHANGE
- * is dispatched as part of the transition the way v3's `syncHistoryWithStore` did,
- * and the reducers keyed off it settle before the next render. 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) => 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);
- return history.listen((update) => {
- setState(update);
- onLocationChangeRef.current?.(update.location);
- });
- }, [history]);
-
- return (
- <Router
- basename={basename}
- location={state.location}
- navigationType={state.action}
- navigator={history}
- >
- {children}
- </Router>
- );
-}
diff --git a/frontend/src/metabase/router/v7/V7RouterBridge.tsx b/frontend/src/metabase/router/v7/V7RouterBridge.tsx
deleted file mode 100644
index e3a0e96e514..00000000000
--- a/frontend/src/metabase/router/v7/V7RouterBridge.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useEffect, useRef } from "react";
-import {
- type HistoryRouterProps,
- useLocation as useV7Location,
- useNavigate as useV7Navigate,
-} from "react-router";
-
-import type { LocationMirror } from "./location-mirror";
-import { setV7Navigate } from "./navigator";
-
-/**
- * Wires the live v7 router to the rest of the app, 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;
- * - calls `onLocationChange` for every location, which is how the app emits
- * LOCATION_CHANGE on navigation (see `createLocationMirror`).
- *
- * The mirror is driven from the history subscription when one is passed, because
- * v3 dispatched LOCATION_CHANGE as part of the transition rather than after a
- * render. Falls back to the rendered location when no history is available,
- * which is how tests mount the tree under a plain `<MemoryRouter>`.
- */
-export function V7RouterBridge({
- history,
- onLocationChange,
-}: {
- history?: HistoryRouterProps["history"];
- onLocationChange?: LocationMirror;
-}): null {
- const navigate = useV7Navigate();
- const location = useV7Location();
-
- // Read through a ref so a new callback identity does not re-run the mirror for
- // a location that has not changed.
- const onLocationChangeRef = useRef(onLocationChange);
- onLocationChangeRef.current = onLocationChange;
-
- useEffect(() => {
- setV7Navigate(navigate);
- return () => setV7Navigate(null);
- }, [navigate]);
-
- // When a history is provided the mirroring happens synchronously in
- // `SyncHistoryRouter`'s subscription instead, so nothing to do here.
- useEffect(() => {
- if (history) {
- return;
- }
- onLocationChangeRef.current?.(location);
- }, [history, location]);
-
- return null;
-}
diff --git a/frontend/src/metabase/router/v7/blocking-history.ts b/frontend/src/metabase/router/v7/blocking-history.ts
deleted file mode 100644
index 28fd59975af..00000000000
--- a/frontend/src/metabase/router/v7/blocking-history.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import {
- type HistoryRouterProps,
- type To,
- type Location as V7Location,
- UNSAFE_createBrowserHistory as createBrowserHistory,
- parsePath,
-} from "react-router";
-
-import type { Action, Location as HistoryLocation } from "../types";
-
-import { toFacadeLocation } from "./location";
-
-// react-router does not export the `History` interface directly, so pull it off
-// the history prop of `unstable_HistoryRouter`, which is exactly the type the
-// router accepts and the blocking wrapper returns.
-type History = HistoryRouterProps["history"];
-
-/**
- * A route-leave hook: it receives the attempted destination and how it was
- * reached, and returns `false` to cancel the navigation. The navigation type is
- * a second argument rather than a field on the location, which carries only the
- * URL parts on v7.
- */
-type LeaveHook = (
- nextLocation?: HistoryLocation,
- navigationType?: Action,
-) => unknown;
-
-interface Registration {
- hook: LeaveHook;
- // The matched pathname of the guarded route. A leave hook is scoped to a route
- // and only fires when a navigation leaves that route's subtree, so a hook with
- // a base path does not fire for destinations that stay under it.
- basePath?: string;
-}
-
-const registrations = new Set<Registration>();
-
-let rawBrowserHistory: History | null = null;
-
-/**
- * A plain browser history for imperative navigation outside the app's router
- * tree, replacing v3's global `browserHistory` singleton. The SDK data-app bundle
- * mounts no router, so it drives its iframe URL through this instead. Created
- * lazily on first use, so it never exists in the main app, where a second history
- * would fight the mounted router over `popstate`.
- */
-export function getRawBrowserHistory(): History {
- rawBrowserHistory ??= createBrowserHistory({ v5Compat: true });
- return rawBrowserHistory;
-}
-
-/**
- * Register a leave hook, so the leave-confirm modals block navigation the way
- * they did on v3. `useRouteLeaveHook` is the call site; `basePath` scopes the
- * hook to a route, so it fires only when the destination leaves that route's
- * subtree, matching v3's `listenBeforeLeavingRoute`. Returns the unregister
- * function the caller uses as effect cleanup.
- */
-export function registerLeaveHook(
- hook: LeaveHook,
- basePath?: string,
-): () => void {
- const registration: Registration = { hook, basePath };
- registrations.add(registration);
- return () => {
- registrations.delete(registration);
- };
-}
-
-/**
- * Whether any leave hook is currently registered. The `beforeunload` guard lives
- * at the call sites (`useBeforeUnload`), so this is exposed only for assertions.
- */
-export function hasLeaveHooks(): boolean {
- return registrations.size > 0;
-}
-
-function staysWithin(basePath: string | undefined, pathname: string): boolean {
- if (!basePath) {
- return false;
- }
- const base = basePath.replace(/\/$/, "");
- return pathname === base || pathname.startsWith(`${base}/`);
-}
-
-function isBlocked(
- nextLocation: HistoryLocation,
- navigationType: Action,
-): boolean {
- // Snapshot so a hook that unregisters mid-run cannot skip a sibling.
- return [...registrations].some(({ hook, basePath }) => {
- // Navigating within the guarded route is not leaving it, so the hook does
- // not fire, exactly as v3's route-scoped leave hook behaves.
- if (staysWithin(basePath, nextLocation.pathname)) {
- return false;
- }
- return hook(nextLocation, navigationType) === false;
- });
-}
-
-function toBlockedLocation(to: To, state: unknown): HistoryLocation {
- const path = typeof to === "string" ? parsePath(to) : to;
- const location: V7Location = {
- pathname: path.pathname ?? "/",
- search: path.search ?? "",
- hash: path.hash ?? "",
- state: state ?? null,
- key: "default",
- };
- return toFacadeLocation(location);
-}
-
-/**
- * Wrap a history so a registered leave hook can cancel navigation, restoring the
- * v3 route-leave behavior on the declarative v7 engine. react-router
- * funnels `Link`, `Navigate`, `useNavigate`, and redux `push` through the
- * history's `push`/`replace`, so checking there covers every in-app navigation.
- * Browser back/forward arrives as a `POP` in the listener and is reverted a step
- * when blocked.
- *
- * Written against the `History` interface, so it wraps a browser or a memory
- * history the same way. Replaced by native `useBlocker` once the app moves to the
- * data router (DEV-2375).
- */
-export function withBlocking(history: History): History {
- let revertingPop = false;
-
- const push: History["push"] = (to, state) => {
- if (!isBlocked(toBlockedLocation(to, state), "PUSH")) {
- history.push(to, state);
- }
- };
-
- const replace: History["replace"] = (to, state) => {
- if (!isBlocked(toBlockedLocation(to, state), "REPLACE")) {
- history.replace(to, state);
- }
- };
-
- const listen: History["listen"] = (listener) => {
- return history.listen((update) => {
- // The forward step we issue below re-enters as its own POP; skip it.
- if (revertingPop) {
- revertingPop = false;
- return;
- }
- const isBlockedPop =
- update.action === "POP" &&
- isBlocked(toFacadeLocation(update.location), "POP");
- if (isBlockedPop) {
- // The browser already moved, so step forward to undo the back. One step
- // covers the back button, the dominant leave case; a multi-step go is
- // not reliably reversible without an index history does not expose.
- revertingPop = true;
- history.go(1);
- return;
- }
- listener(update);
- });
- };
-
- const overrides = { push, replace, listen };
-
- return new Proxy(history, {
- get(target, prop) {
- if (prop === "push" || prop === "replace" || prop === "listen") {
- return overrides[prop];
- }
- const value = Reflect.get(target, prop);
- return typeof value === "function" ? value.bind(target) : value;
- },
- });
-}
diff --git a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts b/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
deleted file mode 100644
index 40150b6eaec..00000000000
--- a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import { UNSAFE_createMemoryHistory as createMemoryHistory } from "react-router";
-
-import type { Location as HistoryLocation } from "../types";
-
-import {
- hasLeaveHooks,
- registerLeaveHook,
- withBlocking,
-} from "./blocking-history";
-
-const setup = (initialEntries: string[] = ["/a"]) =>
- withBlocking(createMemoryHistory({ initialEntries, v5Compat: true }));
-
-const cleanups: Array<() => void> = [];
-
-// Register through here so a failed assertion cannot leak a hook into the next
-// test: the module registry is shared across the suite.
-const register = (
- hook: (nextLocation?: HistoryLocation) => unknown,
- basePath?: string,
-) => {
- const unregister = registerLeaveHook(hook, basePath);
- cleanups.push(unregister);
- return unregister;
-};
-
-afterEach(() => {
- cleanups.splice(0).forEach((unregister) => unregister());
-});
-
-describe("withBlocking", () => {
- it("blocks a push while a hook returns false, and allows it once unregistered", () => {
- const history = setup();
- const unregister = register(() => false);
-
- history.push("/b");
- expect(history.location.pathname).toBe("/a");
-
- unregister();
- history.push("/b");
- expect(history.location.pathname).toBe("/b");
- });
-
- it("allows a push when the hook does not return false", () => {
- const history = setup();
- register(() => undefined);
-
- history.push("/b");
- expect(history.location.pathname).toBe("/b");
- });
-
- // history@3 stayed silent here, so v3 call sites could replace the location they
- // had just read. v7 notifies on every replace, and the call sites skip the
- // redundant navigation themselves.
- it("notifies 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).toHaveBeenCalledTimes(1);
-
- history.replace("/b");
- expect(listener).toHaveBeenCalledTimes(2);
- });
-
- it("blocks a replace while a hook returns false", () => {
- const history = setup();
- register(() => false);
-
- history.replace("/b");
- expect(history.location.pathname).toBe("/a");
- });
-
- it("hands the hook the attempted location and how it was reached", () => {
- const history = setup();
- const hook = jest.fn(() => false);
- register(hook);
-
- history.push("/b?x=1");
-
- expect(hook).toHaveBeenCalledWith(
- expect.objectContaining({
- pathname: "/b",
- search: "?x=1",
- }),
- "PUSH",
- );
- });
-
- it("reverts a blocked POP so the browser back button is cancelled", () => {
- const history = setup();
- // The router subscribes via listen once mounted; the POP interception lives
- // in that subscription, so attach one here to mirror a mounted engine.
- history.listen(() => undefined);
- history.push("/b");
- register(() => false);
-
- history.go(-1);
-
- expect(history.location.pathname).toBe("/b");
- });
-
- it("lets a POP through when no hook blocks it", () => {
- const history = setup();
- history.listen(() => undefined);
- history.push("/b");
-
- history.go(-1);
-
- expect(history.location.pathname).toBe("/a");
- });
-
- it("does not fire a route-scoped hook for a destination within its route", () => {
- const history = setup(["/section/a"]);
- const hook = jest.fn(() => false);
- register(hook, "/section");
-
- history.push("/section/b");
-
- expect(hook).not.toHaveBeenCalled();
- expect(history.location.pathname).toBe("/section/b");
- });
-
- it("fires a route-scoped hook for a destination that leaves its route", () => {
- const history = setup(["/section/a"]);
- const hook = jest.fn(() => false);
- register(hook, "/section");
-
- history.push("/other");
-
- expect(hook).toHaveBeenCalled();
- expect(history.location.pathname).toBe("/section/a");
- });
-
- it("treats the guarded route's own path as within scope", () => {
- const history = setup(["/section/a"]);
- register(() => false, "/section");
-
- history.push("/section");
-
- expect(history.location.pathname).toBe("/section");
- });
-
- it("tracks whether any hook is active", () => {
- expect(hasLeaveHooks()).toBe(false);
- const unregister = register(() => false);
- expect(hasLeaveHooks()).toBe(true);
- unregister();
- expect(hasLeaveHooks()).toBe(false);
- });
-});
diff --git a/frontend/src/metabase/router/v7/create-router.tsx b/frontend/src/metabase/router/v7/create-router.tsx
new file mode 100644
index 00000000000..1bd5a553d8c
--- /dev/null
+++ b/frontend/src/metabase/router/v7/create-router.tsx
@@ -0,0 +1,58 @@
+import type { ReactNode } from "react";
+import {
+ type DataRouter,
+ Route,
+ createBrowserRouter,
+ createMemoryRouter,
+ createRoutesFromElements,
+} from "react-router";
+
+import { AppShell } from "./AppShell";
+import { installLeaveHookBlocker } from "./leave-hooks";
+import { mapToV7 } from "./map-to-v7";
+
+export type MemoryTestRouter = DataRouter;
+
+/**
+ * Lets the test harness hand out a `history` handle before the route tree, and
+ * so the router, exists.
+ */
+export type MemoryTestRouterHolder = { current: MemoryTestRouter | null };
+
+/**
+ * The whole facade tree as real data routes, under a pathless layout route.
+ *
+ * The layout route contributes no path, so it changes no matching. It exists so
+ * relative redux navigation resolves from the root (see `AppShell`) and as the
+ * seat for anything the app shell needs above the route tree.
+ */
+function toDataRoutes(tree: ReactNode) {
+ return createRoutesFromElements(
+ <Route element={<AppShell />}>{mapToV7(tree)}</Route>,
+ );
+}
+
+export function createAppRouter(
+ tree: ReactNode,
+ basename?: string,
+): DataRouter {
+ const router = createBrowserRouter(toDataRoutes(tree), { basename });
+ installLeaveHookBlocker(router);
+ return router;
+}
+
+export function createMemoryAppRouter(
+ tree: ReactNode,
+ initialRoute: string,
+ basename?: string,
+): DataRouter {
+ const entry = initialRoute.startsWith("/")
+ ? initialRoute
+ : `/${initialRoute}`;
+ const router = createMemoryRouter(toDataRoutes(tree), {
+ basename,
+ initialEntries: [entry],
+ });
+ installLeaveHookBlocker(router);
+ return router;
+}
diff --git a/frontend/src/metabase/router/v7/leave-hooks.ts b/frontend/src/metabase/router/v7/leave-hooks.ts
new file mode 100644
index 00000000000..1666b2efc00
--- /dev/null
+++ b/frontend/src/metabase/router/v7/leave-hooks.ts
@@ -0,0 +1,94 @@
+import type { DataRouter } from "react-router";
+
+import type { Action, Location as HistoryLocation } from "../types";
+
+import { toFacadeLocation } from "./location";
+
+/**
+ * A route-leave hook: it receives the attempted destination and how it was
+ * reached, and returns `false` to cancel the navigation. The navigation type is
+ * a second argument rather than a field on the location, which carries only the
+ * URL parts on v7.
+ */
+type LeaveHook = (
+ nextLocation?: HistoryLocation,
+ navigationType?: Action,
+) => unknown;
+
+interface Registration {
+ hook: LeaveHook;
+ // The matched pathname of the guarded route. A leave hook is scoped to a route
+ // and only fires when a navigation leaves that route's subtree, so a hook with
+ // a base path does not fire for destinations that stay under it.
+ basePath?: string;
+}
+
+const registrations = new Set<Registration>();
+
+/**
+ * Register a leave hook, so the leave-confirm modals block navigation the way
+ * they did on v3. `useRouteLeaveHook` is the call site; `basePath` scopes the
+ * hook to a route, so it fires only when the destination leaves that route's
+ * subtree, matching v3's `listenBeforeLeavingRoute`. Returns the unregister
+ * function the caller uses as effect cleanup.
+ */
+export function registerLeaveHook(
+ hook: LeaveHook,
+ basePath?: string,
+): () => void {
+ const registration: Registration = { hook, basePath };
+ registrations.add(registration);
+ return () => {
+ registrations.delete(registration);
+ };
+}
+
+/**
+ * Whether any leave hook is currently registered. The `beforeunload` guard lives
+ * at the call sites (`useBeforeUnload`), so this is exposed only for assertions.
+ */
+export function hasLeaveHooks(): boolean {
+ return registrations.size > 0;
+}
+
+function staysWithin(basePath: string | undefined, pathname: string): boolean {
+ if (!basePath) {
+ return false;
+ }
+ const base = basePath.replace(/\/$/, "");
+ return pathname === base || pathname.startsWith(`${base}/`);
+}
+
+function isBlocked(
+ nextLocation: HistoryLocation,
+ navigationType: Action,
+): boolean {
+ // Snapshot so a hook that unregisters mid-run cannot skip a sibling.
+ return [...registrations].some(({ hook, basePath }) => {
+ // Navigating within the guarded route is not leaving it, so the hook does
+ // not fire, exactly as v3's route-scoped leave hook behaves.
+ if (staysWithin(basePath, nextLocation.pathname)) {
+ return false;
+ }
+ return hook(nextLocation, navigationType) === false;
+ });
+}
+
+// The router supports one blocker, so every leave hook shares this key.
+const LEAVE_HOOK_BLOCKER_KEY = "route-leave-hooks";
+
+/**
+ * Point the data router's blocker at the leave-hook registry, so a hook
+ * returning `false` cancels the navigation. The router consults the blocker
+ * before it starts navigating, so `Link`, `Navigate`, `useNavigate`, and redux
+ * `push` are all covered, and it reverses the history delta itself when a back
+ * or forward is blocked.
+ *
+ * Replaced by native `useBlocker` once the leave-confirm call sites move to it
+ * (DEV-2375).
+ */
+export function installLeaveHookBlocker(router: DataRouter): void {
+ router.getBlocker(LEAVE_HOOK_BLOCKER_KEY, ({ nextLocation, historyAction }) =>
+ isBlocked(toFacadeLocation(nextLocation), historyAction),
+ );
+}
diff --git a/frontend/src/metabase/router/v7/leave-hooks.unit.spec.tsx b/frontend/src/metabase/router/v7/leave-hooks.unit.spec.tsx
new file mode 100644
index 00000000000..4b11464f200
--- /dev/null
+++ b/frontend/src/metabase/router/v7/leave-hooks.unit.spec.tsx
@@ -0,0 +1,126 @@
+import { Route } from "../route";
+import type { Action, Location as HistoryLocation } from "../types";
+
+import { createMemoryAppRouter } from "./create-router";
+import { hasLeaveHooks, registerLeaveHook } from "./leave-hooks";
+
+const setup = (initialRoute = "/a") =>
+ createMemoryAppRouter(<Route path="*" element={null} />, initialRoute);
+
+const cleanups: Array<() => void> = [];
+
+// Register through here so a failed assertion cannot leak a hook into the next
+// test: the module registry is shared across the suite.
+const register = (
+ hook: (nextLocation?: HistoryLocation, navigationType?: Action) => unknown,
+ basePath?: string,
+) => {
+ const unregister = registerLeaveHook(hook, basePath);
+ cleanups.push(unregister);
+ return unregister;
+};
+
+afterEach(() => {
+ cleanups.splice(0).forEach((unregister) => unregister());
+});
+
+describe("leave hooks on the data router", () => {
+ it("blocks a push while a hook returns false, and allows it once unregistered", async () => {
+ const router = setup();
+ const unregister = register(() => false);
+
+ await router.navigate("/b");
+ expect(router.state.location.pathname).toBe("/a");
+
+ unregister();
+ await router.navigate("/b");
+ expect(router.state.location.pathname).toBe("/b");
+ });
+
+ it("allows a push when the hook does not return false", async () => {
+ const router = setup();
+ register(() => undefined);
+
+ await router.navigate("/b");
+ expect(router.state.location.pathname).toBe("/b");
+ });
+
+ it("blocks a replace while a hook returns false", async () => {
+ const router = setup();
+ register(() => false);
+
+ await router.navigate("/b", { replace: true });
+ expect(router.state.location.pathname).toBe("/a");
+ });
+
+ it("hands the hook the attempted location and a PUSH navigation type", async () => {
+ const router = setup();
+ const hook = jest.fn(() => false);
+ register(hook);
+
+ await router.navigate("/b?x=1");
+
+ expect(hook).toHaveBeenCalledWith(
+ expect.objectContaining({ pathname: "/b", search: "?x=1" }),
+ "PUSH",
+ );
+ });
+
+ it("reverts a blocked POP so the browser back button is cancelled", async () => {
+ const router = setup();
+ await router.navigate("/b");
+ register(() => false);
+
+ await router.navigate(-1);
+
+ expect(router.state.location.pathname).toBe("/b");
+ });
+
+ it("lets a POP through when no hook blocks it", async () => {
+ const router = setup();
+ await router.navigate("/b");
+
+ await router.navigate(-1);
+
+ expect(router.state.location.pathname).toBe("/a");
+ });
+
+ it("does not fire a route-scoped hook for a destination within its route", async () => {
+ const router = setup("/section/a");
+ const hook = jest.fn(() => false);
+ register(hook, "/section");
+
+ await router.navigate("/section/b");
+
+ expect(hook).not.toHaveBeenCalled();
+ expect(router.state.location.pathname).toBe("/section/b");
+ });
+
+ it("fires a route-scoped hook for a destination that leaves its route", async () => {
+ const router = setup("/section/a");
+ const hook = jest.fn(() => false);
+ register(hook, "/section");
+
+ await router.navigate("/other");
+
+ expect(hook).toHaveBeenCalled();
+ expect(router.state.location.pathname).toBe("/section/a");
+ });
+
+ it("treats the guarded route's own path as within scope", async () => {
+ const router = setup("/section/a");
+ register(() => false, "/section");
+
+ await router.navigate("/section");
+
+ expect(router.state.location.pathname).toBe("/section");
+ });
+
+ it("tracks whether any hook is active", () => {
+ expect(hasLeaveHooks()).toBe(false);
+ const unregister = register(() => false);
+ expect(hasLeaveHooks()).toBe(true);
+ unregister();
+ expect(hasLeaveHooks()).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/router/v7/navigator.ts b/frontend/src/metabase/router/v7/navigator.ts
index 6201eec1aff..92ca24b7a6f 100644
--- a/frontend/src/metabase/router/v7/navigator.ts
+++ b/frontend/src/metabase/router/v7/navigator.ts
@@ -4,7 +4,7 @@ import type { RouterNavigator } from "../middleware";
import type { Location as HistoryLocation, LocationDescriptor } from "../types";
/**
- * The live v7 `navigate`, registered by `V7RouterBridge` once the router mounts.
+ * The live v7 `navigate`, registered by the host's `AppShell` 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.
*/
@@ -38,7 +38,7 @@ export function setV7Navigate(navigate: NavigateFunction | null): void {
/**
* Subscribers to location changes, backing the imperative router's `listen`. v3's
- * `router.listen` had no v7 equivalent, so `V7RouterBridge` fans every location
+ * `router.listen` had no v7 equivalent, so the router mirror fans every location
* change out to these on the app's behalf (e.g. `use-dashboard-url-query`).
*/
type LocationListener = (location: HistoryLocation) => void;
diff --git a/frontend/src/metabase/router/v7/raw-history.ts b/frontend/src/metabase/router/v7/raw-history.ts
new file mode 100644
index 00000000000..f5b6318590c
--- /dev/null
+++ b/frontend/src/metabase/router/v7/raw-history.ts
@@ -0,0 +1,22 @@
+import {
+ type HistoryRouterProps,
+ UNSAFE_createBrowserHistory as createBrowserHistory,
+} from "react-router";
+
+// react-router does not export the `History` interface directly, so pull it off
+// the history prop of `unstable_HistoryRouter`.
+type History = HistoryRouterProps["history"];
+
+let rawBrowserHistory: History | null = null;
+
+/**
+ * A plain browser history for imperative navigation outside the app's router
+ * tree, replacing v3's global `browserHistory` singleton. The SDK data-app bundle
+ * mounts no router, so it drives its iframe URL through this instead. Created
+ * lazily on first use, so it never exists in the main app, where a second history
+ * would fight the mounted router over `popstate`.
+ */
+export function getRawBrowserHistory(): History {
+ rawBrowserHistory ??= createBrowserHistory({ v5Compat: true });
+ return rawBrowserHistory;
+}
diff --git a/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
index 77d07bf6cf3..67a4e19becb 100644
--- a/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
+++ b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
@@ -1,18 +1,16 @@
import userEvent from "@testing-library/user-event";
-import { MemoryRouter } from "react-router";
import { renderWithProviders, screen } from "__support__/ui";
import {
Outlet,
Route,
+ push,
useLocation,
useNavigate,
useParams,
useSearchParams,
} from "metabase/router";
-import { V7RouterTree } from "./RouterProviderV7";
-
function Layout() {
return (
<div>
@@ -33,6 +31,7 @@ function ThingPage() {
<span data-testid="pathname">{pathname}</span>
<span data-testid="search">{search}</span>
<span data-testid="thing-id">{params.thingId}</span>
+ <span data-testid="splat">{String(params["*"])}</span>
<span data-testid="query-tab">{searchParams.get("tab")}</span>
<button onClick={() => navigate("/other")}>go absolute</button>
<button onClick={() => navigate("..")}>go up</button>
@@ -48,11 +47,7 @@ const tree = (
);
function setup(initialRoute: string) {
- renderWithProviders(
- <MemoryRouter initialEntries={[initialRoute]}>
- <V7RouterTree>{tree}</V7RouterTree>
- </MemoryRouter>,
- );
+ return renderWithProviders(tree, { withRouter: true, initialRoute });
}
describe("v7 engine (facade over real react-router v7)", () => {
@@ -70,6 +65,25 @@ describe("v7 engine (facade over real react-router v7)", () => {
expect(screen.getByTestId("query-tab")).toHaveTextContent("x");
});
+ // The tree is wrapped in a pathless layout route for the app shell. Pathless
+ // means it must contribute nothing to matching, so no route below it should
+ // see params it did not declare itself.
+ it("the host's layout route contributes no params of its own", () => {
+ setup("/things/42");
+ expect(screen.getByTestId("splat")).toHaveTextContent("undefined");
+ });
+
+ // Redux navigation carries no route context, and history@3 resolved a pathname
+ // without a leading slash against the root. Resolving it against the deepest
+ // match instead would send `{ pathname: "other" }` to `/things/other`.
+ it("resolves a relative redux push from the root", async () => {
+ const { store } = setup("/things/42");
+
+ store.dispatch(push({ pathname: "other" }));
+
+ expect(await screen.findByTestId("other")).toBeInTheDocument();
+ });
+
it("navigates to an absolute path via useNavigate", async () => {
setup("/things/42");
await userEvent.click(screen.getByRole("button", { name: "go absolute" }));
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index 3344c05c3a5..b129833c3d8 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -44,11 +44,10 @@ import {
import {
type History,
type LocationDescriptor,
- type MemoryTestHistory,
+ type MemoryTestRouterHolder,
Route,
RouterProviderV7Memory,
createLocationMirror,
- createMemoryTestHistory,
createV7Navigator,
routerMiddleware,
toFacadeLocation,
@@ -199,12 +198,11 @@ export function getTestStoreAndWrapper({
initialState = _.pick(initialState, ...publicReducerNames);
}
- // The harness owns the memory history (rather than the provider creating it
- // internally) so specs still get a handle to drive and assert against.
- const v7History = withRouter
- ? createMemoryTestHistory(initialRoute)
- : undefined;
- const history = v7History ? createV3HistoryAdapter(v7History) : undefined;
+ // The router can only be built once the route tree is known, which is at
+ // render. Specs still get their handle up front, so hand the adapter a holder
+ // the provider fills in.
+ const routerHolder: MemoryTestRouterHolder = { current: null };
+ const history = withRouter ? createV3HistoryAdapter(routerHolder) : undefined;
let reducers;
@@ -239,7 +237,7 @@ export function getTestStoreAndWrapper({
<TestWrapper
{...props}
store={store}
- v7History={v7History}
+ routerHolder={routerHolder}
withRouter={withRouter}
initialRoute={initialRoute}
withDND={withDND}
@@ -291,7 +289,7 @@ const TestColorSchemeProvider = ({ children }: React.PropsWithChildren) => {
export function TestWrapper({
children,
store,
- v7History,
+ routerHolder,
withRouter,
initialRoute = "/",
withKBar,
@@ -303,7 +301,7 @@ export function TestWrapper({
}: {
children: React.ReactElement;
store: any;
- v7History?: MemoryTestHistory;
+ routerHolder?: MemoryTestRouterHolder;
withRouter: boolean;
initialRoute?: string;
withKBar: boolean;
@@ -340,7 +338,7 @@ export function TestWrapper({
<MaybeKBar hasKBar={withKBar}>
<MaybeRouter
hasRouter={withRouter}
- v7History={v7History}
+ routerHolder={routerHolder}
initialRoute={initialRoute}
>
{children}
@@ -358,33 +356,58 @@ export function TestWrapper({
/**
* The v3 `history` surface the specs drive and assert against
- * (`getCurrentLocation()`, `push`, `goBack`, `listen`, ...), backed by the v7
- * memory history. Lets specs written against the v3 engine keep working
- * unchanged on v7. Cast to `History` so the handle specs already destructure
- * keeps its type; it implements the subset they use.
+ * (`getCurrentLocation()`, `push`, `goBack`, `listen`, ...), backed by the memory
+ * data router. Lets specs written against the v3 engine keep working unchanged.
+ * Cast to `History` so the handle specs already destructure keeps its type; it
+ * implements the subset they use.
*/
-function createV3HistoryAdapter(history: MemoryTestHistory): History {
- const getCurrentLocation = () => toFacadeLocation(history.location);
+function createV3HistoryAdapter(holder: MemoryTestRouterHolder): History {
+ const requireRouter = () => {
+ if (!holder.current) {
+ throw new Error("The router handle is only available after render");
+ }
+ return holder.current;
+ };
+
+ const getCurrentLocation = () =>
+ toFacadeLocation(requireRouter().state.location);
+
+ // v3's history methods returned void. Swallow the router's promise rather than
+ // handing it back: specs drive these inside `act()`, which switches to its
+ // async mode the moment the callback returns a thenable. Split by argument
+ // shape so neither call has to fight `navigate`'s overload.
+ const navigateTo = (...[to, options]: ReturnType<typeof toNavigateArgs>) => {
+ requireRouter().navigate(to, options);
+ };
+ const navigateBy = (delta: number) => {
+ requireRouter().navigate(delta);
+ };
const adapter = {
getCurrentLocation,
get location() {
return getCurrentLocation();
},
- push: (location: LocationDescriptor) => {
- const [to, options] = toNavigateArgs(location);
- history.push(to, options.state);
- },
- replace: (location: LocationDescriptor) => {
- const [to, options] = toNavigateArgs(location);
- history.replace(to, options.state);
- },
- go: (n: number) => history.go(n),
- goBack: () => history.go(-1),
- goForward: () => history.go(1),
+ push: (location: LocationDescriptor) =>
+ navigateTo(...toNavigateArgs(location)),
+ replace: (location: LocationDescriptor) =>
+ navigateTo(...toNavigateArgs(location, { replace: true })),
+ go: (n: number) => navigateBy(n),
+ goBack: () => navigateBy(-1),
+ goForward: () => navigateBy(1),
listen: (
listener: (location: ReturnType<typeof getCurrentLocation>) => void,
- ) => history.listen(({ location }) => listener(toFacadeLocation(location))),
+ ) => {
+ const router = requireRouter();
+ let lastKey = router.state.location.key;
+ return router.subscribe(({ location }) => {
+ if (location.key === lastKey) {
+ return;
+ }
+ lastKey = location.key;
+ listener(toFacadeLocation(location));
+ });
+ },
};
// The adapter implements the subset of v3's `History` the specs actually call,
@@ -413,12 +436,12 @@ function childrenAreRouteTree(children: React.ReactNode): boolean {
function MaybeRouter({
children,
hasRouter,
- v7History,
+ routerHolder,
initialRoute,
}: {
children: React.ReactElement;
hasRouter: boolean;
- v7History?: MemoryTestHistory;
+ routerHolder?: MemoryTestRouterHolder;
initialRoute: string;
}): JSX.Element {
const dispatch = useDispatch();
@@ -441,7 +464,7 @@ function MaybeRouter({
return (
<RouterProviderV7Memory
initialRoute={initialRoute}
- history={v7History}
+ routerHolder={routerHolder}
onLocationChange={onLocationChange}
>
{content}