Skip to content

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

Stop the router from importing metabase/redux (#78527)

Romeo Van Snick357e2739bd90
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index 2d04e9b904a..8df8f72ba88 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -49,7 +49,7 @@ import { initTracing, rotateTraceId } from "metabase/utils/otel";
import MetabaseSettings from "metabase/utils/settings";
import { registerVisualizations } from "metabase/visualizations/register";
-import { RouterProvider } from "./router";
+import { RouterProvider, createLocationMirror } from "./router";
import { getStore } from "./store";
import { OverlayStackProvider } from "./ui/components/overlays/overlay-stack";
@@ -60,6 +60,7 @@ initializePlugins();
function _init(reducers, getRoutes, callback) {
const store = getStore(reducers, createV7Navigator());
const routes = getRoutes(store);
+ const mirrorLocation = createLocationMirror(store.dispatch);
createSnowplowTracker(() => getUserId(store.getState()));
initMetaplow({
@@ -96,7 +97,9 @@ function _init(reducers, getRoutes, callback) {
<GlobalStyles />
{createPortal(<PortalContainer />, document.body)}
<MetabotProvider>
- <RouterProvider>{routes}</RouterProvider>
+ <RouterProvider onLocationChange={mirrorLocation}>
+ {routes}
+ </RouterProvider>
</MetabotProvider>
</AppThemeProvider>
</OverlayStackProvider>
diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsx
index 92a635c8c1b..6716f90ae55 100644
--- a/frontend/src/metabase/router/RouterProvider.tsx
+++ b/frontend/src/metabase/router/RouterProvider.tsx
@@ -2,6 +2,7 @@ import { type PropsWithChildren, createContext } from "react";
import type { WithRouterProps } from "./types";
import { RouterProviderV7 } from "./v7/RouterProviderV7";
+import type { LocationMirror } from "./v7/location-mirror";
type RouterContextType = WithRouterProps;
@@ -12,7 +13,15 @@ export const RouterContext = createContext<RouterContextType | null>(null);
/**
* Hosts the app on react-router v7.
+ *
+ * Pass `createLocationMirror(store.dispatch)` as `onLocationChange` to mirror
+ * every location into `state.routing`.
*/
-export const RouterProvider = ({ children }: PropsWithChildren) => (
- <RouterProviderV7>{children}</RouterProviderV7>
+export const RouterProvider = ({
+ children,
+ onLocationChange,
+}: PropsWithChildren<{ onLocationChange?: LocationMirror }>) => (
+ <RouterProviderV7 onLocationChange={onLocationChange}>
+ {children}
+ </RouterProviderV7>
);
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 83b547e2b00..857f730dbf1 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -16,3 +16,7 @@ export * from "./use-router";
export * from "./use-search-params";
export * from "./with-route-props";
export { getRawBrowserHistory } from "./v7/blocking-history";
+export {
+ createLocationMirror,
+ type LocationMirror,
+} from "./v7/location-mirror";
diff --git a/frontend/src/metabase/router/router-link.unit.spec.tsx b/frontend/src/metabase/router/router-link.unit.spec.tsx
index 4c7f81efcef..6ade781fbfd 100644
--- a/frontend/src/metabase/router/router-link.unit.spec.tsx
+++ b/frontend/src/metabase/router/router-link.unit.spec.tsx
@@ -1,19 +1,18 @@
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 { Link, Outlet, Route, useLocation, useNavigate } from "metabase/router";
function Home() {
const { pathname, key } = useLocation();
- const dispatch = useDispatch();
+ const navigate = useNavigate();
return (
<div>
<span data-testid="location">{pathname}</span>
<span data-testid="location-key">{key}</span>
<Link to="/other">go</Link>
{/* A `<Link>` used as a button: it navigates through its own onClick. */}
- <Link onClick={() => dispatch(push("/other"))}>act</Link>
+ <Link onClick={() => navigate("/other")}>act</Link>
{/* A button-like `<Link to="">` (e.g. the undo toast) must not navigate. */}
<Link to="" onClick={() => undefined}>
noop
@@ -122,8 +121,8 @@ describe("RouterLink", () => {
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.
+ // The click handler performs the navigation; the link itself must not
+ // navigate, or on v7 it would clobber it and never reach /other.
await userEvent.click(screen.getByText("act"));
expect(await screen.findByTestId("other")).toBeInTheDocument();
diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsx
index be07da883f6..b87be1c711d 100644
--- a/frontend/src/metabase/router/v7/RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx
@@ -176,7 +176,7 @@ function makeRouterShim(navigate: V7NavigateFunction): InjectedRouter {
createHref: href,
isActive: () => false,
// Stands in for v3's `router.listen` (used by e.g. `use-dashboard-url-query`).
- // `V7ReduxBridge` feeds these subscribers every location change.
+ // `V7RouterBridge` feeds these subscribers every location change.
listen: subscribeLocation,
} as InjectedRouter;
}
diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
index 92f7379f440..7b9b4c8a3c2 100644
--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx
+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
@@ -1,5 +1,5 @@
import type { PropsWithChildren } from "react";
-import { useCallback, useState } from "react";
+import { useState } from "react";
import {
type HistoryRouterProps,
Routes,
@@ -7,77 +7,63 @@ import {
UNSAFE_createMemoryHistory as createMemoryHistory,
} from "react-router";
-import { useDispatch } from "metabase/redux";
import { getBasename } from "metabase/utils/basename";
-import { LOCATION_CHANGE } from "../routing-reducer";
-
import { SyncHistoryRouter } from "./SyncHistoryRouter";
-import { V7ReduxBridge } from "./V7ReduxBridge";
+import { V7RouterBridge } from "./V7RouterBridge";
import { withBlocking } from "./blocking-history";
-import { toV3Location } from "./location";
+import type { LocationMirror } from "./location-mirror";
import { mapToV7 } from "./map-to-v7";
-import { notifyLocationListeners } from "./navigator";
/**
* The v7 route tree: the facade tree mapped to real v7 routes and rendered by
- * `<Routes>`, plus the redux bridge that mirrors location into `state.routing`
- * and lets `dispatch(push(...))` drive the router. Kept separate from the history
- * provider below so tests can host the same tree under a `<MemoryRouter>`.
+ * `<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>`.
*/
export function V7RouterTree({
children,
history,
+ onLocationChange,
}: PropsWithChildren<{
history?: HistoryRouterProps["history"];
+ onLocationChange?: LocationMirror;
}>): JSX.Element {
return (
<>
- <V7ReduxBridge history={history} />
+ <V7RouterBridge history={history} onLocationChange={onLocationChange} />
<Routes>{mapToV7(children)}</Routes>
</>
);
}
-/**
- * Mirrors each location into `state.routing` (and the `router.listen`
- * subscribers) from inside the history subscription, so the store is current
- * before any thunk reads it. Replaces v3's `syncHistoryWithStore`.
- */
-function useLocationMirror() {
- const dispatch = useDispatch();
- return useCallback(
- (
- location: Parameters<typeof toV3Location>[0],
- action: Parameters<typeof toV3Location>[1],
- ) => {
- const v3Location = toV3Location(location, action);
- dispatch({ type: LOCATION_CHANGE, payload: v3Location });
- notifyLocationListeners(v3Location);
- },
- [dispatch],
- );
-}
-
/**
* react-router v7 hosting the app, declarative mode. Replaces the v3 `<Router>` +
* `useRouterHistory` + `syncHistoryWithStore` stack. Hosted on a blocking history
* so `setRouteLeaveHook` cancels navigation the way it did on v3.
+ *
+ * `onLocationChange` is how the location reaches redux: the app passes
+ * `createLocationMirror(store.dispatch)`, so the router itself stays unaware of
+ * the store.
*/
-export function RouterProviderV7({ children }: PropsWithChildren): JSX.Element {
+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 })),
);
- const onLocationChange = useLocationMirror();
return (
<SyncHistoryRouter
history={history}
basename={getBasename() || undefined}
onLocationChange={onLocationChange}
>
- <V7RouterTree history={history}>{children}</V7RouterTree>
+ <V7RouterTree history={history} onLocationChange={onLocationChange}>
+ {children}
+ </V7RouterTree>
</SyncHistoryRouter>
);
}
@@ -111,22 +97,25 @@ export function RouterProviderV7Memory({
initialRoute,
basename,
history: providedHistory,
+ onLocationChange,
}: PropsWithChildren<{
initialRoute: string;
basename?: string;
history?: MemoryTestHistory;
+ onLocationChange?: LocationMirror;
}>): JSX.Element {
const [history] = useState(
() => providedHistory ?? createMemoryTestHistory(initialRoute),
);
- const onLocationChange = useLocationMirror();
return (
<SyncHistoryRouter
history={history}
basename={basename}
onLocationChange={onLocationChange}
>
- <V7RouterTree history={history}>{children}</V7RouterTree>
+ <V7RouterTree history={history} onLocationChange={onLocationChange}>
+ {children}
+ </V7RouterTree>
</SyncHistoryRouter>
);
}
diff --git a/frontend/src/metabase/router/v7/V7ReduxBridge.tsx b/frontend/src/metabase/router/v7/V7ReduxBridge.tsx
deleted file mode 100644
index a63c599414f..00000000000
--- a/frontend/src/metabase/router/v7/V7ReduxBridge.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { useEffect } from "react";
-import {
- type HistoryRouterProps,
- useNavigationType,
- useLocation as useV7Location,
- useNavigate as useV7Navigate,
-} from "react-router";
-
-import { useDispatch } from "metabase/redux";
-
-import { LOCATION_CHANGE } from "../routing-reducer";
-
-import { toV3Location } from "./location";
-import { notifyLocationListeners, setV7Navigate } from "./navigator";
-
-/**
- * Bridges the v7 router to redux, 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;
- * - mirrors every location into `state.routing` via LOCATION_CHANGE, so
- * `getLocation` / `isNavbarOpen` / `errorPage` keep working.
- *
- * The mirror subscribes to the history when one is passed, because v3 dispatched
- * LOCATION_CHANGE as part of the transition rather than after a render. Thunks
- * read the store synchronously right after navigating (`setEditingDashboard`
- * pushes `{ ...getLocation(getState()) }`), so a store that lags a render makes
- * them push a stale location and clobber query params that were just set.
- * Falls back to the rendered location when no history is available, which is how
- * tests mount the tree under a plain `<MemoryRouter>`. Deleted with the v3 engine
- * in Phase 4.
- */
-export function V7ReduxBridge({
- history,
-}: {
- history?: HistoryRouterProps["history"];
-}): null {
- const navigate = useV7Navigate();
- const location = useV7Location();
- const action = useNavigationType();
- const dispatch = useDispatch();
-
- 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;
- }
- const v3Location = toV3Location(location, action);
- dispatch({ type: LOCATION_CHANGE, payload: v3Location });
- notifyLocationListeners(v3Location);
- }, [dispatch, history, location, action]);
-
- return null;
-}
diff --git a/frontend/src/metabase/router/v7/V7RouterBridge.tsx b/frontend/src/metabase/router/v7/V7RouterBridge.tsx
new file mode 100644
index 00000000000..18f7938ab5f
--- /dev/null
+++ b/frontend/src/metabase/router/v7/V7RouterBridge.tsx
@@ -0,0 +1,57 @@
+import { useEffect, useRef } from "react";
+import {
+ type HistoryRouterProps,
+ useNavigationType,
+ 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 mirrors
+ * the location into `state.routing` (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();
+ const action = useNavigationType();
+
+ // 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, action);
+ }, [history, location, action]);
+
+ return null;
+}
diff --git a/frontend/src/metabase/router/v7/location-mirror.ts b/frontend/src/metabase/router/v7/location-mirror.ts
new file mode 100644
index 00000000000..82dd4e636fe
--- /dev/null
+++ b/frontend/src/metabase/router/v7/location-mirror.ts
@@ -0,0 +1,43 @@
+import type { NavigationType, Location as V7Location } from "react-router";
+
+import { LOCATION_CHANGE } from "../routing-reducer";
+import type { Location } from "../types";
+
+import { toV3Location } from "./location";
+import { notifyLocationListeners } from "./navigator";
+
+export type LocationMirror = (
+ location: V7Location,
+ action: NavigationType,
+) => void;
+
+/**
+ * The dispatch half of a redux store, narrowed to what the mirror needs. Taking
+ * the function rather than importing `metabase/redux` keeps the router free of
+ * a dependency on the store it happens to feed.
+ */
+type DispatchLocationChange = (action: {
+ type: typeof LOCATION_CHANGE;
+ payload: Location;
+}) => void;
+
+/**
+ * Mirrors each location into `state.routing` and the `router.listen`
+ * subscribers. Replaces v3's `syncHistoryWithStore`.
+ *
+ * Pass the result to `RouterProvider` as `onLocationChange`: it runs inside the
+ * history subscription, so the store is current before any thunk reads it.
+ * Thunks read the store synchronously right after navigating
+ * (`setEditingDashboard` pushes `{ ...getLocation(getState()) }`), so a store
+ * that lags a render makes them push a stale location and clobber query params
+ * that were just set.
+ */
+export function createLocationMirror(
+ dispatch: DispatchLocationChange,
+): LocationMirror {
+ return (location, action) => {
+ const v3Location = toV3Location(location, action);
+ dispatch({ type: LOCATION_CHANGE, payload: v3Location });
+ notifyLocationListeners(v3Location);
+ };
+}
diff --git a/frontend/src/metabase/router/v7/navigator.ts b/frontend/src/metabase/router/v7/navigator.ts
index 07ccfb491d0..b283759e2eb 100644
--- a/frontend/src/metabase/router/v7/navigator.ts
+++ b/frontend/src/metabase/router/v7/navigator.ts
@@ -6,7 +6,7 @@ import type { Location as HistoryLocation, LocationDescriptor } from "../types";
import { queryToSearch } from "./location";
/**
- * The live v7 `navigate`, registered by `V7ReduxBridge` once the router mounts.
+ * The live v7 `navigate`, registered by `V7RouterBridge` 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.
*/
@@ -40,7 +40,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 `V7ReduxBridge` fans every location
+ * `router.listen` had no v7 equivalent, so `V7RouterBridge` 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/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index b6000ced7f9..a500cbd5471 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -29,7 +29,7 @@ import { UndoListing } from "metabase/common/components/UndoListing";
import { baseStyle } from "metabase/css/core/base.styled";
import { makeMainReducers } from "metabase/reducers-main";
import { publicReducers } from "metabase/reducers-public";
-import { MetabaseReduxProvider } from "metabase/redux";
+import { MetabaseReduxProvider, useDispatch } from "metabase/redux";
import type { State } from "metabase/redux/store";
import { createMockState } from "metabase/redux/store/mocks";
import {
@@ -37,6 +37,7 @@ import {
type History,
type LocationDescriptor,
Route,
+ createLocationMirror,
routerMiddleware,
routing as routingReducer,
} from "metabase/router";
@@ -424,6 +425,12 @@ function MaybeRouter({
v7History?: MemoryTestHistory;
initialRoute: string;
}): JSX.Element {
+ const dispatch = useDispatch();
+ const onLocationChange = useMemo(
+ () => createLocationMirror(dispatch),
+ [dispatch],
+ );
+
if (!hasRouter) {
return children;
}
@@ -436,7 +443,11 @@ function MaybeRouter({
<Route path="*" element={children} />
);
return (
- <RouterProviderV7Memory initialRoute={initialRoute} history={v7History}>
+ <RouterProviderV7Memory
+ initialRoute={initialRoute}
+ history={v7History}
+ onLocationChange={onLocationChange}
+ >
{content}
</RouterProviderV7Memory>
);