Skip to content

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

Run the route-leave guards on native useBlocker (#79149)

Romeo Van Snickbd1d5d08ef2c
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx
index 08774979df7..9385573aa88 100644
--- a/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmIfFormIsDirty.tsx
@@ -13,12 +13,13 @@ export const useConfirmIfFormIsDirty = () => {
useConfirmation();
const askBeforeDiscardingChanges = useCallback(
- (onConfirm: () => void) =>
+ (onConfirm: () => void, onCancel?: () => void) =>
askConfirmation({
title: t`Discard your changes?`,
message: t`Your changes haven’t been saved, so you’ll lose them if you navigate away.`,
confirmButtonText: t`Discard`,
onConfirm,
+ onCancel,
}),
[askConfirmation],
);
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
index 51655a818c3..59d1d6380d3 100644
--- a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.tsx
@@ -1,39 +1,30 @@
-import { useRef } from "react";
+import { useEffect, useRef } from "react";
-import { useDispatch } from "metabase/redux";
-import { push, useNavigate, useRouteLeaveHook } from "metabase/router";
+import { useRouteLeaveBlocker } from "metabase/router";
type Props = {
shouldConfirm: boolean;
- confirm: (onConfirm: () => void) => void;
+ confirm: (onConfirm: () => void, onCancel: () => void) => void;
};
export const useConfirmOnRouteLeave = ({ shouldConfirm, confirm }: Props) => {
- const dispatch = useDispatch();
- const navigate = useNavigate();
- /**
- * to prevent endless loop
- */
- const confirmedRef = useRef<boolean>(false);
+ const blocker = useRouteLeaveBlocker(() => shouldConfirm);
- useRouteLeaveHook((nextLocation) => {
- if (confirmedRef.current || !shouldConfirm) {
- return true;
+ // Both are replaced on every render or router state update. Read them through
+ // refs so the effect below keys on the blocked state alone, and so asks once
+ // per attempted navigation rather than again on every unrelated update.
+ const latest = useRef({ blocker, confirm });
+ latest.current = { blocker, confirm };
+
+ useEffect(() => {
+ if (blocker.state !== "blocked") {
+ return;
}
- /**
- * This will roll browser's URL back.
- * Returning false from this function cancels routing on the redux level, but browser's URL changes anyway.
- * So we need to roll this change back and then roll forward if user confirms.
- *
- * Unfortunately it won't work if user somewhere in the middle of history (e.g. has forward button available)
- */
- navigate(1);
- confirm(() => {
- confirmedRef.current = true;
- if (nextLocation) {
- dispatch(push(nextLocation));
- }
- });
- return false;
- });
+ // The navigation is parked, so the URL never moved and there is nothing to
+ // roll back: confirming resumes it, dismissing drops it.
+ latest.current.confirm(
+ () => latest.current.blocker.proceed?.(),
+ () => latest.current.blocker.reset?.(),
+ );
+ }, [blocker.state]);
};
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
index f581f0a6bd9..e45a217b8d9 100644
--- a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
@@ -1,4 +1,4 @@
-import { act, renderWithProviders, screen } from "__support__/ui";
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
import type { History } from "metabase/router";
import { Route } from "metabase/router";
import { checkNotNull } from "metabase/utils/types";
@@ -47,7 +47,8 @@ describe("useConfirmOnRouteLeave", () => {
expect(screen.getByText("Page B")).toBeInTheDocument();
expect(history.getCurrentLocation().pathname).toBe("/b");
- // Simulate browser back, which should trigger confirmation and roll URL forward
+ // Simulate browser back. The router parks the navigation and asks for
+ // confirmation, so the URL stays on /b until the answer comes back.
act(() => history.goBack());
};
@@ -64,7 +65,7 @@ describe("useConfirmOnRouteLeave", () => {
expect(history.getCurrentLocation().pathname).toBe("/b");
});
- it("navigates to the previous route when clicking 'Yes' in the confirmation", () => {
+ it("navigates to the previous route when clicking 'Yes' in the confirmation", async () => {
const { history } = setup();
// Do confirm
@@ -73,8 +74,11 @@ describe("useConfirmOnRouteLeave", () => {
// try to leave a page
navigateToBAndTriggerBack(history);
- // We should navigate to /a
- expect(screen.getByText("Page A")).toBeInTheDocument();
- expect(history.getCurrentLocation().pathname).toBe("/a");
+ // We should navigate to /a. The router resumes the parked navigation itself,
+ // which it does asynchronously.
+ expect(await screen.findByText("Page A")).toBeInTheDocument();
+ await waitFor(() =>
+ expect(history.getCurrentLocation().pathname).toBe("/a"),
+ );
});
});
diff --git a/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
index 1b6b13a58d5..691766ef8e8 100644
--- a/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
+++ b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
@@ -1,16 +1,6 @@
-import { useCallback, useEffect, useState } from "react";
-import { match } from "ts-pattern";
+import { useCallback } from "react";
-import { useDispatch } from "metabase/redux";
-import {
- type Action,
- type Location,
- goBack,
- push,
- replace,
- useRouteLeaveHook,
- useRoutePathname,
-} from "metabase/router";
+import { type Location, useRouteLeaveBlocker } from "metabase/router";
import { useBeforeUnload } from "./use-before-unload";
@@ -26,11 +16,9 @@ interface UseConfirmLeaveModalResult {
nextLocation: Location | undefined;
}
-/**
- * If there is no "location" then it's beforeunload event, which is
- * handled by useBeforeUnload hook - no reason to duplicate its work.
- */
-export const IS_LOCATION_ALLOWED = (location?: Location) => !location;
+// Nothing is allowed through by default: every destination gets the modal.
+// Reload and tab close never reach here, they are `useBeforeUnload`'s job.
+const BLOCK_EVERY_LOCATION = () => false;
// NOTE: there's a similar hook called useConfirmOnRouteLeave that should
// ported to use this format instead
@@ -41,74 +29,23 @@ export const IS_LOCATION_ALLOWED = (location?: Location) => !location;
*/
export const useConfirmRouteLeaveModal = ({
isEnabled,
- isLocationAllowed = IS_LOCATION_ALLOWED,
+ isLocationAllowed = BLOCK_EVERY_LOCATION,
}: UseConfirmLeaveModalInput): UseConfirmLeaveModalResult => {
- const dispatch = useDispatch();
- const routePathname = useRoutePathname();
- const [nextNavigation, setNextNavigation] = useState<{
- location: Location;
- navigationType: Action;
- }>();
-
- const [opened, setOpened] = useState<boolean>(false);
- const close = useCallback(() => setOpened(false), []);
-
- const [isConfirmed, setIsConfirmed] = useState(false);
- const confirm = useCallback(() => setIsConfirmed(true), []);
-
useBeforeUnload(isEnabled);
- useRouteLeaveHook((location, navigationType) => {
- if (isEnabled && !isConfirmed && !isLocationAllowed?.(location)) {
- setOpened(true);
- setNextNavigation(
- location && navigationType ? { location, navigationType } : undefined,
- );
- return false;
- }
- });
-
- useEffect(
- function confirmNavigation() {
- if (isConfirmed && nextNavigation) {
- const { location, navigationType } = nextNavigation;
- match(navigationType)
- .with("POP", () => {
- /**
- * Ideally we should be using dispatch(go(numberOfPages)), but there is no simple
- * or reliable way to detect how many pages is user going back, so we use goBack()
- * to go back just one page.
- */
- dispatch(goBack());
- })
- .with("PUSH", () => {
- dispatch(push(location));
- })
- .with("REPLACE", () => {
- dispatch(replace(location));
- })
- .exhaustive();
- }
- },
- [dispatch, isConfirmed, nextNavigation],
+ const blocker = useRouteLeaveBlocker(
+ ({ nextLocation }) => isEnabled && !isLocationAllowed(nextLocation),
);
- useEffect(
- /**
- * We need to reset the state in case programmatic navigation from confirmNavigation effect
- * does not cause useConfirmRouteLeaveModal hook to unmount.
- */
- function resetState() {
- setIsConfirmed(false);
- setOpened(false);
- },
- [routePathname],
- );
+ // The blocker holds the attempted navigation, so confirming resumes it and
+ // dismissing drops it. Neither has to reproduce the navigation by hand.
+ const close = useCallback(() => blocker.reset?.(), [blocker]);
+ const confirm = useCallback(() => blocker.proceed?.(), [blocker]);
return {
- opened,
+ opened: blocker.state === "blocked",
close,
confirm,
- nextLocation: nextNavigation?.location,
+ nextLocation: blocker.location,
};
};
diff --git a/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.unit.spec.tsx b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.unit.spec.tsx
new file mode 100644
index 00000000000..afb74ecb7a9
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.unit.spec.tsx
@@ -0,0 +1,116 @@
+import userEvent from "@testing-library/user-event";
+
+import { act, renderWithProviders, screen } from "__support__/ui";
+import { type Location, Route } from "metabase/router";
+import { checkNotNull } from "metabase/utils/types";
+
+import { useConfirmRouteLeaveModal } from "./use-confirm-route-leave-modal";
+
+interface GuardProps {
+ isEnabled?: boolean;
+ isLocationAllowed?: (location: Location | undefined) => boolean;
+}
+
+function Guard({ isEnabled = true, isLocationAllowed }: GuardProps) {
+ const { opened, close, confirm, nextLocation } = useConfirmRouteLeaveModal({
+ isEnabled,
+ isLocationAllowed,
+ });
+
+ return (
+ <div>
+ <span data-testid="opened">{String(opened)}</span>
+ <span data-testid="next-location">{nextLocation?.pathname ?? ""}</span>
+ <button onClick={confirm}>confirm</button>
+ <button onClick={close}>close</button>
+ </div>
+ );
+}
+
+const setup = (props: GuardProps = {}) => {
+ const { history } = renderWithProviders(
+ <Route path="/">
+ <Route path="a" element={<Guard {...props} />} />
+ <Route path="b" element={<span>page b</span>} />
+ </Route>,
+ { withRouter: true, initialRoute: "/a" },
+ );
+
+ return { history: checkNotNull(history) };
+};
+
+/**
+ * Fires the event the browser sends on reload or tab close, and reports whether
+ * a handler asked to interrupt it.
+ */
+const isUnloadGuarded = () => {
+ const event = new Event("beforeunload", { cancelable: true });
+ act(() => {
+ window.dispatchEvent(event);
+ });
+ return event.defaultPrevented;
+};
+
+describe("useConfirmRouteLeaveModal", () => {
+ it("opens on a navigation away, and reports where it was headed", () => {
+ const { history } = setup();
+
+ act(() => history.push("/b"));
+
+ expect(screen.getByTestId("opened")).toHaveTextContent("true");
+ expect(screen.getByTestId("next-location")).toHaveTextContent("/b");
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ });
+
+ it("lets the navigation through on confirm", async () => {
+ const { history } = setup();
+ act(() => history.push("/b"));
+
+ await userEvent.click(screen.getByRole("button", { name: "confirm" }));
+
+ expect(await screen.findByText("page b")).toBeInTheDocument();
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+
+ it("stays put on close", async () => {
+ const { history } = setup();
+ act(() => history.push("/b"));
+
+ await userEvent.click(screen.getByRole("button", { name: "close" }));
+
+ expect(screen.getByTestId("opened")).toHaveTextContent("false");
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ });
+
+ it("does not open when it is disabled", () => {
+ const { history } = setup({ isEnabled: false });
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+
+ it("does not open for a destination the caller allows", () => {
+ const { history } = setup({
+ isLocationAllowed: (location) => location?.pathname === "/b",
+ });
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+
+ // `useBlocker` only sees in-app navigation, so reload and tab close stay with
+ // the `beforeunload` guard.
+ it("guards reload and tab close while it is enabled", () => {
+ setup();
+
+ expect(isUnloadGuarded()).toBe(true);
+ });
+
+ it("leaves reload and tab close alone when it is disabled", () => {
+ setup({ isEnabled: false });
+
+ expect(isUnloadGuarded()).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
index 1d228a2f0ac..1320836ec66 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { usePrevious } from "react-use";
import _ from "underscore";
@@ -12,6 +12,7 @@ import {
queryToSearch,
replace,
subscribeLocation,
+ useIsNavigationHeld,
} from "metabase/router";
import * as Urls from "metabase/urls";
import { parseSearchQuery } from "metabase/utils/browser";
@@ -31,6 +32,7 @@ export function useDashboardUrlQuery(location: Location) {
const selectedTab = useSelector(getSelectedTab);
const parameters = useSelector(getValuePopulatedParameters);
const siteUrl = useSetting("site-url");
+ const isNavigationHeld = useIsNavigationHeld();
const dispatch = useDispatch();
@@ -51,6 +53,7 @@ export function useDashboardUrlQuery(location: Location) {
}, [parameterValuesBySlug, tabs, selectedTab]);
const previousQueryParams = usePrevious(queryParams);
+ const hasDeferredSyncRef = useRef(false);
useEffect(() => {
/**
@@ -63,6 +66,18 @@ export function useDashboardUrlQuery(location: Location) {
return;
}
+ /**
+ * A leave prompt is up, and the router holds a single pending navigation.
+ * Syncing now would replace the destination the user is being asked about,
+ * and letting them through would then take them somewhere else. Note that
+ * the sync was skipped, because `previousQueryParams` still advances and
+ * would otherwise swallow it once the prompt is answered.
+ */
+ if (isNavigationHeld) {
+ hasDeferredSyncRef.current = true;
+ return;
+ }
+
const pathname = location.pathname.replace(siteUrl, "");
const isDashboardUrl = pathname.startsWith("/dashboard/");
if (isDashboardUrl) {
@@ -74,9 +89,13 @@ export function useDashboardUrlQuery(location: Location) {
}
}
- if (_.isEqual(previousQueryParams, queryParams)) {
+ if (
+ !hasDeferredSyncRef.current &&
+ _.isEqual(previousQueryParams, queryParams)
+ ) {
return;
}
+ hasDeferredSyncRef.current = false;
const currentQuery = parseSearchQuery(location.search);
@@ -102,6 +121,7 @@ export function useDashboardUrlQuery(location: Location) {
location,
siteUrl,
dispatch,
+ isNavigationHeld,
]);
useEffect(() => {
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
index 0908ae6a225..185b79d7826 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
@@ -10,7 +10,7 @@ import {
createMockStoreDashboard,
} from "metabase/redux/store/mocks";
import type { Location } from "metabase/router";
-import { push, replace } from "metabase/router";
+import { push, replace, useIsNavigationHeld } from "metabase/router";
import { notifyLocationListeners } from "metabase/router/v7/navigator";
import type { ParameterValueOrArray } from "metabase-types/api";
import { createMockParameter } from "metabase-types/api/mocks";
@@ -28,6 +28,7 @@ jest.mock("metabase/router", () => ({
type: "MOCK_REPLACE",
payload: descriptor,
})),
+ useIsNavigationHeld: jest.fn(() => false),
}));
jest.mock("metabase/embedding/config", () => ({
@@ -87,12 +88,12 @@ function setup({
settings: createMockSettingsState({ "site-url": "" }),
});
- const { store, unmount } = renderHookWithProviders(
+ const { store, unmount, rerender } = renderHookWithProviders(
() => useDashboardUrlQuery(location),
{ storeInitialState },
);
- return { store, unmount, location };
+ return { store, unmount, rerender, location };
}
describe("useDashboardUrlQuery", () => {
@@ -103,6 +104,46 @@ describe("useDashboardUrlQuery", () => {
(replace as jest.Mock).mockClear();
// Unjustified type cast. FIXME
(isEmbedPreview as jest.Mock).mockReturnValue(false);
+ // Unjustified type cast. FIXME
+ (useIsNavigationHeld as jest.Mock).mockReturnValue(false);
+ });
+
+ // The router keeps one pending navigation. Syncing the URL while a leave
+ // prompt is up would replace the destination the user is being asked about,
+ // and confirming would then take them somewhere they never agreed to
+ // (metabase#53132).
+ describe("while a leave prompt holds a navigation", () => {
+ it("does not sync the query string", () => {
+ // Unjustified type cast. FIXME
+ (useIsNavigationHeld as jest.Mock).mockReturnValue(true);
+
+ setup({
+ parameters: [createMockParameter({ id: "1", slug: "text" })],
+ parameterValues: { "1": "bar" },
+ });
+
+ expect(replace).not.toHaveBeenCalled();
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("syncs once the prompt is answered", () => {
+ // Unjustified type cast. FIXME
+ (useIsNavigationHeld as jest.Mock).mockReturnValue(true);
+
+ const { rerender } = setup({
+ parameters: [createMockParameter({ id: "1", slug: "text" })],
+ parameterValues: { "1": "bar" },
+ });
+ expect(replace).not.toHaveBeenCalled();
+
+ // Unjustified type cast. FIXME
+ (useIsNavigationHeld as jest.Mock).mockReturnValue(false);
+ rerender();
+
+ expect(replace).toHaveBeenCalledWith(
+ expect.objectContaining({ search: "?text=bar" }),
+ );
+ });
});
it("syncs a parameter-value change with replace (not push), writing the parameter slug values into the search string", () => {
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index cfe6e1ba8e5..c997c9dab2c 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -12,7 +12,7 @@ export * from "./use-location";
export * from "./use-navigate";
export * from "./use-navigation-type";
export * from "./use-params";
-export * from "./use-route-leave-hook";
+export * from "./use-route-leave-blocker";
export * from "./use-search-params";
export {
createMemoryAppRouter,
diff --git a/frontend/src/metabase/router/route.unit.spec.tsx b/frontend/src/metabase/router/route.unit.spec.tsx
index 88523b87725..8718f7c8b1b 100644
--- a/frontend/src/metabase/router/route.unit.spec.tsx
+++ b/frontend/src/metabase/router/route.unit.spec.tsx
@@ -5,7 +5,7 @@ import { checkNotNull } from "metabase/utils/types";
import { Outlet } from "./Outlet";
import { Route } from "./route";
-import { useRoutePathname } from "./use-route-leave-hook";
+import { useRoutePathname } from "./use-route-leave-blocker";
const Parent = () => (
<div>
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index c75c594e850..7a50f0a61f0 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -179,17 +179,6 @@ export interface RouteProps {
component?: RouteComponent;
}
-/**
- * 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.
- */
-export type RouteHook = (
- nextLocation?: Location,
- navigationType?: Action,
-) => unknown;
-
/**
* v3's function form of a `<Link to>`, kept because `RouterLink` still handles it.
*/
diff --git a/frontend/src/metabase/router/use-route-leave-blocker.ts b/frontend/src/metabase/router/use-route-leave-blocker.ts
new file mode 100644
index 00000000000..30f8d982b78
--- /dev/null
+++ b/frontend/src/metabase/router/use-route-leave-blocker.ts
@@ -0,0 +1,48 @@
+import { useContext, useId, useRef } from "react";
+import type { Blocker, BlockerFunction } from "react-router";
+import { UNSAFE_RouteContext } from "react-router";
+
+import { useGuardedBlocker } from "./v7/route-leave-guards";
+
+export { useIsNavigationHeld } from "./v7/route-leave-guards";
+
+/**
+ * Block navigation that leaves the route this component renders in, replacing
+ * v3's `router.setRouteLeaveHook(route, hook)`.
+ *
+ * `shouldBlock` decides per navigation. A blocked navigation is parked rather
+ * than cancelled: the returned blocker reports `state === "blocked"` and carries
+ * the attempted destination, and `proceed()` lets it through while `reset()`
+ * drops it. So the caller no longer re-issues the navigation itself.
+ *
+ * The scope is the route's matched pathname, so a destination that stays inside
+ * that route does not block, matching v3's `listenBeforeLeavingRoute`. Callers
+ * do not pass the route in: v7 publishes the matched branch, so the scope is
+ * read here rather than threaded through props.
+ *
+ * Guards nest. Several can be mounted at once, the innermost one that blocks
+ * gets the prompt, and letting it through asks the rest before the navigation
+ * resumes.
+ *
+ * @see https://reactrouter.com/7.18.1/api/hooks/useBlocker
+ */
+export function useRouteLeaveBlocker(shouldBlock: BlockerFunction): Blocker {
+ const id = useId();
+ const basePath = useRoutePathname();
+
+ // `shouldBlock` closes over state that changes every render (whether the page
+ // is dirty). Read it through a ref so the registration stays put: re-running
+ // it would drop the guard for the moment a navigation could land in.
+ const latestShouldBlock = useRef(shouldBlock);
+ latestShouldBlock.current = shouldBlock;
+
+ return useGuardedBlocker(id, latestShouldBlock, basePath);
+}
+
+/**
+ * The matched pathname of the route this component renders in.
+ */
+export function useRoutePathname(): string | undefined {
+ const { matches } = useContext(UNSAFE_RouteContext);
+ return matches.at(-1)?.pathname;
+}
diff --git a/frontend/src/metabase/router/use-route-leave-blocker.unit.spec.tsx b/frontend/src/metabase/router/use-route-leave-blocker.unit.spec.tsx
new file mode 100644
index 00000000000..77bb38b0047
--- /dev/null
+++ b/frontend/src/metabase/router/use-route-leave-blocker.unit.spec.tsx
@@ -0,0 +1,279 @@
+import userEvent from "@testing-library/user-event";
+import type { PropsWithChildren } from "react";
+
+import { act, renderWithProviders, screen } from "__support__/ui";
+import { checkNotNull } from "metabase/utils/types";
+
+import { Route } from "./route";
+import { useRouteLeaveBlocker } from "./use-route-leave-blocker";
+
+const shouldBlock = jest.fn();
+
+/**
+ * Renders the blocker's state, and buttons for the two ways out of it, so a spec
+ * can assert on a parked navigation and then resume or drop it.
+ */
+function Guard() {
+ const blocker = useRouteLeaveBlocker(shouldBlock);
+
+ return (
+ <div>
+ <span data-testid="blocker-state">{blocker.state}</span>
+ <span data-testid="blocked-pathname">
+ {blocker.location?.pathname ?? ""}
+ </span>
+ <button onClick={() => blocker.proceed?.()}>proceed</button>
+ <button onClick={() => blocker.reset?.()}>reset</button>
+ </div>
+ );
+}
+
+const setup = (initialRoute = "/a") => {
+ const { history } = renderWithProviders(
+ <Route path="/">
+ <Route path="a" element={<Guard />} />
+ <Route path="b" element={<span>page b</span>} />
+ </Route>,
+ { withRouter: true, initialRoute },
+ );
+
+ return { history: checkNotNull(history) };
+};
+
+describe("useRouteLeaveBlocker", () => {
+ beforeEach(() => {
+ shouldBlock.mockReturnValue(false);
+ });
+
+ it("parks a push while it blocks", () => {
+ shouldBlock.mockReturnValue(true);
+ const { history } = setup();
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("blocked");
+ });
+
+ it("lets a push through when it does not block", () => {
+ const { history } = setup();
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+
+ it("parks a replace while it blocks", () => {
+ shouldBlock.mockReturnValue(true);
+ const { history } = setup();
+
+ act(() => history.replace("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ });
+
+ it("hands the attempted destination and the navigation type to the caller", () => {
+ shouldBlock.mockReturnValue(true);
+ const { history } = setup();
+
+ act(() => history.push("/b?x=1"));
+
+ expect(shouldBlock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ nextLocation: expect.objectContaining({
+ pathname: "/b",
+ search: "?x=1",
+ }),
+ historyAction: "PUSH",
+ }),
+ );
+ expect(screen.getByTestId("blocked-pathname")).toHaveTextContent("/b");
+ });
+
+ it("resumes the parked navigation on proceed", async () => {
+ shouldBlock.mockReturnValue(true);
+ const { history } = setup();
+ act(() => history.push("/b"));
+
+ await userEvent.click(screen.getByRole("button", { name: "proceed" }));
+
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ expect(screen.getByText("page b")).toBeInTheDocument();
+ });
+
+ it("drops the parked navigation on reset", async () => {
+ shouldBlock.mockReturnValue(true);
+ const { history } = setup();
+ act(() => history.push("/b"));
+
+ await userEvent.click(screen.getByRole("button", { name: "reset" }));
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("unblocked");
+ });
+
+ it("cancels the browser back button while it blocks", () => {
+ const { history } = setup();
+ act(() => history.push("/b"));
+ act(() => history.push("/a"));
+ shouldBlock.mockReturnValue(true);
+
+ act(() => history.goBack());
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ });
+
+ it("lets the browser back button through when it does not block", () => {
+ const { history } = setup();
+ act(() => history.push("/b"));
+ act(() => history.push("/a"));
+
+ act(() => history.goBack());
+
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+});
+
+const outerShouldBlock = jest.fn();
+
+function OuterGuard({ children }: PropsWithChildren) {
+ const blocker = useRouteLeaveBlocker(outerShouldBlock);
+
+ return (
+ <div>
+ <span data-testid="outer-state">{blocker.state}</span>
+ <button onClick={() => blocker.proceed?.()}>proceed outer</button>
+ {children}
+ </div>
+ );
+}
+
+const setupNestedGuards = () => {
+ const { history } = renderWithProviders(
+ <Route path="/">
+ <Route
+ path="a"
+ element={
+ <OuterGuard>
+ <Guard />
+ </OuterGuard>
+ }
+ />
+ <Route path="b" element={<span>page b</span>} />
+ </Route>,
+ { withRouter: true, initialRoute: "/a" },
+ );
+
+ return { history: checkNotNull(history) };
+};
+
+// react-router holds one blocker per router. The app fans that one out, so a
+// guard is not silently dropped when another is mounted on the same page: the
+// caching sidebar mounts one inside the dashboard and the query builder, which
+// carry their own.
+describe("useRouteLeaveBlocker with several guards mounted", () => {
+ beforeEach(() => {
+ outerShouldBlock.mockReturnValue(false);
+ shouldBlock.mockReturnValue(false);
+ });
+
+ it("blocks when only the inner guard says so", () => {
+ shouldBlock.mockReturnValue(true);
+ const { history } = setupNestedGuards();
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("blocked");
+ expect(screen.getByTestId("outer-state")).toHaveTextContent("unblocked");
+ });
+
+ it("blocks when only the outer guard says so", () => {
+ outerShouldBlock.mockReturnValue(true);
+ const { history } = setupNestedGuards();
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ expect(screen.getByTestId("outer-state")).toHaveTextContent("blocked");
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("unblocked");
+ });
+
+ it("gives the prompt to the inner guard when both say so", () => {
+ outerShouldBlock.mockReturnValue(true);
+ shouldBlock.mockReturnValue(true);
+ const { history } = setupNestedGuards();
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("blocked");
+ expect(screen.getByTestId("outer-state")).toHaveTextContent("unblocked");
+ });
+
+ it("asks the outer guard once the inner one is let through", async () => {
+ outerShouldBlock.mockReturnValue(true);
+ shouldBlock.mockReturnValue(true);
+ const { history } = setupNestedGuards();
+ act(() => history.push("/b"));
+
+ await userEvent.click(screen.getByRole("button", { name: "proceed" }));
+
+ // Letting the inner guard through hands the prompt to the outer one rather
+ // than releasing the navigation, so a second dirty form still gets a say.
+ expect(screen.getByTestId("outer-state")).toHaveTextContent("blocked");
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("unblocked");
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ });
+
+ it("resumes the navigation once every guard has been asked", async () => {
+ outerShouldBlock.mockReturnValue(true);
+ shouldBlock.mockReturnValue(true);
+ const { history } = setupNestedGuards();
+ act(() => history.push("/b"));
+
+ await userEvent.click(screen.getByRole("button", { name: "proceed" }));
+ await userEvent.click(
+ screen.getByRole("button", { name: "proceed outer" }),
+ );
+
+ expect(await screen.findByText("page b")).toBeInTheDocument();
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+
+ it("drops the navigation when any guard in the chain resets", async () => {
+ outerShouldBlock.mockReturnValue(true);
+ shouldBlock.mockReturnValue(true);
+ const { history } = setupNestedGuards();
+ act(() => history.push("/b"));
+
+ await userEvent.click(screen.getByRole("button", { name: "reset" }));
+
+ expect(history.getCurrentLocation().pathname).toBe("/a");
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("unblocked");
+ expect(screen.getByTestId("outer-state")).toHaveTextContent("unblocked");
+ });
+
+ it("lets a navigation through when neither says so", () => {
+ const { history } = setupNestedGuards();
+
+ act(() => history.push("/b"));
+
+ expect(history.getCurrentLocation().pathname).toBe("/b");
+ });
+});
+
+// A guard registers with the provider above it, which only a mounted router
+// supplies. Without one it registers nowhere, so it cannot hold a navigation it
+// has no way to release.
+describe("useRouteLeaveBlocker outside a router", () => {
+ it("is inert rather than an error", () => {
+ shouldBlock.mockReturnValue(true);
+ shouldBlock.mockClear();
+
+ renderWithProviders(<Guard />, { withRouter: false });
+
+ expect(screen.getByTestId("blocker-state")).toHaveTextContent("unblocked");
+ expect(shouldBlock).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/router/use-route-leave-hook.ts b/frontend/src/metabase/router/use-route-leave-hook.ts
deleted file mode 100644
index 63a138040a3..00000000000
--- a/frontend/src/metabase/router/use-route-leave-hook.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { useContext, useEffect, useRef } from "react";
-import { UNSAFE_RouteContext } from "react-router";
-
-import type { RouteHook } from "./types";
-import { registerLeaveHook } from "./v7/leave-hooks";
-
-/**
- * Register a hook that runs before a navigation leaves the route this component
- * renders in, replacing v3's `router.setRouteLeaveHook(route, hook)`. Returning
- * `false` cancels the navigation.
- *
- * The hook is scoped to the route's matched pathname, so it does not fire for a
- * destination that stays inside that route, matching v3's
- * `listenBeforeLeavingRoute`.
- *
- * Callers no longer pass the route in. v3 had to inject it because only the
- * route object knew its own pattern; v7 publishes the matched branch, so the
- * scope is read here instead of threaded through props.
- *
- * Replaced by native `useBlocker` once the data router hosts the app (DEV-2375).
- */
-export function useRouteLeaveHook(hook: RouteHook): void {
- const basePath = useRoutePathname();
-
- // The hook closes over state that changes every render (whether the page is
- // dirty, whether the user already confirmed). Read it through a ref so the
- // registration survives those renders: re-registering would drop the hook for
- // the moment a navigation could land in.
- const latestHook = useRef(hook);
- latestHook.current = hook;
-
- useEffect(
- () =>
- registerLeaveHook(
- (location, navigationType) =>
- latestHook.current(location, navigationType),
- basePath,
- ),
- [basePath],
- );
-}
-
-/**
- * The matched pathname of the route this component renders in. Changes whenever
- * the component is reused across a navigation that re-matched its route, which
- * is what the leave-confirm state keys its reset on.
- */
-export function useRoutePathname(): string | undefined {
- const { matches } = useContext(UNSAFE_RouteContext);
- return matches.at(-1)?.pathname;
-}
diff --git a/frontend/src/metabase/router/v7/AppShell.tsx b/frontend/src/metabase/router/v7/AppShell.tsx
index 6c1aaf0826e..4fb9d7d2835 100644
--- a/frontend/src/metabase/router/v7/AppShell.tsx
+++ b/frontend/src/metabase/router/v7/AppShell.tsx
@@ -2,6 +2,7 @@ import { useEffect } from "react";
import { Outlet, useNavigate } from "react-router";
import { setV7Navigate } from "./navigator";
+import { RouteLeaveGuards } from "./route-leave-guards";
/**
* The element of the host's pathless layout route.
@@ -13,6 +14,8 @@ import { setV7Navigate } from "./navigator";
* 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" }`).
+ *
+ * It also owns the router's single blocker, which the route-leave guards share.
*/
export function AppShell(): JSX.Element {
const navigate = useNavigate();
@@ -22,5 +25,9 @@ export function AppShell(): JSX.Element {
return () => setV7Navigate(null);
}, [navigate]);
- return <Outlet />;
+ return (
+ <RouteLeaveGuards>
+ <Outlet />
+ </RouteLeaveGuards>
+ );
}
diff --git a/frontend/src/metabase/router/v7/create-router.tsx b/frontend/src/metabase/router/v7/create-router.tsx
index 1bd5a553d8c..0a8dd8a0acf 100644
--- a/frontend/src/metabase/router/v7/create-router.tsx
+++ b/frontend/src/metabase/router/v7/create-router.tsx
@@ -8,7 +8,6 @@ import {
} from "react-router";
import { AppShell } from "./AppShell";
-import { installLeaveHookBlocker } from "./leave-hooks";
import { mapToV7 } from "./map-to-v7";
export type MemoryTestRouter = DataRouter;
@@ -36,9 +35,7 @@ export function createAppRouter(
tree: ReactNode,
basename?: string,
): DataRouter {
- const router = createBrowserRouter(toDataRoutes(tree), { basename });
- installLeaveHookBlocker(router);
- return router;
+ return createBrowserRouter(toDataRoutes(tree), { basename });
}
export function createMemoryAppRouter(
@@ -49,10 +46,8 @@ export function createMemoryAppRouter(
const entry = initialRoute.startsWith("/")
? initialRoute
: `/${initialRoute}`;
- const router = createMemoryRouter(toDataRoutes(tree), {
+ return 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
deleted file mode 100644
index 1666b2efc00..00000000000
--- a/frontend/src/metabase/router/v7/leave-hooks.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-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
deleted file mode 100644
index 4b11464f200..00000000000
--- a/frontend/src/metabase/router/v7/leave-hooks.unit.spec.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-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/route-leave-guards.tsx b/frontend/src/metabase/router/v7/route-leave-guards.tsx
new file mode 100644
index 00000000000..ff30652cae5
--- /dev/null
+++ b/frontend/src/metabase/router/v7/route-leave-guards.tsx
@@ -0,0 +1,206 @@
+import type { PropsWithChildren, RefObject } from "react";
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import type { Blocker, BlockerFunction } from "react-router";
+import { useBlocker } from "react-router";
+
+type BlockerArgs = Parameters<BlockerFunction>[0];
+
+interface Guard {
+ // Held as a ref because the caller's decision closes over state that changes
+ // every render, while the registration itself must stay put.
+ shouldBlock: RefObject<BlockerFunction>;
+ // The matched pathname of the guarded route. A guard only fires when a
+ // navigation leaves that route's subtree, so a guard with a base path does not
+ // fire for destinations that stay under it.
+ basePath?: string;
+}
+
+function staysWithin(basePath: string | undefined, pathname: string): boolean {
+ if (!basePath) {
+ return false;
+ }
+ const base = basePath.replace(/\/$/, "");
+ return pathname === base || pathname.startsWith(`${base}/`);
+}
+
+/**
+ * The first guard that wants to stop this navigation and has not been answered
+ * for it yet. Insertion order is mount order, so the innermost guard goes first.
+ */
+function findBlockingGuard(
+ guards: Map<string, Guard>,
+ args: BlockerArgs,
+ answered: Set<string>,
+): string | null {
+ for (const [id, { shouldBlock, basePath }] of guards) {
+ if (answered.has(id) || staysWithin(basePath, args.nextLocation.pathname)) {
+ continue;
+ }
+ if (shouldBlock.current?.(args)) {
+ return id;
+ }
+ }
+ return null;
+}
+
+interface RouteLeaveGuardsValue {
+ registerGuard: (id: string, guard: Guard) => () => void;
+ blockedGuardId: string | null;
+ blocker: Blocker;
+ proceedFrom: (id: string) => void;
+ resetAll: () => void;
+}
+
+const RouteLeaveGuardsContext = createContext<RouteLeaveGuardsValue | null>(
+ null,
+);
+
+/**
+ * Owns the router's blocker on behalf of every route-leave guard below it.
+ *
+ * react-router holds one blocker per router, and a second `useBlocker` silently
+ * takes over from the first, so the app registers exactly one and fans it out.
+ * That matters here: the caching sidebar's form guard sits inside both the
+ * dashboard and the query builder, which carry their own. The one-blocker limit
+ * is tracked in https://github.com/remix-run/react-router/discussions/9978. Drop
+ * this fan-out if react-router grows support for several blockers.
+ *
+ * Guards are answered in turn. The first one that blocks gets the prompt, and
+ * letting it through asks the rest before the navigation resumes, so two dirty
+ * forms on one page prompt twice, as they did when each guard cancelled the
+ * navigation outright.
+ *
+ * The registry lives here rather than at module level, so a guard rendered
+ * outside a router registers nowhere and stays inert. A module-level registry
+ * would still be consulted by a router mounted elsewhere, and could then block a
+ * navigation that no mounted component is able to release.
+ */
+export function RouteLeaveGuards({ children }: PropsWithChildren): JSX.Element {
+ const guardsRef = useRef(new Map<string, Guard>());
+ // Guards that already had their say about the navigation being held.
+ const answeredRef = useRef(new Set<string>());
+ const blockedArgsRef = useRef<BlockerArgs | null>(null);
+ const [blockedGuardId, setBlockedGuardId] = useState<string | null>(null);
+
+ const registerGuard = useCallback((id: string, guard: Guard) => {
+ guardsRef.current.set(id, guard);
+ return () => {
+ guardsRef.current.delete(id);
+ answeredRef.current.delete(id);
+ setBlockedGuardId((current) => (current === id ? null : current));
+ };
+ }, []);
+
+ const shouldBlock = useCallback<BlockerFunction>((args) => {
+ answeredRef.current.clear();
+ blockedArgsRef.current = args;
+
+ const id = findBlockingGuard(guardsRef.current, args, answeredRef.current);
+ setBlockedGuardId(id);
+ return id != null;
+ }, []);
+
+ const blocker = useBlocker(shouldBlock);
+
+ const proceedFrom = useCallback(
+ (id: string) => {
+ answeredRef.current.add(id);
+
+ const args = blockedArgsRef.current;
+ const next = args
+ ? findBlockingGuard(guardsRef.current, args, answeredRef.current)
+ : null;
+
+ // Hand the prompt to the next guard that objects. Only once none is left
+ // does the navigation itself resume.
+ if (next) {
+ setBlockedGuardId(next);
+ } else {
+ blocker.proceed?.();
+ }
+ },
+ [blocker],
+ );
+
+ const resetAll = useCallback(() => {
+ answeredRef.current.clear();
+ setBlockedGuardId(null);
+ blocker.reset?.();
+ }, [blocker]);
+
+ const value = useMemo(
+ () => ({ registerGuard, blockedGuardId, blocker, proceedFrom, resetAll }),
+ [registerGuard, blockedGuardId, blocker, proceedFrom, resetAll],
+ );
+
+ return (
+ <RouteLeaveGuardsContext.Provider value={value}>
+ {children}
+ </RouteLeaveGuardsContext.Provider>
+ );
+}
+
+const IDLE_BLOCKER: Blocker = {
+ state: "unblocked",
+ proceed: undefined,
+ reset: undefined,
+ location: undefined,
+};
+
+/**
+ * Whether a leave prompt is holding a navigation right now.
+ *
+ * A page that syncs its own URL has to stand still while one is up. react-router
+ * keeps a single pending navigation, so navigating now replaces the one the user
+ * is being asked about, and letting them through would then take them somewhere
+ * they never agreed to.
+ */
+export function useIsNavigationHeld(): boolean {
+ const context = useContext(RouteLeaveGuardsContext);
+ return context?.blockedGuardId != null && context.blocker.state === "blocked";
+}
+
+/**
+ * Registers a guard with the nearest `RouteLeaveGuards`, and reports the blocker
+ * for as long as that guard is the one holding the navigation. Outside a router
+ * there is no provider, so the guard registers nowhere and stays idle.
+ */
+export function useGuardedBlocker(
+ id: string,
+ shouldBlock: RefObject<BlockerFunction>,
+ basePath: string | undefined,
+): Blocker {
+ const context = useContext(RouteLeaveGuardsContext);
+ const registerGuard = context?.registerGuard;
+
+ useEffect(
+ () => registerGuard?.(id, { shouldBlock, basePath }),
+ [registerGuard, id, shouldBlock, basePath],
+ );
+
+ return useMemo<Blocker>(() => {
+ if (!context) {
+ return IDLE_BLOCKER;
+ }
+
+ const { blocker, blockedGuardId, proceedFrom, resetAll } = context;
+ if (blockedGuardId !== id || blocker.state !== "blocked") {
+ return IDLE_BLOCKER;
+ }
+
+ return {
+ state: "blocked",
+ location: blocker.location,
+ proceed: () => proceedFrom(id),
+ reset: resetAll,
+ };
+ }, [context, id]);
+}
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
index fa28cc658e2..ec895e25a42 100644
--- a/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx
+++ b/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx
@@ -4,13 +4,13 @@ import {
Route,
push,
useLocation,
- useRouteLeaveHook,
+ useRouteLeaveBlocker,
} from "metabase/router";
-// 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).
+// Blocks every navigation, scoped to the route it is rendered on, exactly as the
+// leave-confirm modals do (guard on a parent layout route).
function Guard() {
- useRouteLeaveHook(() => false);
+ useRouteLeaveBlocker(() => true);
return null;
}