Skip to content

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

Retire the state.routing slice (#78189)

Romeo Van Snick3488d1525219
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx
index 811c131c720..51692dbfc10 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/tables/components/TableHeader/TableTabs/TableTabs.tsx
@@ -5,9 +5,7 @@ import {
PaneHeaderTabs,
} from "metabase/common/data-studio/components/PaneHeader";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
-import { useSelector } from "metabase/redux";
-import type { Location } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
+import { type Location, useLocation } from "metabase/router";
import * as Urls from "metabase/urls";
import type { Table } from "metabase-types/api";
@@ -16,12 +14,15 @@ type TableTabsProps = {
};
export function TableTabs({ table }: TableTabsProps) {
- const location = useSelector(getLocation);
+ const location = useLocation();
const tabs = getTabs(table, location);
return <PaneHeaderTabs tabs={tabs} />;
}
-function getTabs(table: Table, location: Location): PaneHeaderTab[] {
+function getTabs(
+ table: Table,
+ location: Omit<Location, "query" | "action">,
+): PaneHeaderTab[] {
const tabs: PaneHeaderTab[] = [];
tabs.push({
diff --git a/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx b/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx
index a10b8f3822c..4bcaa23cfe8 100644
--- a/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx
+++ b/frontend/src/embedding-sdk-bundle/test/__support__/ui.tsx
@@ -41,11 +41,8 @@ export function renderWithSDKProviders(
) {
// `settings` is served from the `getSessionProperties` RTK Query cache.
// Capture any seeded settings here and seed the cache through `preloadedState` below.
- let {
- routing,
- settings: seededSettings,
- ...initialState
- }: Partial<StoreSeedState> = createMockState(storeInitialState);
+ let { settings: seededSettings, ...initialState }: Partial<StoreSeedState> =
+ createMockState(storeInitialState);
const sdkReducerNames = Object.keys(sdkReducers);
initialState = _.pick(
diff --git a/frontend/src/metabase/admin/components/AdminNav/AdminNav.tsx b/frontend/src/metabase/admin/components/AdminNav/AdminNav.tsx
index 2e1e092b072..f71e08e5858 100644
--- a/frontend/src/metabase/admin/components/AdminNav/AdminNav.tsx
+++ b/frontend/src/metabase/admin/components/AdminNav/AdminNav.tsx
@@ -1,8 +1,7 @@
import type React from "react";
import { Link } from "metabase/common/components/Link";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import {
Icon,
NavLink,
@@ -39,8 +38,8 @@ export function AdminNavItem({
icon,
...navLinkProps
}: AdminNavItemProps) {
- const location = useSelector(getLocation);
- const subpath = location?.pathname;
+ const location = useLocation();
+ const subpath = location.pathname;
return (
<NavLink
diff --git a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx
index d2600e11d0a..40fc1087009 100644
--- a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx
+++ b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.tsx
@@ -7,8 +7,7 @@ import {
} from "metabase/admin/components/AdminNav";
import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
import { useHasTokenFeature } from "metabase/common/hooks";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import { Divider, Flex, Stack } from "metabase/ui";
export function EmbeddingNav() {
@@ -70,8 +69,8 @@ export function EmbeddingNav() {
}
const EmbeddingNavItem = (props: AdminNavItemProps) => {
- const location = useSelector(getLocation);
- const subpath = location?.pathname;
+ const location = useLocation();
+ const subpath = location.pathname;
const isActive = props.path === subpath;
diff --git a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.unit.spec.tsx b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.unit.spec.tsx
index 4fb086b6cc6..81c7af325fb 100644
--- a/frontend/src/metabase/admin/embedding/components/EmbeddingNav.unit.spec.tsx
+++ b/frontend/src/metabase/admin/embedding/components/EmbeddingNav.unit.spec.tsx
@@ -1,9 +1,5 @@
import { renderWithProviders, screen, within } from "__support__/ui";
-import {
- createMockLocation,
- createMockRoutingState,
- createMockSettingsState,
-} from "metabase/redux/store/mocks";
+import { createMockSettingsState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import {
createMockSettings,
@@ -30,11 +26,6 @@ const setup = ({
initialRoute,
storeInitialState: {
currentUser: createMockUser({ is_superuser: true }),
- routing: createMockRoutingState({
- locationBeforeTransitions: createMockLocation({
- pathname: initialRoute,
- }),
- }),
settings: createMockSettingsState(settings),
},
});
diff --git a/frontend/src/metabase/admin/people/components/PeopleNav.tsx b/frontend/src/metabase/admin/people/components/PeopleNav.tsx
index 48785374dab..d60882047f6 100644
--- a/frontend/src/metabase/admin/people/components/PeopleNav.tsx
+++ b/frontend/src/metabase/admin/people/components/PeopleNav.tsx
@@ -13,7 +13,7 @@ import { UpsellSSO } from "metabase/admin/upsells";
import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
import { useSetting } from "metabase/common/hooks";
import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import { Divider, Stack } from "metabase/ui";
export function PeopleNav() {
@@ -81,7 +81,7 @@ export function PeopleNav() {
}
export const PeopleNavItem = (props: AdminNavItemProps) => {
- const location = useSelector(getLocation);
+ const location = useLocation();
const subpath = location?.pathname;
// we want to highlight the groups nav item if it's showing a details subpage
diff --git a/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.tsx b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.tsx
index 5e8b27a26ce..860fb8b031a 100644
--- a/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.tsx
+++ b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.tsx
@@ -1,13 +1,12 @@
import { AdminSettingsLayout } from "metabase/admin/components/AdminLayout/AdminSettingsLayout";
import { shouldShowTenantsUpsell } from "metabase/admin/people/selectors";
import { useSelector } from "metabase/redux";
-import { Outlet } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
+import { Outlet, useLocation } from "metabase/router";
import { PeopleNav } from "../../components/PeopleNav";
export const AdminPeopleApp = () => {
- const location = useSelector(getLocation);
+ const location = useLocation();
const showTenantsUpsell = useSelector(shouldShowTenantsUpsell);
const isTenantsRoute = location?.pathname.startsWith("/admin/people/tenants");
const isFullWidth = showTenantsUpsell && isTenantsRoute;
diff --git a/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.unit.spec.tsx b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.unit.spec.tsx
index 33e1dfe0b71..8a6e4092c95 100644
--- a/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.unit.spec.tsx
+++ b/frontend/src/metabase/admin/people/containers/AdminPeopleApp/AdminPeopleApp.unit.spec.tsx
@@ -4,8 +4,6 @@ import { createTenantsRouteGuard } from "metabase/admin/utils";
import {
createMockAdminAppState,
createMockAdminState,
- createMockLocation,
- createMockRoutingState,
createMockSettingsState,
createMockState,
} from "metabase/redux/store/mocks";
@@ -79,11 +77,6 @@ const setupTenantRoute = async (initialRoute: string) => {
currentUser: createMockUser({
is_superuser: true,
}),
- routing: createMockRoutingState({
- locationBeforeTransitions: createMockLocation({
- pathname: initialRoute,
- }),
- }),
settings: createMockSettingsState({
"setup-embedding-autoenabled": true,
"use-tenants": false,
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/CustomVisualizationsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/CustomVisualizationsNav.tsx
index 8498fab812a..b10e36717a3 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsNav/CustomVisualizationsNav.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/CustomVisualizationsNav.tsx
@@ -2,8 +2,7 @@ import { t } from "ttag";
import { UpsellGem } from "metabase/common/components/upsells/components";
import { useHasTokenFeature, useSetting } from "metabase/common/hooks";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import { Flex } from "metabase/ui";
import * as Urls from "metabase/urls";
@@ -15,7 +14,7 @@ export const CustomVisualizationsNav = () => {
"custom-viz-plugin-dev-mode-enabled",
);
- const pathname = useSelector(getLocation).pathname;
+ const pathname = useLocation().pathname;
const hasSubNav = hasCustomVizAvailable && customVizDevModeEnabled;
const isManageVisualizationsActive =
pathname.startsWith(Urls.customVizAdd()) ||
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.unit.spec.tsx
index 534004139d4..c15129f247e 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.unit.spec.tsx
@@ -2,11 +2,7 @@ import userEvent from "@testing-library/user-event";
import { setupSettingEndpoint } from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
-import {
- createMockLocation,
- createMockRoutingState,
- createMockSettingsState,
-} from "metabase/redux/store/mocks";
+import { createMockSettingsState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import type { TokenFeatures } from "metabase-types/api";
import {
@@ -51,11 +47,6 @@ const setup = async ({
initialRoute,
storeInitialState: {
currentUser: createMockUser({ is_superuser: true }),
- routing: createMockRoutingState({
- locationBeforeTransitions: createMockLocation({
- pathname: initialRoute,
- }),
- }),
settings: createMockSettingsState(settings),
},
});
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNavItem.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNavItem.tsx
index 0966c15e1cf..057ebb4071f 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNavItem.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNavItem.tsx
@@ -5,8 +5,7 @@ import {
AdminNavItem,
type AdminNavItemProps,
} from "metabase/admin/components/AdminNav";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
/**
* Find the child whose path is the best (longest) prefix match for the current
@@ -46,7 +45,7 @@ export function SettingsNavItem({
}: AdminNavItemProps & { active?: boolean }) {
// Unjustified type cast. FIXME
const children = React.Children.toArray(childrenProp) as ReactElement[];
- const currentPath = useSelector(getLocation)?.pathname ?? "";
+ const currentPath = useLocation().pathname;
const [isOpen, { toggle: toggleOpen }] = useDisclosure(
folderPattern ? currentPath.includes(folderPattern) : false,
);
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/UpdatesNavItem.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/UpdatesNavItem.unit.spec.tsx
index cde08ca9612..4c5d7f0d740 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsNav/UpdatesNavItem.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/UpdatesNavItem.unit.spec.tsx
@@ -5,6 +5,7 @@ import {
} from "__support__/server-mocks";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { createMockSettingsState } from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
import type { SettingKey } from "metabase-types/api";
import {
createMockSettingDefinition,
@@ -44,7 +45,8 @@ const setup = async (props: { versionTag: string }) => {
),
);
- renderWithProviders(<UpdatesNavItem />, {
+ renderWithProviders(<Route path="*" element={<UpdatesNavItem />} />, {
+ withRouter: true,
storeInitialState: {
settings: createMockSettingsState(settings),
},
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index 73395b2be78..0d68f04539a 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -37,6 +37,7 @@ import { initializeInteractiveEmbedding } from "metabase/embedding/interactive-e
import { MetabotProvider } from "metabase/metabot/context";
import { PLUGIN_APP_INIT_FUNCTIONS } from "metabase/plugins";
import { MetabaseReduxProvider } from "metabase/redux";
+import { LOCATION_CHANGE } from "metabase/router";
import { createV7Navigator } from "metabase/router/v7/navigator";
import { getUserId } from "metabase/selectors/user";
import { GlobalStyles } from "metabase/styled-components/containers/GlobalStyles";
@@ -58,32 +59,40 @@ setBasename(window.MetabaseRoot);
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({
- getUserId: () => getUserId(store.getState()),
- });
-
// Initialize distributed tracing if enabled via MB_TRACING_ENABLED.
// Uses bootstrap data so it's available before the first API call.
+ const extraMiddlewares = [];
if (window.MetabaseBootstrap?.["tracing-enabled"]) {
initTracing();
- // Rotate trace ID on route changes so all API calls within a single page view
- // share one trace. The router mirrors the location into state.routing.
+ // Rotate trace ID on route changes so all API calls within a single page
+ // view share one trace. The router emits LOCATION_CHANGE on navigation.
let lastPathname;
- store.subscribe(() => {
- const { pathname } =
- store.getState().routing.locationBeforeTransitions ?? {};
- if (pathname !== lastPathname) {
- lastPathname = pathname;
- rotateTraceId();
+ extraMiddlewares.push(() => (next) => (action) => {
+ if (action?.type === LOCATION_CHANGE) {
+ const pathname = action.payload?.pathname;
+ if (pathname !== lastPathname) {
+ lastPathname = pathname;
+ rotateTraceId();
+ }
}
+ return next(action);
});
}
+ const store = getStore(
+ reducers,
+ createV7Navigator(),
+ undefined,
+ extraMiddlewares,
+ );
+ const routes = getRoutes(store);
+ const mirrorLocation = createLocationMirror(store.dispatch);
+
+ createSnowplowTracker(() => getUserId(store.getState()));
+ initMetaplow({
+ getUserId: () => getUserId(store.getState()),
+ });
+
initializeInteractiveEmbedding(store.dispatch);
const root = createRoot(document.getElementById("root"));
diff --git a/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx b/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx
index b730c6d6da6..dd20ef3986b 100644
--- a/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx
+++ b/frontend/src/metabase/common/data-studio/components/PaneHeader/PaneHeader.tsx
@@ -6,8 +6,7 @@ import { LinkTab } from "metabase/common/components/LinkTab";
import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
import { MetabotDataStudioButton } from "metabase/metabot/components/MetabotDataStudioButton";
import { AppSwitcher } from "metabase/nav/components/AppSwitcher";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import {
Box,
Button,
@@ -145,7 +144,7 @@ function isTabSelected(tab: PaneHeaderTab, pathname: string) {
}
export function PaneHeaderTabs({ tabs }: PaneHeaderTabsProps) {
- const { pathname } = useSelector(getLocation);
+ const { pathname } = useLocation();
const activeTab = tabs.find((tab) => isTabSelected(tab, pathname));
return (
diff --git a/frontend/src/metabase/dashboard/actions/actions.unit.spec.ts b/frontend/src/metabase/dashboard/actions/actions.unit.spec.ts
index d7d10928f10..c01e0a2a997 100644
--- a/frontend/src/metabase/dashboard/actions/actions.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/actions.unit.spec.ts
@@ -2,7 +2,6 @@ import type { Dispatch, GetState } from "metabase/redux/store";
import {
createMockDashboardState,
createMockLocation,
- createMockRoutingState,
createMockState,
createMockStoreDashboard,
} from "metabase/redux/store/mocks";
@@ -17,6 +16,7 @@ import { SIDEBAR_NAME } from "../constants";
import {
CLOSE_SIDEBAR,
SET_DASHBOARD_ATTRIBUTES,
+ SET_EDITING_DASHBOARD,
SET_SIDEBAR,
closeSidebar,
openAddQuestionSidebar,
@@ -208,36 +208,61 @@ describe("dashboard actions", () => {
});
describe("setEditingDashboard", () => {
- const getState: GetState = () =>
- createMockState({
- routing: createMockRoutingState({
- locationBeforeTransitions: createMockLocation({
- pathname: "/dashboard/1",
- hash: "#hashparam",
- }),
- }),
+ it("should remove any hash parameters from url when not editing", () => {
+ const location = createMockLocation({
+ pathname: "/dashboard/1",
+ hash: "#hashparam",
});
- it("should remove any hash parameters from url when not editing", () => {
- setEditingDashboard(null)(dispatch, getState);
+ setEditingDashboard(null, location)(dispatch);
expect(dispatch).toHaveBeenCalledWith({
payload: {
- args: [
- {
- action: "POP",
- hash: "",
- key: "",
- pathname: "/dashboard/1",
- query: {},
- search: "",
- state: undefined,
- },
- ],
+ args: ["/dashboard/1"],
method: "push",
},
type: "@@router/CALL_HISTORY_METHOD",
});
});
+
+ // The v3 history rebuilds `search` from `query`, so pushing a location
+ // object without a `query` field silently drops params like the open tab.
+ it("should keep query params when leaving edit mode", () => {
+ const location = createMockLocation({
+ pathname: "/dashboard/1",
+ search: "?tab=2-tab-two",
+ hash: "#hashparam",
+ });
+
+ setEditingDashboard(null, location)(dispatch);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ payload: {
+ args: ["/dashboard/1?tab=2-tab-two"],
+ method: "push",
+ },
+ type: "@@router/CALL_HISTORY_METHOD",
+ });
+ });
+
+ // The location is captured when the caller rendered, so navigating with no
+ // hash to strip would clobber query params written since (the dashboard tab
+ // sync writes `?tab=` as edit mode exits).
+ it("should not navigate when there is no hash to strip", () => {
+ const location = createMockLocation({
+ pathname: "/dashboard/1",
+ search: "?tab=2-tab-two",
+ });
+
+ setEditingDashboard(null, location)(dispatch);
+
+ expect(dispatch).not.toHaveBeenCalledWith(
+ expect.objectContaining({ type: "@@router/CALL_HISTORY_METHOD" }),
+ );
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_EDITING_DASHBOARD,
+ payload: null,
+ });
+ });
});
});
diff --git a/frontend/src/metabase/dashboard/actions/core.ts b/frontend/src/metabase/dashboard/actions/core.ts
index db1bc8867be..2ad06dfd9e4 100644
--- a/frontend/src/metabase/dashboard/actions/core.ts
+++ b/frontend/src/metabase/dashboard/actions/core.ts
@@ -1,8 +1,7 @@
import { createAction } from "@reduxjs/toolkit";
-import type { Dispatch, GetState } from "metabase/redux/store";
-import { push } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
+import type { Dispatch } from "metabase/redux/store";
+import { type Location, push } from "metabase/router";
import type {
DashCardId,
DashCardVisualizationSettings,
@@ -12,12 +11,23 @@ import type {
} from "metabase-types/api";
export const SET_EDITING_DASHBOARD = "metabase/dashboard/SET_EDITING_DASHBOARD";
-export const setEditingDashboard = (dashboard: Dashboard | null) => {
- return (dispatch: Dispatch, getState: GetState) => {
- if (dashboard === null) {
- const location = getLocation(getState());
- const locationWithoutEditHash = { ...location, hash: "" };
- dispatch(push(locationWithoutEditHash));
+export const setEditingDashboard = (
+ dashboard: Dashboard | null,
+ location?: Omit<Location, "query" | "action">,
+) => {
+ return (dispatch: Dispatch) => {
+ // Leaving edit mode drops any hash params from the URL. The caller passes the
+ // current location, since this no longer reads the retired routing slice.
+ //
+ // Only navigate when there is actually a hash to strip. The location is
+ // captured when the caller rendered, so pushing it unconditionally would
+ // clobber query params written since then (e.g. the tab the dashboard URL
+ // sync just selected, which it will not re-add because it dedupes on the
+ // previous params). Push a path string rather than spreading the location:
+ // it has no v3 `query` field, and the v3 history rebuilds `search` from
+ // `query`, so spreading it would drop the query string entirely.
+ if (dashboard === null && location?.hash) {
+ dispatch(push(`${location.pathname}${location.search}`));
}
dispatch({
@@ -29,10 +39,11 @@ export const setEditingDashboard = (dashboard: Dashboard | null) => {
export const CANCEL_EDITING_DASHBOARD =
"metabase/dashboard/CANCEL_EDITING_DASHBOARD";
-export const cancelEditingDashboard = () => (dispatch: Dispatch) => {
- dispatch(setEditingDashboard(null));
- dispatch({ type: CANCEL_EDITING_DASHBOARD });
-};
+export const cancelEditingDashboard =
+ (location?: Omit<Location, "query" | "action">) => (dispatch: Dispatch) => {
+ dispatch(setEditingDashboard(null, location));
+ dispatch({ type: CANCEL_EDITING_DASHBOARD });
+ };
export type SetDashboardAttributesOpts = {
id: DashboardId;
diff --git a/frontend/src/metabase/dashboard/actions/save.ts b/frontend/src/metabase/dashboard/actions/save.ts
index 97e71160347..7b534f652f8 100644
--- a/frontend/src/metabase/dashboard/actions/save.ts
+++ b/frontend/src/metabase/dashboard/actions/save.ts
@@ -6,6 +6,7 @@ import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
import { createThunkAction } from "metabase/redux";
import { UPDATE_DASHBOARD_AND_CARDS } from "metabase/redux/dashboard";
import type { StoreDashboard, StoreDashcard } from "metabase/redux/store";
+import type { Location } from "metabase/router";
import { clickBehaviorIsValid } from "metabase/visualizations/lib/formatting/click-data";
import type {
DashCardId,
@@ -29,7 +30,7 @@ export const UPDATE_DASHBOARD = "metabase/dashboard/UPDATE_DASHBOARD";
export const updateDashboardAndCards = createThunkAction(
UPDATE_DASHBOARD_AND_CARDS,
- function () {
+ function (location?: Omit<Location, "query" | "action">) {
return async function (dispatch, getState) {
const startTime = performance.now();
const state = getState();
@@ -211,7 +212,7 @@ export const updateDashboardAndCards = createThunkAction(
});
}
- dispatch(setEditingDashboard(null));
+ dispatch(setEditingDashboard(null, location));
// Reset the dashboard state from the save response instead of re-fetching
// it. Re-using the just-returned dashboard avoids an extra round-trip and
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx
index 4589b15abb0..ddedb6df858 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/DashboardHeader.tsx
@@ -18,6 +18,7 @@ import {
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { fetchPulseFormInput } from "metabase/notifications/pulse/actions";
import { useDispatch, useSelector } from "metabase/redux";
+import { useMaybeLocation } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { canManageSubscriptions as canManageSubscriptionsSelector } from "metabase/selectors/user";
import { Flex, Loader } from "metabase/ui";
@@ -36,6 +37,8 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {
const [modalOpened, { open: openModal, close: closeModal }] = useDisclosure();
const dispatch = useDispatch();
+ // The SDK renders the dashboard header outside the app router.
+ const location = useMaybeLocation() ?? undefined;
const { isGuestEmbed } = useDashboardContext();
const canManageSubscriptions = useSelector(canManageSubscriptionsSelector);
@@ -82,7 +85,7 @@ export const DashboardHeaderInner = ({ dashboard }: DashboardHeaderProps) => {
options: { preserveParameters: true },
}),
);
- dispatch(cancelEditingDashboard());
+ dispatch(cancelEditingDashboard(location));
closeModal();
};
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsx
index 1cfb9e81267..dfe340790de 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/SaveEditButton.tsx
@@ -6,11 +6,15 @@ import { getMissingRequiredParameters } from "metabase/dashboard/selectors";
import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
import { useDispatch, useSelector } from "metabase/redux";
import { dismissAllUndo } from "metabase/redux/undo";
+import { useMaybeLocation } from "metabase/router";
import { Tooltip } from "metabase/ui";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
export const SaveEditButton = () => {
const dispatch = useDispatch();
+ // The SDK renders the dashboard header outside the app router, and has no URL
+ // hash to strip, so leaving edit mode there simply skips the navigation.
+ const location = useMaybeLocation() ?? undefined;
const {
setEditingDashboard,
updateDashboardAndCards,
@@ -26,14 +30,14 @@ export const SaveEditButton = () => {
const handleDoneEditing = () => {
onRefreshPeriodChange(null);
- setEditingDashboard(null);
+ setEditingDashboard(null, location);
};
const onSave = async () => {
// optimistically dismissing all the undos before the saving has finished
// clicking on them wouldn't do anything at this moment anyway
dispatch(dismissAllUndo());
- await updateDashboardAndCards();
+ await updateDashboardAndCards(location);
handleDoneEditing();
};
diff --git a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx
index f1cc4e7bff5..dcb2736e616 100644
--- a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx
@@ -5,7 +5,7 @@ import { updateDashboardAndCards } from "metabase/dashboard/actions/save";
import { getIsDirty, getIsEditing } from "metabase/dashboard/selectors";
import { useDispatch, useSelector } from "metabase/redux";
import { dismissAllUndo } from "metabase/redux/undo";
-import { useRoute, useRouter } from "metabase/router";
+import { useLocation, useRoute, useRouter } from "metabase/router";
import { Box, Button, Flex, Modal, Text } from "metabase/ui";
import { isNavigatingToCreateADashboardQuestion } from "./utils";
@@ -15,6 +15,7 @@ export const DashboardLeaveConfirmationModal = () => {
const isDirty = useSelector(getIsDirty);
const { router, routes } = useRouter();
const route = useRoute();
+ const location = useLocation();
const dispatch = useDispatch();
@@ -33,7 +34,7 @@ export const DashboardLeaveConfirmationModal = () => {
actionBtn: {
message: t`Save changes`,
},
- onConfirm: () => dispatch(updateDashboardAndCards()),
+ onConfirm: () => dispatch(updateDashboardAndCards(location)),
}
: {
title: t`Discard your changes?`,
diff --git a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
index b3d1aaa5f00..52034384ec5 100644
--- a/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
+++ b/frontend/src/metabase/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
@@ -11,8 +11,7 @@ import {
PLUGIN_REMOTE_SYNC,
} from "metabase/plugins";
import { useSelector } from "metabase/redux";
-import { Outlet } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
+import { Outlet, useLocation } from "metabase/router";
import { canAccessTransforms as canAccessTransformsSelector } from "metabase/transforms/selectors";
import * as Urls from "metabase/urls";
@@ -29,7 +28,7 @@ export function DataStudioLayout() {
});
const isNavbarOpened = _isNavbarOpened !== false;
- const { pathname } = useSelector(getLocation);
+ const { pathname } = useLocation();
const canAccessDataModel = useSelector(
PLUGIN_FEATURE_LEVEL_PERMISSIONS.canAccessDataModel,
);
diff --git a/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx b/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx
index cccb3cdc734..852315df278 100644
--- a/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx
+++ b/frontend/src/metabase/data-studio/common/components/EntityDetailTabs/EntityDetailTabs.tsx
@@ -5,8 +5,7 @@ import {
PaneHeaderTabs,
} from "metabase/common/data-studio/components/PaneHeader";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
export type EntityDetailTabUrls = {
definition: string;
@@ -19,7 +18,7 @@ type EntityDetailTabsProps = {
};
export function EntityDetailTabs({ urls }: EntityDetailTabsProps) {
- const location = useSelector(getLocation);
+ const location = useLocation();
const tabs: PaneHeaderTab[] = [
{
diff --git a/frontend/src/metabase/documents/hooks/use-register-document-metabot-context.ts b/frontend/src/metabase/documents/hooks/use-register-document-metabot-context.ts
index 203bfeed414..2b91578fce3 100644
--- a/frontend/src/metabase/documents/hooks/use-register-document-metabot-context.ts
+++ b/frontend/src/metabase/documents/hooks/use-register-document-metabot-context.ts
@@ -1,12 +1,12 @@
import { useRegisterMetabotContextProvider } from "metabase/metabot";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
export const useRegisterDocumentMetabotContext = () => {
- useRegisterMetabotContextProvider(async (state) => {
- const location = getLocation(state);
+ const { pathname } = useLocation();
+ useRegisterMetabotContextProvider(async () => {
// Extract document ID from URL path like "/document/123"
- const documentMatch = location.pathname.match(/^\/document\/(\d+)/);
+ const documentMatch = pathname.match(/^\/document\/(\d+)/);
if (!documentMatch) {
return {};
}
@@ -21,5 +21,5 @@ export const useRegisterDocumentMetabotContext = () => {
},
],
};
- }, []);
+ }, [pathname]);
};
diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx
index b873686fb4e..e7010261e75 100644
--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx
@@ -4,11 +4,7 @@ import fetchMock from "fetch-mock";
import { setupEnterprisePlugins } from "__support__/enterprise";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
-import {
- createMockLocation,
- createMockRoutingState,
- createMockState,
-} from "metabase/redux/store/mocks";
+import { createMockState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import type { UserMetabotPermissions } from "metabase-types/api";
import { createMockUserMetabotPermissions } from "metabase-types/api/mocks";
@@ -52,9 +48,6 @@ function setup({
initialRoute: pathname,
storeInitialState: createMockState({
settings,
- routing: createMockRoutingState({
- locationBeforeTransitions: createMockLocation({ pathname }),
- }),
}),
},
);
diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx
index b5c59da34ba..ac8d34f8aa2 100644
--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx
@@ -7,7 +7,6 @@ import {
getMetabotVisible,
} from "metabase/metabot/state";
import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";
-import { createMockLocation } from "metabase/redux/store/mocks";
import {
createMockMetabotConversation,
createMockUser,
@@ -22,14 +21,6 @@ import {
import { MetabotAsk } from "./MetabotAsk";
-const askPageRouting = {
- routing: {
- locationBeforeTransitions: createMockLocation({
- pathname: "/question/ask",
- }),
- },
-};
-
const greetingTitle =
/What would you like to know\?|What do you want to explore\?|What are you looking to learn\?/;
@@ -170,7 +161,6 @@ describe("MetabotAsk", () => {
const { store, history } = setupMetabotAsk({
withRouter: true,
initialRoute: "/question/ask",
- storeInitialState: askPageRouting,
});
mockAgentEndpoint({ events: whoIsYourFavoriteResponse });
@@ -189,7 +179,6 @@ describe("MetabotAsk", () => {
const { history } = setupMetabotAsk({
withRouter: true,
initialRoute: "/question/ask",
- storeInitialState: askPageRouting,
conversations: [
createMockMetabotConversation({
conversation_id: "past-conversation-id",
diff --git a/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx b/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx
index ec97f25ddf4..1dbb15284ee 100644
--- a/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx
@@ -5,8 +5,7 @@ import {
useMetabotName,
useUserMetabotPermissions,
} from "metabase/metabot/hooks";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import { ActionIcon, Tooltip } from "metabase/ui";
import * as Urls from "metabase/urls";
import { METAKEY } from "metabase/utils/browser";
@@ -19,7 +18,7 @@ export const MetabotDataStudioButton = () => {
const { hasMetabotAccess } = useUserMetabotPermissions();
const metabot = useMetabotAgent("omnibot");
const metabotName = useMetabotName();
- const location = useSelector(getLocation);
+ const location = useLocation();
if (!hasMetabotAccess) {
return null;
diff --git a/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx b/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx
index 9780850b17e..bfb5ce5619c 100644
--- a/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotDataStudioSidebar.tsx
@@ -1,13 +1,12 @@
import { t } from "ttag";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import * as Urls from "metabase/urls";
import { Metabot } from "./Metabot";
export function MetabotDataStudioSidebar() {
- const location = useSelector(getLocation);
+ const location = useLocation();
const disabled = !location.pathname?.startsWith(Urls.transformList());
return (
diff --git a/frontend/src/metabase/metabot/hooks/use-is-ask-page.ts b/frontend/src/metabase/metabot/hooks/use-is-ask-page.ts
index 8a624413f45..f24d48891f8 100644
--- a/frontend/src/metabase/metabot/hooks/use-is-ask-page.ts
+++ b/frontend/src/metabase/metabot/hooks/use-is-ask-page.ts
@@ -1,8 +1,9 @@
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useMaybeLocation } from "metabase/router";
import * as Urls from "metabase/urls";
export function useIsAskPage() {
- const { pathname } = useSelector(getLocation);
- return pathname === Urls.newQuestion({ mode: "ask" });
+ // Metabot also renders outside the app router (the SDK, and component tests
+ // that mount it bare), where there is no ask page.
+ const location = useMaybeLocation();
+ return location?.pathname === Urls.newQuestion({ mode: "ask" });
}
diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts b/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts
index 4936321083f..d7d0755f8cc 100644
--- a/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts
+++ b/frontend/src/metabase/metabot/hooks/use-metabot-agent.ts
@@ -3,6 +3,8 @@ import { useCallback } from "react";
import { useMetabotContext } from "metabase/metabot";
import { useDispatch, useSelector } from "metabase/redux";
+import { useMaybeLocation } from "metabase/router";
+import * as Urls from "metabase/urls";
import { trackMetabotRequestSent } from "../analytics";
import type { MetabotProfileId } from "../constants";
@@ -36,6 +38,13 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
const { prompt, setPrompt, promptInputRef, getChatContext } =
useMetabotContext();
+ // `null` when rendered outside the app router (e.g. the SDK), where there is
+ // no transforms page. Drives the transforms-codegen profile auto-selection
+ // that used to read the retired routing slice.
+ const location = useMaybeLocation();
+ const isTransformsPage =
+ location?.pathname.startsWith(Urls.transformList()) ?? false;
+
const metabotRequestId = useSelector((state) =>
getMetabotRequestId(state, agentId),
);
@@ -91,6 +100,7 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
agentId,
metabot_id: metabotRequestId,
profile: options?.profile,
+ isTransformsPage,
}),
);
@@ -112,6 +122,7 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
agentId,
promptInputRef,
setPrompt,
+ isTransformsPage,
],
);
@@ -124,6 +135,7 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
context,
metabot_id: metabotRequestId,
agentId,
+ isTransformsPage,
}),
);
if (isFulfilled(action)) {
@@ -136,6 +148,7 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
metabotRequestId,
prepareRetryIfUnsuccesful,
agentId,
+ isTransformsPage,
],
);
@@ -166,7 +179,9 @@ export const useMetabotAgent = (agentId: MetabotAgentId = "omnibot") => {
retryMessage,
cancelRequest,
metabotId: useSelector(getMetabotId),
- profile: useSelector((state) => getProfile(state, agentId)),
+ profile: useSelector((state) =>
+ getProfile(state, agentId, isTransformsPage),
+ ),
conversationId: useSelector((state) =>
getMetabotConversationId(state, agentId),
),
diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.ts
index 9c723745041..c44631c3305 100644
--- a/frontend/src/metabase/metabot/state/actions.ts
+++ b/frontend/src/metabase/metabot/state/actions.ts
@@ -325,6 +325,7 @@ export const submitInput = createAsyncThunk<
metabot_id?: string;
profile?: MetabotProfileId;
retryMessageId?: string;
+ isTransformsPage?: boolean;
}
>(
"metabase/metabot/submitInput",
@@ -335,6 +336,7 @@ export const submitInput = createAsyncThunk<
message: rawPrompt,
profile,
retryMessageId,
+ isTransformsPage,
...data
} = payload;
const convo = getMetabotConversation(state, agentId);
@@ -380,6 +382,7 @@ export const submitInput = createAsyncThunk<
getState(),
agentId,
retryMessageId,
+ isTransformsPage ?? false,
);
const messageId = createMessageId();
const userMessageId = retryMessageId ?? uuid();
@@ -793,11 +796,12 @@ export const retryPrompt = createAsyncThunk<
context: MetabotChatContext;
metabot_id?: string;
agentId: MetabotAgentId;
+ isTransformsPage?: boolean;
}
>(
"metabase/metabot/retryPrompt",
async (
- { messageId, context, metabot_id, agentId },
+ { messageId, context, metabot_id, agentId, isTransformsPage },
{ getState, dispatch },
) => {
const state = getState();
@@ -825,6 +829,7 @@ export const retryPrompt = createAsyncThunk<
context,
metabot_id,
retryMessageId: prompt.externalId,
+ isTransformsPage,
}),
).unwrap();
},
diff --git a/frontend/src/metabase/metabot/state/selectors.ts b/frontend/src/metabase/metabot/state/selectors.ts
index 763283d2e26..8b5f129b4d0 100644
--- a/frontend/src/metabase/metabot/state/selectors.ts
+++ b/frontend/src/metabase/metabot/state/selectors.ts
@@ -4,7 +4,6 @@ import _ from "underscore";
import { isEmbedding } from "metabase/embedding/config";
import type { State } from "metabase/redux/store";
-import { getLocation } from "metabase/selectors/routing";
import * as Urls from "metabase/urls";
import type { TransformId } from "metabase-types/api";
@@ -280,27 +279,34 @@ export const getProfileOverride = createSelector(
(convo) => convo.profileOverride,
);
-export const getProfile = createSelector(
- [getProfileOverride, getDebugMode, getLocation],
- (profileOverride, debugMode, location): MetabotProfileId | undefined => {
- const isTransformsPage = location.pathname.startsWith(Urls.transformList());
- return match({ debugMode, isTransformsPage })
- .returnType<MetabotProfileId | undefined>()
- .with(
- { debugMode: false, isTransformsPage: true },
- () => "transforms_codegen",
- )
- .with(
- { debugMode: true, isTransformsPage: true },
- () => profileOverride ?? "transforms_codegen",
- )
- .otherwise(() => profileOverride);
- },
-);
+export const getProfile = (
+ state: State,
+ agentId: MetabotAgentId,
+ isTransformsPage: boolean,
+): MetabotProfileId | undefined => {
+ const profileOverride = getProfileOverride(state, agentId);
+ const debugMode = getDebugMode(state);
+ return match({ debugMode, isTransformsPage })
+ .returnType<MetabotProfileId | undefined>()
+ .with(
+ { debugMode: false, isTransformsPage: true },
+ () => "transforms_codegen",
+ )
+ .with(
+ { debugMode: true, isTransformsPage: true },
+ () => profileOverride ?? "transforms_codegen",
+ )
+ .otherwise(() => profileOverride);
+};
export const getAgentRequestMetadata = createSelector(
[
- getProfile,
+ (
+ state: State,
+ agentId: MetabotAgentId,
+ _retryMessageId: string | undefined,
+ isTransformsPage: boolean,
+ ) => getProfile(state, agentId, isTransformsPage),
getLastAgentMessageExternalId,
(
_state: State,
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx
index b2de6434a78..f0117f37cdd 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx
@@ -1,8 +1,7 @@
import { useCallback, useEffect, useState } from "react";
-import { useDispatch, useSelector } from "metabase/redux";
-import { push, replace } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
+import { useDispatch } from "metabase/redux";
+import { push, replace, useLocation } from "metabase/router";
import * as Urls from "metabase/urls";
import { TablePicker } from "./components";
@@ -11,7 +10,7 @@ import type { ChangeOptions, TreePath } from "./types";
export function RouterTablePicker(props: TreePath) {
const dispatch = useDispatch();
const [value, setValue] = useState(props);
- const location = useSelector(getLocation);
+ const location = useLocation();
const isSegments = location.pathname?.startsWith("/admin/datamodel/segment");
const onChange = useCallback(
diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
index fc865ce2bac..af32851879f 100644
--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx
@@ -5,6 +5,7 @@ import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import type { MetricUrls } from "metabase/common/metrics/types";
import { createMockState } from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
import type { Card } from "metabase-types/api";
import {
createMockCard,
@@ -76,9 +77,13 @@ describe("MetricTabs", () => {
}),
});
- renderWithProviders(<MetricTabs card={card} urls={urls} />, {
- storeInitialState: state,
- });
+ renderWithProviders(
+ <Route path="*" element={<MetricTabs card={card} urls={urls} />} />,
+ {
+ withRouter: true,
+ storeInitialState: state,
+ },
+ );
}
function getTabLabels() {
diff --git a/frontend/src/metabase/monitor/components/MonitorHeaderTabs/MonitorHeaderTabs.tsx b/frontend/src/metabase/monitor/components/MonitorHeaderTabs/MonitorHeaderTabs.tsx
index ea7d707a4b3..01a932eedfd 100644
--- a/frontend/src/metabase/monitor/components/MonitorHeaderTabs/MonitorHeaderTabs.tsx
+++ b/frontend/src/metabase/monitor/components/MonitorHeaderTabs/MonitorHeaderTabs.tsx
@@ -1,7 +1,6 @@
import { LinkTab } from "metabase/common/components/LinkTab";
import { UpsellGem } from "metabase/common/components/upsells/components/UpsellGem";
-import { useSelector } from "metabase/redux";
-import { getLocation } from "metabase/selectors/routing";
+import { useLocation } from "metabase/router";
import { FixedSizeIcon, Tabs } from "metabase/ui";
import type { IconName } from "metabase-types/api";
@@ -25,7 +24,7 @@ function isTabSelected(tab: MonitorHeaderTab, pathname: string) {
}
export function MonitorHeaderTabs({ tabs }: MonitorHeaderTabsProps) {
- const { pathname } = useSelector(getLocation);
+ const { pathname } = useLocation();
const activeTab = tabs.find((tab) => isTabSelected(tab, pathname));
return (
diff --git a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx
index bf627df7af3..ab5d5b3f5a8 100644
--- a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx
+++ b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx
@@ -18,8 +18,7 @@ import {
AreaTabGroup,
} from "metabase/nav/components/AreaLayout";
import { useSelector } from "metabase/redux";
-import { Outlet } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
+import { Outlet, useLocation } from "metabase/router";
import { FixedSizeIcon, Flex } from "metabase/ui";
import * as Urls from "metabase/urls";
@@ -58,7 +57,7 @@ export function MonitorLayout() {
});
const isNavbarOpened = _isNavbarOpened !== false;
- const { pathname } = useSelector(getLocation);
+ const { pathname } = useLocation();
const hasDependenciesFeature = useHasTokenFeature("dependencies");
const hasAuditAppFeature = useHasTokenFeature("audit_app");
const canAccessDiagnostics = useSelector(canAccessMonitorDiagnostics);
diff --git a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx
index e39a792acb2..9eff6c647d5 100644
--- a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx
@@ -8,11 +8,7 @@ import {
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
-import {
- createMockLocation,
- createMockRoutingState,
- createMockState,
-} from "metabase/redux/store/mocks";
+import { createMockState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import * as Urls from "metabase/urls";
import type { TokenFeatures } from "metabase-types/api";
@@ -103,9 +99,6 @@ const setup = ({
const state = createMockState({
currentUser: user,
- routing: createMockRoutingState({
- locationBeforeTransitions: createMockLocation({ pathname: initialRoute }),
- }),
settings,
});
diff --git a/frontend/src/metabase/monitor/tools/components/Logs/Logs.unit.spec.tsx b/frontend/src/metabase/monitor/tools/components/Logs/Logs.unit.spec.tsx
index 0e3b482b140..b9250c156ab 100644
--- a/frontend/src/metabase/monitor/tools/components/Logs/Logs.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/tools/components/Logs/Logs.unit.spec.tsx
@@ -2,10 +2,7 @@ import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
-import {
- createMockLocation,
- createMockRoutingState,
-} from "metabase/redux/store/mocks";
+import { createMockLocation } from "metabase/redux/store/mocks";
import type { Location } from "metabase/router";
import { Route } from "metabase/router";
import { openSaveDialog } from "metabase/utils/dom";
@@ -48,11 +45,6 @@ function setup({
<Route path={location.pathname} element={<Logs />} />,
{
initialRoute: `${location.pathname}${location.search}`,
- storeInitialState: {
- routing: createMockRoutingState({
- locationBeforeTransitions: location,
- }),
- },
withRouter: true,
},
);
diff --git a/frontend/src/metabase/query_builder/actions/navigation.ts b/frontend/src/metabase/query_builder/actions/navigation.ts
index 33685c55df1..011a91ee16c 100644
--- a/frontend/src/metabase/query_builder/actions/navigation.ts
+++ b/frontend/src/metabase/query_builder/actions/navigation.ts
@@ -4,7 +4,6 @@ import { createThunkAction } from "metabase/redux";
import { resetUIControls } from "metabase/redux/query-builder";
import type { Dispatch } from "metabase/redux/store";
import type { Location } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
import {
getCard,
@@ -25,13 +24,15 @@ import { zoomInRow } from "./zoom";
export const POP_STATE = "metabase/qb/POP_STATE";
export const popState = createThunkAction(
POP_STATE,
- (location) => async (dispatch, getState) => {
+ (location: Location) => async (dispatch, getState) => {
dispatch(cancelQuery());
const zoomedObjectId = getZoomedObjectId(getState());
if (zoomedObjectId) {
- const { state, query } = getLocation(getState());
- const previouslyZoomedObjectId = state?.objectId || query?.objectId;
+ // The POP has already committed, so `location` is the entry we navigated
+ // to; its state/query hold the object we were previously zoomed into.
+ const previouslyZoomedObjectId =
+ location.state?.objectId || location.query?.objectId;
if (
previouslyZoomedObjectId &&
diff --git a/frontend/src/metabase/query_builder/actions/url.unit.spec.ts b/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
index 5dc9734c79f..7ae08ca2e85 100644
--- a/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/url.unit.spec.ts
@@ -2,9 +2,9 @@
//
// This pins updateUrl -> dispatch(push/replace, { ..., state }), the QB side that
// decides which router action to emit and what card state to carry on it. It is a
-// lock-down net for the upcoming react-router migration and is complementary to
+// lock-down net for the react-router migration and is complementary to
// redux/routing-contract.unit.spec.ts, which pins the transport side (how the
-// dispatched push/replace action mutates state.routing).
+// dispatched push/replace action drives history navigation).
import { createMockEntitiesState } from "__support__/store";
import {
diff --git a/frontend/src/metabase/redux/routing-contract.unit.spec.tsx b/frontend/src/metabase/redux/routing-contract.unit.spec.tsx
index e6281c50843..73ddfbd288d 100644
--- a/frontend/src/metabase/redux/routing-contract.unit.spec.tsx
+++ b/frontend/src/metabase/redux/routing-contract.unit.spec.tsx
@@ -1,32 +1,34 @@
import { act, renderWithProviders, waitFor } from "__support__/ui";
import { Route, goBack, push, replace } from "metabase/router";
-import { getLocation } from "metabase/selectors/routing";
// Keystone characterization test for the navigation TRANSPORT seam.
//
// `metabase/router` owns the `push`/`replace`/`goBack` action creators, the
-// `routerMiddleware`, the `routing` reducer, and the redux bridge that mirrors
-// the router's location back into the store. This test pins the observable
-// contract:
+// `routerMiddleware`, and the redux bridge that drives the router. This test
+// pins the observable contract that survives retiring the `routing` slice:
//
-// dispatch(push/replace/goBack) -> state.routing
+// dispatch(push/replace/goBack) -> router navigation
//
// It wires up the same transport `app.js` uses, isolated from the rest of the
-// app graph.
+// app graph. The location is read off the router rather than the store, since it
+// is no longer mirrored into redux.
const setup = () => {
- const { store } = renderWithProviders(<Route path="*" element={null} />, {
- withRouter: true,
- initialRoute: "/",
- });
+ const { store, history } = renderWithProviders(
+ <Route path="*" element={null} />,
+ {
+ withRouter: true,
+ initialRoute: "/",
+ },
+ );
- // Unjustified type cast. FIXME
- const location = () => getLocation(store.getState() as any);
+ const location = () => history?.getCurrentLocation();
const navigate = async (action: unknown) => {
await act(async () => {
- // Unjustified type cast. FIXME
- store.dispatch(action as any);
+ // The transport actions are typed against the app's dispatch, not the
+ // test store's inferred action union.
+ store.dispatch(action as never);
});
};
@@ -34,9 +36,9 @@ const setup = () => {
};
describe("routing transport contract", () => {
- it("mirrors the initial location into state.routing on mount", async () => {
+ it("starts at the initial location on mount", async () => {
const { location } = setup();
- await waitFor(() => expect(location().pathname).toBe("/"));
+ await waitFor(() => expect(location()?.pathname).toBe("/"));
});
it("push(string) updates pathname, search and hash", async () => {
@@ -44,9 +46,9 @@ describe("routing transport contract", () => {
await navigate(push("/question/42?x=1#hash"));
- expect(location().pathname).toBe("/question/42");
- expect(location().search).toBe("?x=1");
- expect(location().hash).toBe("#hash");
+ expect(location()?.pathname).toBe("/question/42");
+ expect(location()?.search).toBe("?x=1");
+ expect(location()?.hash).toBe("#hash");
});
it("push(descriptor) round-trips location.state (the QB card-state case)", async () => {
@@ -68,8 +70,8 @@ describe("routing transport contract", () => {
}),
);
- expect(location().pathname).toBe("/question");
- expect(location().state).toEqual(cardState);
+ expect(location()?.pathname).toBe("/question");
+ expect(location()?.state).toEqual(cardState);
});
it("preserves the preserveNavbarState flag on location.state", async () => {
@@ -79,18 +81,18 @@ describe("routing transport contract", () => {
push({ pathname: "/question/1", state: { preserveNavbarState: true } }),
);
- expect(location().state).toEqual({ preserveNavbarState: true });
+ expect(location()?.state).toEqual({ preserveNavbarState: true });
});
it("distinguishes push from replace via location.action", async () => {
const { location, navigate } = setup();
await navigate(push("/a"));
- expect(location().action).toBe("PUSH");
+ expect(location()?.action).toBe("PUSH");
await navigate(replace("/b"));
- expect(location().pathname).toBe("/b");
- expect(location().action).toBe("REPLACE");
+ expect(location()?.pathname).toBe("/b");
+ expect(location()?.action).toBe("REPLACE");
});
it("goBack returns to the previous entry", async () => {
@@ -98,26 +100,21 @@ describe("routing transport contract", () => {
await navigate(push("/first"));
await navigate(push("/second"));
- expect(location().pathname).toBe("/second");
+ expect(location()?.pathname).toBe("/second");
await navigate(goBack());
- expect(location().pathname).toBe("/first");
+ expect(location()?.pathname).toBe("/first");
});
- it("mirrors every navigation into state.routing", async () => {
- const { store, location, navigate } = setup();
+ it("routes every navigation through the transport", async () => {
+ const { location, navigate } = setup();
const seen: string[] = [];
- store.subscribe(() => {
- const { pathname } = location();
- if (seen.at(-1) !== pathname) {
- seen.push(pathname);
- }
- });
-
await navigate(push("/one"));
+ seen.push(location()?.pathname ?? "");
await navigate(push("/two"));
+ seen.push(location()?.pathname ?? "");
- expect(seen).toEqual(expect.arrayContaining(["/one", "/two"]));
+ expect(seen).toEqual(["/one", "/two"]);
});
});
diff --git a/frontend/src/metabase/redux/store/mocks/index.ts b/frontend/src/metabase/redux/store/mocks/index.ts
index 7c0633d0c49..b7b6c03cf5d 100644
--- a/frontend/src/metabase/redux/store/mocks/index.ts
+++ b/frontend/src/metabase/redux/store/mocks/index.ts
@@ -7,7 +7,7 @@ export * from "./entities";
export * from "./embed";
export * from "./parameters";
export * from "./qb";
-export * from "./routing";
+export * from "./location";
export * from "./settings";
export * from "./setup";
export * from "./state";
diff --git a/frontend/src/metabase/redux/store/mocks/location.ts b/frontend/src/metabase/redux/store/mocks/location.ts
new file mode 100644
index 00000000000..2c986e63681
--- /dev/null
+++ b/frontend/src/metabase/redux/store/mocks/location.ts
@@ -0,0 +1,14 @@
+import type { Location } from "metabase/router";
+
+export const createMockLocation = (opts?: Partial<Location>): Location => {
+ return {
+ pathname: "/",
+ search: "",
+ query: {},
+ hash: "",
+ state: undefined,
+ action: "POP",
+ key: "", // can be null at runtime but the history typings type it as string
+ ...opts,
+ };
+};
diff --git a/frontend/src/metabase/redux/store/mocks/routing.ts b/frontend/src/metabase/redux/store/mocks/routing.ts
deleted file mode 100644
index 51dc58af17b..00000000000
--- a/frontend/src/metabase/redux/store/mocks/routing.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { Location, RouterState } from "metabase/router";
-
-export const createMockRoutingState = (
- opts?: Partial<RouterState>,
-): RouterState => {
- const location = opts?.locationBeforeTransitions;
- return {
- ...opts,
- locationBeforeTransitions:
- location === null ? null : createMockLocation(location),
- };
-};
-
-export const createMockLocation = (opts?: Partial<Location>): Location => {
- return {
- pathname: "/",
- search: "",
- query: {},
- hash: "",
- state: undefined,
- action: "POP",
- key: "", // can be null at runtime but the history typings type it as string
- ...opts,
- };
-};
diff --git a/frontend/src/metabase/redux/store/mocks/state.ts b/frontend/src/metabase/redux/store/mocks/state.ts
index ac24ca1e8d2..f55527d3ed6 100644
--- a/frontend/src/metabase/redux/store/mocks/state.ts
+++ b/frontend/src/metabase/redux/store/mocks/state.ts
@@ -13,7 +13,6 @@ import { createMockNormalizedEntitiesState } from "./entities";
import { createMockModalState } from "./modal";
import { createMockParametersState } from "./parameters";
import { createMockQueryBuilderState } from "./qb";
-import { createMockRoutingState } from "./routing";
import { createMockSettingsState } from "./settings";
import { createMockSetupState } from "./setup";
import { createMockUploadState } from "./upload";
@@ -46,7 +45,6 @@ export function createMockState(opts: any) {
"metabase-api": createMockApiState(),
parameters: createMockParametersState(),
qb: createMockQueryBuilderState(),
- routing: createMockRoutingState(),
settings: createMockSettingsState(),
setup: createMockSetupState(),
upload: createMockUploadState(),
diff --git a/frontend/src/metabase/redux/store/state.ts b/frontend/src/metabase/redux/store/state.ts
index b6f4adf423d..094d1c06d6c 100644
--- a/frontend/src/metabase/redux/store/state.ts
+++ b/frontend/src/metabase/redux/store/state.ts
@@ -1,6 +1,5 @@
import type { Api } from "metabase/api/api";
import type { DocumentsState } from "metabase/redux/store/documents";
-import type { RouterState } from "metabase/router";
import type { User } from "metabase-types/api";
import type { AdminState } from "./admin";
@@ -37,7 +36,6 @@ export interface State {
parameters: ParametersState;
pulse: PulseState;
qb: QueryBuilderState;
- routing: RouterState;
setup: SetupState;
upload: FileUploadState;
modal: ModalState;
diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsx
index 6716f90ae55..3b2a3e1c711 100644
--- a/frontend/src/metabase/router/RouterProvider.tsx
+++ b/frontend/src/metabase/router/RouterProvider.tsx
@@ -14,8 +14,9 @@ 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`.
+ * Pass `createLocationMirror(store.dispatch)` as `onLocationChange` to emit a
+ * LOCATION_CHANGE for every navigation (the `isNavbarOpen` / `errorPage`
+ * reducers and trace-id rotation react to it).
*/
export const RouterProvider = ({
children,
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 857f730dbf1..3508d3b3848 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -6,7 +6,7 @@ export * from "./redirect";
export * from "./router-link";
export * from "./route";
export * from "./Outlet";
-export * from "./routing-reducer";
+export * from "./location-change";
export * from "./RouterProvider";
export * from "./types";
export * from "./use-location";
diff --git a/frontend/src/metabase/router/location-change.ts b/frontend/src/metabase/router/location-change.ts
new file mode 100644
index 00000000000..9c1569bba00
--- /dev/null
+++ b/frontend/src/metabase/router/location-change.ts
@@ -0,0 +1,7 @@
+/**
+ * The navigation event both engines dispatch on every location change. It no
+ * longer feeds a location slice (the `routing` reducer was retired); the
+ * `isNavbarOpen` and `errorPage` reducers in `metabase/redux/app` still react to
+ * it, and trace-id rotation keys off it.
+ */
+export const LOCATION_CHANGE = "@@router/LOCATION_CHANGE";
diff --git a/frontend/src/metabase/router/routing-reducer.ts b/frontend/src/metabase/router/routing-reducer.ts
deleted file mode 100644
index 4eee88eb95d..00000000000
--- a/frontend/src/metabase/router/routing-reducer.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { Action } from "@reduxjs/toolkit";
-
-import type { Location } from "./types";
-
-/**
- * Re-owned equivalent of react-router-redux's `routerReducer`.
- *
- * Mirrors the current location into `state.routing.locationBeforeTransitions`.
- * Both the slice shape and the LOCATION_CHANGE action type are preserved so
- * `getLocation` and the `isNavbarOpen` / `errorPage` reducers keep working
- * unchanged.
- */
-export const LOCATION_CHANGE = "@@router/LOCATION_CHANGE";
-
-export interface RouterState {
- locationBeforeTransitions: Location | null;
-}
-
-// react-router-redux's reducer starts with a null location and relies on
-// `getLocation`'s default to guard reads until the history sync populates it.
-const INITIAL_STATE: RouterState = {
- locationBeforeTransitions: null,
-};
-
-interface LocationChangeAction extends Action<typeof LOCATION_CHANGE> {
- payload: Location;
-}
-
-function isLocationChange(action: Action): action is LocationChangeAction {
- return action.type === LOCATION_CHANGE;
-}
-
-export function routing(
- state: RouterState = INITIAL_STATE,
- action: Action,
-): RouterState {
- if (isLocationChange(action)) {
- return { ...state, locationBeforeTransitions: action.payload };
- }
- return state;
-}
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 5bd628e5455..02b66366de2 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -44,8 +44,8 @@ export type Query<T = DefaultQuery> = T;
/**
* The `state` carried through a navigation. history@3 typed this `any` and the
- * legacy route-prop readers were written against that; tightened when the
- * `state.routing` slice is thinned to the pure v7 shape (DEV-2290).
+ * legacy route-prop readers were written against that; tightened once those call
+ * sites migrate off the compat shape onto the pure v7 `Location`.
*/
export type LocationState = any;
@@ -53,8 +53,8 @@ export type LocationState = any;
* An entry in a history stack. Mirrors history@3's `Location`: alongside the URL
* parts it carries the parsed `query` object and the navigation `action` that
* the legacy route-prop call sites still read. The generic is the shape of
- * `query`, not `state`. Thinned to the pure v7 shape (no `query`/`action`) when
- * the `state.routing` slice is retired (DEV-2290).
+ * `query`, not `state`. Thinned to the pure v7 shape (no `query`/`action`) once
+ * those call sites migrate off `query`/`action` (follow-up to DEV-2290).
*
* @see https://api.reactrouter.com/v7/interfaces/react-router.Location.html
*/
diff --git a/frontend/src/metabase/router/use-location.ts b/frontend/src/metabase/router/use-location.ts
index f8f7c6997ae..7e9154e2c99 100644
--- a/frontend/src/metabase/router/use-location.ts
+++ b/frontend/src/metabase/router/use-location.ts
@@ -1,3 +1,10 @@
+import { useContext } from "react";
+import {
+ type Location,
+ UNSAFE_LocationContext,
+ useLocation,
+} from "react-router";
+
/**
* react-router v7's `useLocation`. Returns the pure v7 `Location` shape (no v3
* `query`/`action` fields); the legacy compat `Location` type carries those for
@@ -5,4 +12,13 @@
*
* @see https://reactrouter.com/7.18.1/api/hooks/useLocation
*/
-export { useLocation } from "react-router";
+export { useLocation };
+
+/**
+ * Like `useLocation`, but returns `null` when rendered outside a router instead
+ * of throwing. For code shared between the routed app and the SDK, where the
+ * facade router may be absent.
+ */
+export function useMaybeLocation(): Location | null {
+ return useContext(UNSAFE_LocationContext)?.location ?? null;
+}
diff --git a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
index dee202d554f..8248d41fa58 100644
--- a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
+++ b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
@@ -20,10 +20,9 @@ type History = HistoryRouterProps["history"];
* which silently discarded state such as the text typed into a modal that was
* opened right after clicking a link.
*
- * `onLocationChange` runs inside the same history subscription, so `state.routing`
- * is updated as part of the transition the way v3's `syncHistoryWithStore` did.
- * Thunks read the store synchronously right after navigating, so a store that
- * lags a render makes them push a stale location. This stays the blocking
+ * `onLocationChange` runs inside the same history subscription, so LOCATION_CHANGE
+ * is dispatched as part of the transition the way v3's `syncHistoryWithStore` did,
+ * and the reducers keyed off it settle before the next render. This stays the blocking
* history's only subscriber: its POP-revert bookkeeping is per-history rather
* than per-listener, so a second subscription would double-evaluate the leave
* hooks.
diff --git a/frontend/src/metabase/router/v7/V7RouterBridge.tsx b/frontend/src/metabase/router/v7/V7RouterBridge.tsx
index 18f7938ab5f..d7eb992a03a 100644
--- a/frontend/src/metabase/router/v7/V7RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/V7RouterBridge.tsx
@@ -15,8 +15,8 @@ import { setV7Navigate } from "./navigator";
*
* - 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`).
+ * - calls `onLocationChange` for every location, which is how the app emits
+ * LOCATION_CHANGE on navigation (see `createLocationMirror`).
*
* The mirror is driven from the history subscription when one is passed, because
* v3 dispatched LOCATION_CHANGE as part of the transition rather than after a
diff --git a/frontend/src/metabase/router/v7/location-mirror.ts b/frontend/src/metabase/router/v7/location-mirror.ts
index 82dd4e636fe..b7cebe87385 100644
--- a/frontend/src/metabase/router/v7/location-mirror.ts
+++ b/frontend/src/metabase/router/v7/location-mirror.ts
@@ -1,6 +1,6 @@
import type { NavigationType, Location as V7Location } from "react-router";
-import { LOCATION_CHANGE } from "../routing-reducer";
+import { LOCATION_CHANGE } from "../location-change";
import type { Location } from "../types";
import { toV3Location } from "./location";
@@ -22,15 +22,13 @@ type DispatchLocationChange = (action: {
}) => void;
/**
- * Mirrors each location into `state.routing` and the `router.listen`
+ * Emits LOCATION_CHANGE on every navigation and notifies 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.
+ * history subscription, so the reducers keyed off LOCATION_CHANGE
+ * (`isNavbarOpen`, `errorPage`) and trace-id rotation settle as part of the
+ * transition rather than after a render.
*/
export function createLocationMirror(
dispatch: DispatchLocationChange,
diff --git a/frontend/src/metabase/router/v7/location.ts b/frontend/src/metabase/router/v7/location.ts
index 04e20a5ce3c..e8cc12f9171 100644
--- a/frontend/src/metabase/router/v7/location.ts
+++ b/frontend/src/metabase/router/v7/location.ts
@@ -51,8 +51,9 @@ export function queryToSearch(query: Record<string, unknown>): string {
}
/**
- * Build the v3-shaped `history` location the facade context and `state.routing`
- * expect from a v7 location plus the current navigation type.
+ * Build the v3-shaped `history` location the facade context and the
+ * LOCATION_CHANGE payload expect from a v7 location plus the current navigation
+ * type.
*/
export function toV3Location(
location: V7Location,
diff --git a/frontend/src/metabase/selectors/routing.ts b/frontend/src/metabase/selectors/routing.ts
deleted file mode 100644
index ea590d6fd2d..00000000000
--- a/frontend/src/metabase/selectors/routing.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { State } from "metabase/redux/store";
-import type { Location } from "metabase/router";
-
-const DEFAULT_LOCATION: Location = {
- pathname: "",
- search: "",
- query: {},
- hash: "",
- state: undefined,
- action: "POP",
- key: "",
-};
-
-export const getLocation = (state: State) =>
- state.routing?.locationBeforeTransitions ?? DEFAULT_LOCATION;
diff --git a/frontend/src/metabase/selectors/routing.unit.spec.ts b/frontend/src/metabase/selectors/routing.unit.spec.ts
deleted file mode 100644
index 1636da8c692..00000000000
--- a/frontend/src/metabase/selectors/routing.unit.spec.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import {
- createMockLocation,
- createMockRoutingState,
- createMockState,
-} from "metabase/redux/store/mocks";
-
-import { getLocation } from "./routing";
-
-// Characterization tests — these lock the public shape of `getLocation` so the
-// router migration (react-router v3 -> TanStack) cannot silently change what
-// `state.routing` exposes. The migration keeps the `routing` slice shape and
-// the `locationBeforeTransitions` key on purpose; these tests are the net.
-describe("getLocation", () => {
- it("returns state.routing.locationBeforeTransitions", () => {
- const location = createMockLocation({
- pathname: "/question/1",
- search: "?a=1",
- hash: "#abc",
- });
- const state = createMockState({
- routing: createMockRoutingState({ locationBeforeTransitions: location }),
- });
-
- const result = getLocation(state);
- expect(result.pathname).toBe("/question/1");
- expect(result.search).toBe("?a=1");
- expect(result.hash).toBe("#abc");
- });
-
- it("falls back to a default location when routing is absent", () => {
- // Unjustified type cast. FIXME
- const state = { ...createMockState(), routing: undefined } as any;
-
- expect(getLocation(state)).toEqual(createMockLocation({ pathname: "" }));
- });
-
- it("falls back to a default location before the history sync has run", () => {
- const state = createMockState({
- routing: createMockRoutingState({ locationBeforeTransitions: null }),
- });
-
- expect(getLocation(state)).toEqual(createMockLocation({ pathname: "" }));
- });
-});
diff --git a/frontend/src/metabase/store.js b/frontend/src/metabase/store.js
index 0649d3b82a6..b3e673d9547 100644
--- a/frontend/src/metabase/store.js
+++ b/frontend/src/metabase/store.js
@@ -2,7 +2,7 @@ import { combineReducers, configureStore } from "@reduxjs/toolkit";
import { Api } from "metabase/api";
import { PLUGIN_REDUX_MIDDLEWARES } from "metabase/plugins";
-import { routerMiddleware, routing } from "metabase/router";
+import { routerMiddleware } from "metabase/router";
export function getStore(
reducers,
@@ -12,7 +12,6 @@ export function getStore(
) {
const reducer = combineReducers({
...reducers,
- routing,
[Api.reducerPath]: Api.reducer,
});
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index c457328e668..5f1726f9fbb 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -42,7 +42,6 @@ import {
Route,
createLocationMirror,
routerMiddleware,
- routing as routingReducer,
} from "metabase/router";
import {
type MemoryTestHistory,
@@ -190,7 +189,6 @@ export function getTestStoreAndWrapper({
theme,
}: GetTestStoreAndWrapperOptions) {
let {
- routing,
settings, // pull settings out because they aren't in the store
...initialState
}: Partial<StoreSeedState> = createMockState(storeInitialState);
@@ -215,10 +213,6 @@ export function getTestStoreAndWrapper({
reducers = makeMainReducers();
}
- if (withRouter) {
- Object.assign(reducers, { routing: routingReducer });
- Object.assign(initialState, { routing });
- }
if (customReducers) {
reducers = { ...reducers, ...customReducers };
}