Skip to content

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

Restore navigation blocking on the v7 engine and fix v7 Link navigation (#78103)

Romeo Van Snick07909c841ffb
diff --git a/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.tsx b/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.tsx
index 661b3e0fc81..4b4add2de73 100644
--- a/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.tsx
+++ b/frontend/src/metabase/admin/permissions/components/PermissionsTable/PermissionsTable.tsx
@@ -231,10 +231,7 @@ const EntityRow = memo(function EntityRow({
<PermissionsTableRow aria-label={`${entity.name} permissions`}>
<PermissionsTableCell>
{entity.canSelect ? (
- // @ts-expect-error - Link expects a `to` prop, but we don't have one. maybe this should be a button?
- <EntityNameLink //force line break so we can type check next line
- onClick={() => onSelect?.(entity)}
- >
+ <EntityNameLink onClick={() => onSelect?.(entity)}>
{entityName}
</EntityNameLink>
) : (
diff --git a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx
new file mode 100644
index 00000000000..1d62ce56918
--- /dev/null
+++ b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx
@@ -0,0 +1,100 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabasesEndpoints,
+ setupGroupsEndpoint,
+ setupPermissionsGraphEndpoints,
+} from "__support__/server-mocks";
+import {
+ renderWithProviders,
+ screen,
+ waitForLoaderToBeRemoved,
+ within,
+} from "__support__/ui";
+import DataPermissionsPage from "metabase/admin/permissions/pages/DataPermissionsPage/DataPermissionsPage";
+import { GroupsPermissionsPage } from "metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage";
+import { Route, withRouteProps } from "metabase/router";
+import type { RouterEngine } from "metabase/router/engine";
+import { createMockGroup } from "metabase-types/api/mocks/group";
+import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+
+const RoutedDataPermissionsPage = withRouteProps(DataPermissionsPage);
+const RoutedGroupsPermissionsPage = withRouteProps(GroupsPermissionsPage);
+
+const TEST_DATABASE = createSampleDatabase();
+const TEST_TABLES = TEST_DATABASE.tables ?? [];
+
+const TEST_GROUPS = [
+ createMockGroup({ id: 2, name: "Administrators", magic_group_type: "admin" }),
+ createMockGroup({
+ id: 1,
+ name: "All internal users",
+ magic_group_type: "all-internal-users",
+ }),
+];
+
+// The real routes.tsx enumerates each drill-down depth as its own sibling route
+// because v7's matcher cannot parse v3's optional groups.
+const GROUPS_PERMISSIONS_PATHS = [
+ "group/:groupId",
+ "group/:groupId/database/:databaseId",
+ "group/:groupId/database/:databaseId/schema/:schemaName",
+];
+
+const setup = (routerEngine: RouterEngine) => {
+ setupDatabasesEndpoints([TEST_DATABASE]);
+ setupPermissionsGraphEndpoints(TEST_GROUPS, [TEST_DATABASE]);
+ setupGroupsEndpoint(TEST_GROUPS);
+
+ fetchMock.get(
+ `path:/api/database/${TEST_DATABASE.id}/metadata`,
+ TEST_DATABASE,
+ );
+
+ return renderWithProviders(
+ <Route
+ path="/admin/permissions/data"
+ element={<RoutedDataPermissionsPage />}
+ >
+ {GROUPS_PERMISSIONS_PATHS.map((path) => (
+ <Route
+ key={path}
+ path={path}
+ element={<RoutedGroupsPermissionsPage />}
+ />
+ ))}
+ </Route>,
+ {
+ withRouter: true,
+ routerEngine,
+ initialRoute: `/admin/permissions/data/group/2`,
+ },
+ );
+};
+
+const tableRowCount = () =>
+ within(screen.getByTestId("permission-table")).getAllByRole("row").length;
+
+// Clicking a database name is a `<Link>` used as a button (onClick, no `to`).
+// On v7 the engine-aware link must not perform its own navigation, or it clobbers
+// the push the click handler dispatches and the drill-down never happens.
+describe.each<RouterEngine>(["v3", "v7"])(
+ "GroupsPermissionsPage drill-down on the %s engine",
+ (routerEngine) => {
+ it("shows the tables after drilling into a database", async () => {
+ setup(routerEngine);
+ await waitForLoaderToBeRemoved();
+
+ // Database-level view: one row for Sample Database (plus header row).
+ const dbRow = await screen.findByText("Sample Database");
+ expect(tableRowCount()).toBe(2);
+
+ await userEvent.click(dbRow);
+
+ // Table-level view: a row per table in the sample database.
+ expect(await screen.findByText("Orders")).toBeInTheDocument();
+ expect(tableRowCount()).toBe(TEST_TABLES.length + 1);
+ });
+ },
+);
diff --git a/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx b/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx
index deb96becdf2..419d2f31708 100644
--- a/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx
+++ b/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx
@@ -3,10 +3,8 @@
import { forwardRef } from "react";
-import {
- RouterLink as Link,
- type RouterLinkProps as LinkProps,
-} from "metabase/router/react-router";
+import type { RouterLinkProps as LinkProps } from "metabase/router/react-router";
+import { RouterLink as Link } from "metabase/router/router-link";
// `ref` prop, we have to manually forward it to the correct prop name to make hover work as expected.
export const ForwardRefLink = forwardRef(function _ForwardRefLink(
diff --git a/frontend/src/metabase/common/components/Link/Link.tsx b/frontend/src/metabase/common/components/Link/Link.tsx
index fa3a5e2fed4..b45cb55ca6c 100644
--- a/frontend/src/metabase/common/components/Link/Link.tsx
+++ b/frontend/src/metabase/common/components/Link/Link.tsx
@@ -1,6 +1,6 @@
import cx from "classnames";
-import { RouterLink } from "metabase/router/react-router";
+import { RouterLink } from "metabase/router/router-link";
import { Tooltip } from "metabase/ui";
import S from "./Link.module.css";
diff --git a/frontend/src/metabase/common/components/Link/types.ts b/frontend/src/metabase/common/components/Link/types.ts
index 8d7d1992200..c96d634face 100644
--- a/frontend/src/metabase/common/components/Link/types.ts
+++ b/frontend/src/metabase/common/components/Link/types.ts
@@ -1,7 +1,11 @@
import type { RouterLinkProps } from "metabase/router/react-router";
import type { TooltipProps } from "metabase/ui";
-export interface LinkProps extends RouterLinkProps {
+export interface LinkProps extends Omit<RouterLinkProps, "to"> {
+ // A link with no destination is used as a button: it navigates through its own
+ // `onClick` instead. v3's types make `to` required, but both engines handle it
+ // being absent, so the app's `Link` allows it.
+ to?: RouterLinkProps["to"];
variant?: "default" | "brand" | "brandBold";
tooltip?: string | TooltipProps;
}
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index c9eced48a1a..648babc1c3f 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -5,6 +5,7 @@ export * from "./navigation";
export * from "./Navigate";
export * from "./react-router";
export * from "./redirect";
+export * from "./router-link";
export * from "./route";
export * from "./Outlet";
export * from "./routing-reducer";
diff --git a/frontend/src/metabase/router/react-router.ts b/frontend/src/metabase/router/react-router.ts
index 9b7f812cffe..4385c492ff3 100644
--- a/frontend/src/metabase/router/react-router.ts
+++ b/frontend/src/metabase/router/react-router.ts
@@ -11,7 +11,10 @@
import type { RouteProps as BaseRouteProps } from "react-router";
export {
- Link as RouterLink,
+ // The raw v3 `<Link>`. The public `RouterLink` (router-link.tsx) is engine-aware
+ // and renders v7's `<Link>` on the v7 engine, so v3's is exported under a private
+ // name for that wrapper to fall back to on the v3 engine.
+ Link as V3RouterLink,
// The raw v3 `<Route>`, used by the `Route` shim to run v3's route builder over
// a `<Route index>` element without recursing back into the shim's own builder.
Route as ReactRouterRoute,
diff --git a/frontend/src/metabase/router/router-link.tsx b/frontend/src/metabase/router/router-link.tsx
new file mode 100644
index 00000000000..831daab2f13
--- /dev/null
+++ b/frontend/src/metabase/router/router-link.tsx
@@ -0,0 +1,111 @@
+import { type Ref, forwardRef } from "react";
+import {
+ Link as V7Link,
+ type LinkProps as V7LinkProps,
+ NavLink as V7NavLink,
+ useInRouterContext,
+} from "react-router-v7";
+
+import { type RouterLinkProps, V3RouterLink } from "./react-router";
+
+/**
+ * The app's `<Link>`, engine-aware.
+ *
+ * v3's `<Link>` reads v3's legacy React context, which only a v3 `<Router>`
+ * provides and which does not cross portals. On the v7 engine there is no v3
+ * router, so a v3 `<Link>` throws "rendered outside of a router context" the
+ * moment it is clicked (worst inside portaled modals). v7's `<Link>` uses modern
+ * context, provided by the engine's `<BrowserRouter>` and propagated through
+ * portals, so it works everywhere. Both collapse to v7's `<Link>` when the v3
+ * engine is deleted in Phase 4.
+ */
+
+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.
+function toV7Target(to: V3To): { to: V7LinkProps["to"]; state?: unknown } {
+ if (to == null || typeof to === "string") {
+ return { to: 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);
+ return {
+ to: { pathname: pathname ?? "", search: searchString, hash },
+ state,
+ };
+}
+
+interface Props extends Omit<RouterLinkProps, "to"> {
+ // Optional: a link with no destination is used as a button, navigating through
+ // its own `onClick`.
+ to?: V3To;
+ // v3's ref-forwarding prop; the facade's `ForwardRefLink` still passes it.
+ innerRef?: Ref<HTMLAnchorElement>;
+}
+
+export const RouterLink = forwardRef<HTMLAnchorElement, Props>(
+ function RouterLink({ to, innerRef, ...props }, ref) {
+ const linkRef = ref ?? innerRef;
+ // Detect the engine from the mounted router rather than the flag, so the link
+ // matches whichever provider actually wraps it (the flag and the provider
+ // agree in the app; tests mount a provider directly).
+ const isV7Engine = useInRouterContext();
+
+ if (isV7Engine) {
+ // v3-only props v7's `<Link>` does not accept.
+ 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) {
+ return <a {...rest} ref={linkRef} />;
+ }
+
+ const { to: v7To, state } = toV7Target(to);
+
+ // v3's `<Link>` highlights itself when its route is active via
+ // `activeClassName`/`activeStyle` (and `onlyActiveOnIndex` for an exact
+ // match). v7 moved that to `<NavLink>`, so route it there when a call site
+ // asks for active styling; a plain `<Link>` would silently drop it.
+ if (activeClassName != null || activeStyle != null) {
+ const { className, style, ...navRest } = rest;
+ return (
+ <V7NavLink
+ {...navRest}
+ to={v7To}
+ state={state}
+ ref={linkRef}
+ end={onlyActiveOnIndex}
+ className={({ isActive }) =>
+ [className, isActive ? activeClassName : null]
+ .filter(Boolean)
+ .join(" ")
+ }
+ style={({ isActive }) =>
+ isActive ? { ...style, ...activeStyle } : style
+ }
+ />
+ );
+ }
+
+ return <V7Link {...rest} to={v7To} state={state} ref={linkRef} />;
+ }
+
+ return (
+ // `innerRef` is a valid v3 `<Link>` prop but is missing from its types.
+ // @ts-expect-error see https://github.com/remix-run/react-router/blob/v3.2.6/docs/API.md#innerref
+ <V3RouterLink {...props} to={to} innerRef={linkRef} />
+ );
+ },
+);
diff --git a/frontend/src/metabase/router/router-link.unit.spec.tsx b/frontend/src/metabase/router/router-link.unit.spec.tsx
new file mode 100644
index 00000000000..9e738a780c7
--- /dev/null
+++ b/frontend/src/metabase/router/router-link.unit.spec.tsx
@@ -0,0 +1,84 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { useDispatch } from "metabase/redux";
+import { Link, Outlet, Route, push, useLocation } from "metabase/router";
+
+import type { RouterEngine } from "./engine";
+
+function Home() {
+ const { pathname } = useLocation();
+ const dispatch = useDispatch();
+ return (
+ <div>
+ <span data-testid="location">{pathname}</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>
+ <Link to="/" activeClassName="is-active" onlyActiveOnIndex>
+ home
+ </Link>
+ <Link to="/other" activeClassName="is-active">
+ section
+ </Link>
+ <Outlet />
+ </div>
+ );
+}
+
+const tree = (
+ <Route path="/" element={<Home />}>
+ <Route path="other" element={<span data-testid="other">other</span>} />
+ </Route>
+);
+
+// A v3 `<Link>` reads v3's legacy router context, which the v7 engine does not
+// provide, so it threw "rendered outside of a router context" on click. The
+// engine-aware `RouterLink` renders v7's `<Link>` on v7, so clicking navigates on
+// both engines.
+describe.each<RouterEngine>(["v3", "v7"])(
+ "RouterLink on the %s engine",
+ (routerEngine) => {
+ it("navigates on click without throwing", async () => {
+ renderWithProviders(tree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute: "/",
+ });
+
+ await userEvent.click(screen.getByRole("link", { name: "go" }));
+
+ expect(await screen.findByTestId("other")).toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent("/other");
+ });
+
+ it("applies activeClassName to the link that matches the route", async () => {
+ renderWithProviders(tree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute: "/other",
+ });
+
+ await screen.findByTestId("other");
+
+ // The exact-match home link is not active on /other; the section link is.
+ expect(screen.getByText("home")).not.toHaveClass("is-active");
+ expect(screen.getByText("section")).toHaveClass("is-active");
+ });
+
+ it("does not navigate on its own when used as a button (no `to`)", async () => {
+ renderWithProviders(tree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute: "/",
+ });
+
+ // The click handler dispatches the navigation; the link itself must not
+ // navigate, or on v7 it would clobber the push and never reach /other.
+ await userEvent.click(screen.getByText("act"));
+
+ expect(await screen.findByTestId("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.tsx
index ffddb84d927..0dde3c8495a 100644
--- a/frontend/src/metabase/router/v7/RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx
@@ -19,9 +19,14 @@ import type {
} from "../react-router";
import type { Route } from "../route";
+import { registerLeaveHook } from "./blocking-history";
import { toV3Location } from "./location";
import { 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.
+type RouteStub = PlainRoute & { pathnameBase?: string };
+
/**
* Runs as the `element` of every v7 route and republishes v7's location,
* params, matched-route branch, and an imperative-router shim into the shared
@@ -46,13 +51,14 @@ export function RouterBridge({
// context that also drives `<Outlet>` (available in declarative mode). Each
// route keeps its v3 path on `handle`, which the facade hooks match against.
const { matches } = useContext(UNSAFE_RouteContext);
- const routes = useMemo<PlainRoute[]>(
+ const routes = useMemo<RouteStub[]>(
() =>
matches.map((match) => {
// `handle` is typed `unknown`; we only ever put `{ v3Path }` on it.
const handle = match.route.handle as { v3Path?: string } | undefined;
- // The facade hooks read only `route.path`, so a `{ path }` stub is enough.
- return { path: handle?.v3Path } as PlainRoute;
+ // The facade hooks read `route.path`; `pathnameBase` is the route's matched
+ // pathname, which `setRouteLeaveHook` uses to scope its hook to this route.
+ return { path: handle?.v3Path, pathnameBase: match.pathname };
}),
[matches],
);
@@ -72,9 +78,9 @@ export function RouterBridge({
[router, location, params, routes],
);
- // The injected `route` prop / `useRoute()`: consumers only read it to hand back
- // to `setRouteLeaveHook` (a no-op on v7), so the leaf match's `{ path }` is
- // enough. Cast because the facade types the injected route object as `Route`.
+ // The injected `route` prop / `useRoute()`: consumers hand it back to
+ // `setRouteLeaveHook`, which reads its `pathnameBase` to scope the hook. Cast
+ // because the facade types the injected route as `Route`.
const route = (routes.at(-1) ?? null) as Route | null;
return (
@@ -92,8 +98,10 @@ export function RouterBridge({
* The v3 `InjectedRouter` (`router.push/replace/go/...`) reimplemented over v7's
* `navigate`. The facade's `useNavigate` has already resolved relative targets to
* absolute paths before calling `push`/`replace`, so these pass straight through.
- * `setRouteLeaveHook` is a no-op for now: navigation blocking is data-router-only,
- * restored on the declarative engine via a blocking history in DEV-2374.
+ * `setRouteLeaveHook` registers into the blocking history, which cancels the
+ * navigation when the hook returns `false`, matching v3. The route's matched
+ * pathname scopes the hook, so it fires only when the destination leaves that
+ * route, the way v3's `listenBeforeLeavingRoute` does.
*/
function makeRouterShim(navigate: V7NavigateFunction): InjectedRouter {
const href = (location: LocationDescriptor) =>
@@ -108,7 +116,12 @@ function makeRouterShim(navigate: V7NavigateFunction): InjectedRouter {
go: (n) => navigate(n),
goBack: () => navigate(-1),
goForward: () => navigate(1),
- setRouteLeaveHook: () => () => undefined,
+ setRouteLeaveHook: (route, hook) => {
+ // The facade types the route arg as v3's `Route`; on v7 it is our stub,
+ // which carries the matched `pathnameBase` used to scope the hook.
+ const basePath = (route as RouteStub | undefined)?.pathnameBase;
+ return registerLeaveHook(hook, basePath);
+ },
createPath: href,
createHref: href,
isActive: () => false,
diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
index 2b274cb105a..888992873b2 100644
--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx
+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
@@ -1,9 +1,16 @@
import type { PropsWithChildren } from "react";
-import { BrowserRouter, MemoryRouter, Routes } from "react-router-v7";
+import { useState } from "react";
+import {
+ unstable_HistoryRouter as HistoryRouter,
+ Routes,
+ UNSAFE_createBrowserHistory as createBrowserHistory,
+ UNSAFE_createMemoryHistory as createMemoryHistory,
+} from "react-router-v7";
import { getBasename } from "metabase/utils/basename";
import { V7ReduxBridge } from "./V7ReduxBridge";
+import { withBlocking } from "./blocking-history";
import { mapToV7 } from "./map-to-v7";
/**
@@ -24,27 +31,39 @@ export function V7RouterTree({ children }: PropsWithChildren): JSX.Element {
/**
* react-router v7 hosting the app, declarative mode (Phase 3.1). Replaces the v3
* `<Router>` + `useRouterHistory` + `syncHistoryWithStore` stack behind the
- * `use-v7-router` flag.
+ * `use-v7-router` flag. Hosted on a blocking history so `setRouteLeaveHook`
+ * cancels navigation the way it does on v3.
*/
export function RouterProviderV7({ children }: PropsWithChildren): 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 (
- <BrowserRouter basename={getBasename() || undefined}>
+ <HistoryRouter history={history} basename={getBasename() || undefined}>
<V7RouterTree>{children}</V7RouterTree>
- </BrowserRouter>
+ </HistoryRouter>
);
}
/**
* The v7 engine hosted on an in-memory history, for tests. Mirrors what
- * `renderWithProviders({ routerEngine: "v7" })` mounts.
+ * `renderWithProviders({ routerEngine: "v7" })` mounts, including navigation
+ * blocking.
*/
export function RouterProviderV7Memory({
children,
initialRoute,
}: PropsWithChildren<{ initialRoute: string }>): JSX.Element {
+ const [history] = useState(() =>
+ withBlocking(
+ createMemoryHistory({ initialEntries: [initialRoute], v5Compat: true }),
+ ),
+ );
return (
- <MemoryRouter initialEntries={[initialRoute]}>
+ <HistoryRouter history={history}>
<V7RouterTree>{children}</V7RouterTree>
- </MemoryRouter>
+ </HistoryRouter>
);
}
diff --git a/frontend/src/metabase/router/v7/blocking-history.ts b/frontend/src/metabase/router/v7/blocking-history.ts
new file mode 100644
index 00000000000..472fe37e328
--- /dev/null
+++ b/frontend/src/metabase/router/v7/blocking-history.ts
@@ -0,0 +1,154 @@
+import type { Location as HistoryLocation } from "history";
+import {
+ type HistoryRouterProps,
+ type To,
+ type Location as V7Location,
+ parsePath,
+} from "react-router-v7";
+
+import { toV3Location } 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, matching v3's `setRouteLeaveHook` callback: it receives
+ * the attempted destination and returns `false` to cancel the navigation.
+ */
+type LeaveHook = (nextLocation?: HistoryLocation) => unknown;
+
+interface Registration {
+ hook: LeaveHook;
+ // The matched pathname of the guarded route. v3's `setRouteLeaveHook` 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. The v7 `setRouteLeaveHook` shim calls this, so the
+ * leave-confirm modals block navigation on v7 the same way they do on v3.
+ * `basePath` scopes the hook to a route: 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): 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) === false;
+ });
+}
+
+function toBlockedLocation(
+ to: To,
+ action: HistoryLocation["action"],
+ 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 toV3Location(location, action);
+}
+
+/**
+ * Wrap a history so a registered leave hook can cancel navigation, restoring the
+ * v3 `setRouteLeaveHook` 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, "PUSH", state))) {
+ history.push(to, state);
+ }
+ };
+
+ const replace: History["replace"] = (to, state) => {
+ if (!isBlocked(toBlockedLocation(to, "REPLACE", state))) {
+ 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(toV3Location(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
new file mode 100644
index 00000000000..b72ac294df6
--- /dev/null
+++ b/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
@@ -0,0 +1,136 @@
+import type { Location as HistoryLocation } from "history";
+import { UNSAFE_createMemoryHistory as createMemoryHistory } from "react-router-v7";
+
+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");
+ });
+
+ 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 with a PUSH action", () => {
+ 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",
+ action: "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/dual-engine.unit.spec.tsx b/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx
index 7b336879641..40dd513fb64 100644
--- a/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx
+++ b/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx
@@ -1,5 +1,14 @@
+import { useEffect } from "react";
+
import { renderWithProviders, screen, waitFor } from "__support__/ui";
-import { Outlet, Route, push, useLocation, useParams } from "metabase/router";
+import {
+ Outlet,
+ Route,
+ push,
+ useLocation,
+ useParams,
+ useRouter,
+} from "metabase/router";
import { getLocation } from "metabase/selectors/routing";
import type { RouterEngine } from "../engine";
@@ -19,6 +28,18 @@ function Page() {
return <span data-testid="page-id">{id}</span>;
}
+// Registers a route-leave hook the way the leave-confirm modals do, cancelling
+// the navigation when `block` is set.
+function LeaveGuard({ block }: { block: boolean }) {
+ const { router, routes } = useRouter();
+ const route = routes.at(-1);
+ useEffect(
+ () => router.setRouteLeaveHook(route, () => (block ? false : undefined)),
+ [router, route, block],
+ );
+ return null;
+}
+
const tree = (
<Route path="/" element={<Home />}>
<Route path="page/:id" element={<Page />} />
@@ -55,6 +76,72 @@ describe.each<RouterEngine>(["v3", "v7"])(
},
);
+// setRouteLeaveHook must cancel navigation on both engines so the flag stays a
+// reliable two-way switch: v3 blocks natively, v7 through the blocking history.
+describe.each<RouterEngine>(["v3", "v7"])(
+ "route-leave blocking on the %s engine",
+ (routerEngine) => {
+ const blockingTree = (
+ <Route path="/" element={<Home />}>
+ <Route
+ path="page/:id"
+ element={
+ <>
+ <Page />
+ <LeaveGuard block />
+ </>
+ }
+ />
+ <Route path="other" element={<span data-testid="other">other</span>} />
+ </Route>
+ );
+
+ const openTree = (
+ <Route path="/" element={<Home />}>
+ <Route
+ path="page/:id"
+ element={
+ <>
+ <Page />
+ <LeaveGuard block={false} />
+ </>
+ }
+ />
+ <Route path="other" element={<span data-testid="other">other</span>} />
+ </Route>
+ );
+
+ it("cancels navigation while the hook returns false", async () => {
+ const { store } = renderWithProviders(blockingTree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute: "/page/7",
+ });
+ expect(await screen.findByTestId("page-id")).toBeInTheDocument();
+
+ store.dispatch(push("/other"));
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(screen.queryByTestId("other")).not.toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent("/page/7");
+ });
+
+ it("allows navigation when the hook does not block", async () => {
+ const { store } = renderWithProviders(openTree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute: "/page/7",
+ });
+ expect(await screen.findByTestId("page-id")).toBeInTheDocument();
+
+ store.dispatch(push("/other"));
+
+ expect(await screen.findByTestId("other")).toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent("/other");
+ });
+ },
+);
+
// v3 tests never wired `syncHistoryWithStore`, so `state.routing` only tracks the
// location on v7, through the redux bridge. This pins that the bridge feeds it.
describe("v7 redux bridge", () => {
diff --git a/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx b/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx
new file mode 100644
index 00000000000..c3287a95618
--- /dev/null
+++ b/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx
@@ -0,0 +1,83 @@
+import { useEffect } from "react";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import {
+ Outlet,
+ Route,
+ push,
+ useLocation,
+ useRoute,
+ useRouter,
+} from "metabase/router";
+
+import type { RouterEngine } from "../engine";
+
+// Registers an always-blocking leave hook scoped to the route it is rendered on,
+// exactly as the leave-confirm modals do (guard on a parent layout route).
+function Guard() {
+ const { router } = useRouter();
+ const route = useRoute();
+ useEffect(
+ () => router.setRouteLeaveHook(route, () => false),
+ [router, route],
+ );
+ return null;
+}
+
+function Layout() {
+ const { pathname } = useLocation();
+ return (
+ <div>
+ <span data-testid="location">{pathname}</span>
+ <Guard />
+ <Outlet />
+ </div>
+ );
+}
+
+const tree = (
+ <Route path="/">
+ <Route path="section" element={<Layout />}>
+ <Route path="a" element={<span data-testid="a">a</span>} />
+ <Route path="b" element={<span data-testid="b">b</span>} />
+ </Route>
+ <Route path="other" element={<span data-testid="other">other</span>} />
+ </Route>
+);
+
+// v3's `setRouteLeaveHook` is scoped to the guarded route: it fires only when a
+// navigation leaves that route's subtree. So moving between sibling child routes
+// under the guarded layout is allowed, and only leaving the layout is blocked.
+describe.each<RouterEngine>(["v3", "v7"])(
+ "route-scoped leave hook on the %s engine",
+ (routerEngine) => {
+ it("allows navigation that stays within the guarded route", async () => {
+ const { store } = renderWithProviders(tree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute: "/section/a",
+ });
+ expect(await screen.findByTestId("a")).toBeInTheDocument();
+
+ store.dispatch(push("/section/b"));
+
+ expect(await screen.findByTestId("b")).toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent("/section/b");
+ });
+
+ it("blocks navigation that leaves the guarded route", async () => {
+ const { store } = renderWithProviders(tree, {
+ withRouter: true,
+ routerEngine,
+ initialRoute: "/section/a",
+ });
+ expect(await screen.findByTestId("a")).toBeInTheDocument();
+
+ store.dispatch(push("/other"));
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(screen.queryByTestId("other")).not.toBeInTheDocument();
+ expect(screen.getByTestId("location")).toHaveTextContent("/section/a");
+ });
+ },
+);