Skip to content

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

Stop passing query objects in navigation descriptors (#78796)

Romeo Van Snickbfbedff78ad3
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
index d1d484b2a05..ad6cd178d7e 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.tsx
@@ -10,7 +10,7 @@ import { useUrlState } from "metabase/common/hooks/use-url-state";
import { serializeDateParameterValue } from "metabase/querying/parameters/utils/parsing";
import { useDispatch } from "metabase/redux";
import type { WithRouterProps } from "metabase/router";
-import { push } from "metabase/router";
+import { push, queryToSearch } from "metabase/router";
import { Button, Flex, SimpleGrid, Tabs, Text, Title } from "metabase/ui";
import { hasPremiumFeature } from "metabase-enterprise/settings";
@@ -194,16 +194,18 @@ export function ConversationStatsPage({ location }: WithRouterProps) {
dispatch(
push({
pathname: "/admin/metabot/usage-auditing/conversations",
- query: conversationsUrlStateConfig.serialize({
- page: 0,
- sort_column: "created_at",
- sort_direction: "desc",
- date,
- user,
- group,
- tenant,
- ...filterOverrides,
- }),
+ search: queryToSearch(
+ conversationsUrlStateConfig.serialize({
+ page: 0,
+ sort_column: "created_at",
+ sort_direction: "desc",
+ date,
+ user,
+ group,
+ tenant,
+ ...filterOverrides,
+ }),
+ ),
}),
);
},
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/components/LensNavigator/useLensNavigation.ts b/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/components/LensNavigator/useLensNavigation.ts
index 03f271d4bb3..153b781f099 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/components/LensNavigator/useLensNavigation.ts
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-inspector/pages/TransformInspectPage/components/LensNavigator/useLensNavigation.ts
@@ -3,7 +3,7 @@ import { t } from "ttag";
import { useDispatch } from "metabase/redux";
import type { Location } from "metabase/router";
-import { push, replace } from "metabase/router";
+import { push, queryToSearch, replace } from "metabase/router";
import type { InspectorLensMetadata } from "metabase-types/api";
import type { LensHandle, RouteParams } from "../../types";
@@ -95,7 +95,9 @@ export const useLensNavigation = (
(handle: LensHandle, isReplace: boolean = false) => {
const action = isReplace ? replace : push;
const path = `${basePath}/${handle.id}`;
- dispatch(action({ pathname: path, query: handle.params }));
+ dispatch(
+ action({ pathname: path, search: queryToSearch(handle.params ?? {}) }),
+ );
},
[basePath, dispatch],
);
diff --git a/frontend/src/metabase/admin/ai/AISettingsPage.tsx b/frontend/src/metabase/admin/ai/AISettingsPage.tsx
index 6b6170e0c1f..18bc81546f5 100644
--- a/frontend/src/metabase/admin/ai/AISettingsPage.tsx
+++ b/frontend/src/metabase/admin/ai/AISettingsPage.tsx
@@ -17,7 +17,7 @@ import {
PLUGIN_EMBEDDING_IFRAME_SDK,
PLUGIN_EMBEDDING_SDK,
} from "metabase/plugins";
-import { useRouter } from "metabase/router";
+import { queryToSearch, useRouter } from "metabase/router";
import { Divider, Flex, Stack, Switch, Tabs } from "metabase/ui";
import { AIProviderSettingsSection } from "./AIProviderSettingsSection";
@@ -276,8 +276,8 @@ function getSelectedMetabotId(metabotId: string | undefined): MetabotTabId {
function getMetabotTabPath(metabotId: MetabotTabId) {
return {
pathname: METABOT_SETTINGS_PATH,
- query: {
+ search: queryToSearch({
[METABOT_ID_QUERY_PARAM]: String(metabotId),
- },
+ }),
};
}
diff --git a/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx b/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx
index e6ca35ca86f..dceb20d3026 100644
--- a/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx
+++ b/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx
@@ -7,8 +7,8 @@ import { FieldSet } from "metabase/common/components/FieldSet";
import CS from "metabase/css/core/index.css";
import { DatabaseSchemaAndTableDataSelector } from "metabase/querying/common/components/DataSelector";
import { connect, useSelector } from "metabase/redux";
-import type { Location } from "metabase/router";
-import { push } from "metabase/router";
+import type { Location, LocationDescriptorObject } from "metabase/router";
+import { push, queryToSearch } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import { Icon } from "metabase/ui";
import type { ConcreteTableId, Segment } from "metabase-types/api";
@@ -19,7 +19,7 @@ type LocationWithQuery = Location<{
type FilteredToUrlTableInnerProps = {
location: LocationWithQuery;
- push: (location: LocationWithQuery) => void;
+ push: (location: LocationDescriptorObject) => void;
segments: Segment[];
};
@@ -53,7 +53,9 @@ export function FilteredToUrlTable(
setTableIdState(newTableId);
push({
...location,
- query: newTableId == null ? {} : { table: String(newTableId) },
+ search: queryToSearch(
+ newTableId == null ? {} : { table: String(newTableId) },
+ ),
});
};
diff --git a/frontend/src/metabase/common/hooks/use-url-state/use-url-state.ts b/frontend/src/metabase/common/hooks/use-url-state/use-url-state.ts
index f054bd07cfe..7004074254b 100644
--- a/frontend/src/metabase/common/hooks/use-url-state/use-url-state.ts
+++ b/frontend/src/metabase/common/hooks/use-url-state/use-url-state.ts
@@ -5,7 +5,7 @@ import _ from "underscore";
import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
import { useDispatch } from "metabase/redux";
import type { Location, Query } from "metabase/router";
-import { push, replace } from "metabase/router";
+import { push, queryToSearch, replace } from "metabase/router";
type BaseState = Record<string, unknown>;
@@ -38,7 +38,10 @@ export function useUrlState<State extends BaseState>(
const updateUrl = useCallback(
(state: State) => {
- const newLocation = { ...location, query: serialize(state) };
+ const newLocation = {
+ ...location,
+ search: queryToSearch(serialize(state)),
+ };
dispatch(push(newLocation));
},
[dispatch, location, serialize],
@@ -51,7 +54,7 @@ export function useUrlState<State extends BaseState>(
// Replacing to the identical URL notifies the router, which re-renders every
// location consumer on the page for nothing.
if (!_.isEqual(query, location.query)) {
- dispatch(replace({ ...location, query }));
+ dispatch(replace({ ...location, search: queryToSearch(query) }));
}
});
diff --git a/frontend/src/metabase/dashboard/actions/parameters.tsx b/frontend/src/metabase/dashboard/actions/parameters.tsx
index 0fcf42442e1..5116f1bc99d 100644
--- a/frontend/src/metabase/dashboard/actions/parameters.tsx
+++ b/frontend/src/metabase/dashboard/actions/parameters.tsx
@@ -24,7 +24,7 @@ import { createAction, createThunkAction } from "metabase/redux";
import { selectTab, setParameterValues } from "metabase/redux/dashboard";
import type { Dispatch, GetState } from "metabase/redux/store";
import { addUndo, dismissUndo } from "metabase/redux/undo";
-import type { LocationDescriptorObject } from "metabase/router";
+import type { Query } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import { Text } from "metabase/ui";
import { isQuestionDashCard } from "metabase/utils/dashboard";
@@ -1070,7 +1070,7 @@ export const setOrUnsetParameterValues =
};
export const setParameterValuesFromQueryParams =
- (queryParams: LocationDescriptorObject["query"] = {}) =>
+ (queryParams: Query = {}) =>
(dispatch: Dispatch, getState: GetState) => {
const parameters = getParameters(getState());
const parameterValues = getParameterValuesByIdFromQueryParams(
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
index a33bff92135..3fb05a3b8b1 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
@@ -20,7 +20,7 @@ import { EmbeddingEntityContextProvider } from "metabase/embedding/context";
import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";
import { useDispatch, useSelector } from "metabase/redux";
import type { LocationDescriptorObject } from "metabase/router";
-import { push } from "metabase/router";
+import { push, searchToQuery } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Flex, Group, type IconProps, Menu, Title } from "metabase/ui";
import { isVirtualDashCard } from "metabase/utils/dashboard";
@@ -178,7 +178,9 @@ export function DashCardVisualization({
const onSameOriginNavigation = useCallback(
(location: LocationDescriptorObject) => {
dispatch(push(location));
- dispatch(setParameterValuesFromQueryParams(location.query));
+ dispatch(
+ setParameterValuesFromQueryParams(searchToQuery(location.search ?? "")),
+ );
},
[dispatch],
);
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
index 4635d45d9c9..18b22a89cf9 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
@@ -10,6 +10,7 @@ import {
type InjectedRouter,
type Location,
push,
+ queryToSearch,
replace,
} from "metabase/router";
import * as Urls from "metabase/urls";
@@ -94,7 +95,7 @@ export function useDashboardUrlQuery(
queryParams.tab !== previousQueryParams.tab;
const action = isDashboardTabChange ? push : replace;
- dispatch(action({ ...location, query: nextQuery }));
+ dispatch(action({ ...location, search: queryToSearch(nextQuery) }));
}
}, [
dashboardId,
diff --git a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
index ae58ffc5678..a3d88e6d173 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.unit.spec.tsx
@@ -115,7 +115,7 @@ describe("useDashboardUrlQuery", () => {
(isEmbedPreview as jest.Mock).mockReturnValue(false);
});
- it("syncs a parameter-value change with replace (not push), writing the parameter slug values into the query", () => {
+ it("syncs a parameter-value change with replace (not push), writing the parameter slug values into the search string", () => {
setup({
parameters: [createMockParameter({ id: "1", slug: "text" })],
parameterValues: { "1": "bar" },
@@ -123,14 +123,12 @@ describe("useDashboardUrlQuery", () => {
expect(replace).toHaveBeenCalledTimes(1);
expect(replace).toHaveBeenCalledWith(
- expect.objectContaining({
- query: expect.objectContaining({ text: "bar" }),
- }),
+ expect.objectContaining({ search: "?text=bar" }),
);
expect(push).not.toHaveBeenCalled();
});
- it("syncs a tab change with push (not replace), writing the new tab slug into the query", () => {
+ it("syncs a tab change with push (not replace), writing the new tab slug into the search string", () => {
const { store } = setup({
tabs: [
{ id: 1, name: "Tab 1" },
@@ -150,9 +148,7 @@ describe("useDashboardUrlQuery", () => {
expect(push).toHaveBeenCalledTimes(1);
expect(push).toHaveBeenCalledWith(
- expect.objectContaining({
- query: expect.objectContaining({ tab: "2-tab-2" }),
- }),
+ expect.objectContaining({ search: "?tab=2-tab-2" }),
);
expect(replace).not.toHaveBeenCalled();
});
@@ -243,9 +239,8 @@ describe("useDashboardUrlQuery", () => {
expect(replace).toHaveBeenCalledTimes(1);
expect(replace).toHaveBeenCalledWith(
- expect.objectContaining({
- query: expect.objectContaining({ objectId: "42", text: "bar" }),
- }),
+ // sorted, as `queryToSearch` writes it
+ expect.objectContaining({ search: "?objectId=42&text=bar" }),
);
});
});
diff --git a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
index 1d0ed2749e3..153a3e1d6fa 100644
--- a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
+++ b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
@@ -22,7 +22,7 @@ import { SearchResultsDropdown } from "metabase/nav/components/search/SearchResu
import { APP_BAR_HEIGHT } from "metabase/nav/constants";
import { useDispatch, useSelector } from "metabase/redux";
import type { LocationDescriptorObject } from "metabase/router";
-import { push, useRouter } from "metabase/router";
+import { push, queryToSearch, useRouter } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Box, Flex, Icon, UnstyledButton, rem } from "metabase/ui";
import { modelToUrl } from "metabase/urls";
@@ -156,7 +156,7 @@ function SearchBar({
};
onChangeLocation({
pathname: "search",
- query,
+ search: queryToSearch(query),
});
}, [onChangeLocation, previousLocation, searchFilters, searchText]);
diff --git a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
index 5f6adc08292..28a64b8c038 100644
--- a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
@@ -106,9 +106,7 @@ describe("Mouse/keyboard interactions", () => {
describe("The 'View and filter all N results' command palette item", () => {
const searchLocation = {
pathname: "/search",
- query: {
- q: "hedgehogs",
- },
+ search: "?q=hedgehogs",
};
const viewResults: Partial<PaletteActionImpl> = {
diff --git a/frontend/src/metabase/palette/components/PaletteResults.tsx b/frontend/src/metabase/palette/components/PaletteResults.tsx
index f27ed1ba8a0..83905864ad1 100644
--- a/frontend/src/metabase/palette/components/PaletteResults.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResults.tsx
@@ -7,7 +7,7 @@ import NoResults from "assets/img/no_results.svg";
import { useShowOtherUsersCollections } from "metabase/common/hooks/use-show-other-users-collections";
import { trackSearchClick } from "metabase/common/search/analytics";
import type { Query } from "metabase/router";
-import { Link } from "metabase/router";
+import { Link, queryToSearch } from "metabase/router";
import {
Flex,
Group,
@@ -57,10 +57,10 @@ const FullSearchCTA = ({
id="search-results-metadata"
to={{
pathname: "search",
- query: {
+ search: queryToSearch({
...locationQuery,
q: debouncedSearchTerm,
- },
+ }),
}}
className={S.viewAndFilterResults}
onClick={onClick}
diff --git a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
index 71a77215764..b84e33e09e0 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
@@ -12,6 +12,7 @@ import { trackSearchClick } from "metabase/common/search/analytics";
import { useGetIcon } from "metabase/hooks/use-icon";
import { useSelector } from "metabase/redux";
import type { Query } from "metabase/router";
+import { queryToSearch } from "metabase/router";
import { getDocsUrl, getSettings } from "metabase/selectors/settings";
import { canAccessSettings, getUserIsAdmin } from "metabase/selectors/user";
import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
@@ -144,10 +145,10 @@ export const useCommandPalette = ({
const searchLocation = {
pathname: "search",
- query: {
+ search: queryToSearch({
...locationQuery,
q: debouncedSearchText,
- },
+ }),
};
if (!isSearchTypeaheadEnabled) {
return [
diff --git a/frontend/src/metabase/palette/utils.ts b/frontend/src/metabase/palette/utils.ts
index e21e962af38..709a8c5123a 100644
--- a/frontend/src/metabase/palette/utils.ts
+++ b/frontend/src/metabase/palette/utils.ts
@@ -113,12 +113,9 @@ export const locationDescriptorToURL = (
if (typeof locationDescriptor === "string") {
return locationDescriptor;
} else {
- const { pathname = "", query = null, hash = null } = locationDescriptor;
- const queryString = query
- ? "?" + new URLSearchParams(query).toString()
- : "";
+ const { pathname = "", search = "", hash = null } = locationDescriptor;
const hashString = hash ? "#" + hash : "";
- return `${pathname}${queryString}${hashString}`;
+ return `${pathname}${search}${hashString}`;
}
};
diff --git a/frontend/src/metabase/palette/utils.unit.spec.ts b/frontend/src/metabase/palette/utils.unit.spec.ts
index 211c998674e..f00aa02411c 100644
--- a/frontend/src/metabase/palette/utils.unit.spec.ts
+++ b/frontend/src/metabase/palette/utils.unit.spec.ts
@@ -264,10 +264,10 @@ describe("command palette utils", () => {
expect(locationDescriptorToURL(locationDescriptor)).toBe(`/a/b/c`);
});
- it("should return the correct URL when query is provided", () => {
+ it("should return the correct URL when search is provided", () => {
const locationDescriptor = {
pathname: "/a/b/c",
- query: { en: "hello", es: "hola" },
+ search: "?en=hello&es=hola",
};
expect(locationDescriptorToURL(locationDescriptor)).toBe(
`/a/b/c?en=hello&es=hola`,
@@ -279,10 +279,10 @@ describe("command palette utils", () => {
expect(locationDescriptorToURL(locationDescriptor)).toBe(`/a/b/c#top`);
});
- it("should return the correct URL with pathname, query, and hash", () => {
+ it("should return the correct URL with pathname, search, and hash", () => {
const locationDescriptor = {
pathname: "/a/b/c",
- query: { en: "hello", es: "hola" },
+ search: "?en=hello&es=hola",
hash: "top",
};
expect(locationDescriptorToURL(locationDescriptor)).toBe(
@@ -293,7 +293,7 @@ describe("command palette utils", () => {
it("should handle empty values appropriately", () => {
const locationDescriptor: LocationDescriptor = {
pathname: "/a/b/c",
- query: undefined,
+ search: undefined,
hash: undefined,
};
expect(locationDescriptorToURL(locationDescriptor)).toBe(`/a/b/c`);
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index b51b1a7488b..1d21dd5a1f4 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -20,7 +20,7 @@ import type {
QueryBuilderUIControls,
} from "metabase/redux/store";
import { fetchTableMetadataAndForeignKeys } from "metabase/redux/tables";
-import type { LocationDescriptorObject } from "metabase/router";
+import type { Location } from "metabase/router";
import { replace } from "metabase/router";
import { FieldSchema } from "metabase/schema";
import { getMetadata } from "metabase/selectors/metadata";
@@ -280,7 +280,7 @@ async function handleQBInit(
params,
isStale,
}: {
- location: LocationDescriptorObject;
+ location: Location;
params: QueryParams;
isStale: () => boolean;
},
@@ -507,7 +507,7 @@ async function handleQBInit(
}
export const initializeQB =
- (location: LocationDescriptorObject, params: QueryParams) =>
+ (location: Location, params: QueryParams) =>
async (dispatch: Dispatch, getState: GetState) => {
const version = ++latestInitializeQBVersion;
const isStale = () => version !== latestInitializeQBVersion;
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
index 06367e90ff0..5be032c0e45 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
@@ -8,8 +8,11 @@ import * as questionActions from "metabase/questions/actions";
import { setErrorPage } from "metabase/redux/app";
import * as metadataActions from "metabase/redux/metadata";
import * as sharedQB from "metabase/redux/query-builder";
-import { createMockState } from "metabase/redux/store/mocks";
-import type { LocationDescriptorObject } from "metabase/router";
+import {
+ createMockLocation,
+ createMockState,
+} from "metabase/redux/store/mocks";
+import type { Location } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import * as Urls from "metabase/urls";
import { defer } from "metabase/utils/promise";
@@ -53,7 +56,7 @@ type TestCard = (Card & DisplayLock) | (UnsavedCard & DisplayLock);
type BaseSetupOpts = {
user?: User | null;
- location: LocationDescriptorObject;
+ location: Location;
params: Record<string, unknown>;
hasDataPermissions?: boolean;
};
@@ -103,15 +106,14 @@ async function baseSetup({
function getLocationForCard(
card: TestCard,
- extra: LocationDescriptorObject = {},
-): LocationDescriptorObject {
+ extra: Partial<Location> = {},
+): Location {
const isSaved = "id" in card;
- return {
+ return createMockLocation({
pathname: isSaved ? Urls.card(card) : Urls.serializedQuestion(card),
hash: !isSaved ? CardLib.serializeCardForUrl(card) : "",
- query: {},
...extra,
- };
+ });
}
function getQueryParamsForCard(
@@ -131,7 +133,7 @@ function getQueryParamsForCard(
type SetupOpts = Omit<BaseSetupOpts, "location" | "params"> & {
card: TestCard;
- location?: LocationDescriptorObject;
+ location?: Location;
params?: Record<string, unknown>;
};
@@ -310,10 +312,11 @@ describe("QB Actions > initializeQB", () => {
it("passes object ID from location query params correctly", async () => {
const location = getLocationForCard(card, {
- query: { objectId: 123 },
+ search: "?objectId=123",
+ query: { objectId: "123" },
});
const { result } = await setup({ card, location });
- expect(result.objectId).toBe(123);
+ expect(result.objectId).toBe("123");
});
it("sets original card id on the card", async () => {
@@ -354,10 +357,11 @@ describe("QB Actions > initializeQB", () => {
it("passes object ID from location query params correctly", async () => {
const location = getLocationForCard(card, {
- query: { objectId: 123 },
+ search: "?objectId=123",
+ query: { objectId: "123" },
});
const { result } = await setup({ card: card, location });
- expect(result.objectId).toBe(123);
+ expect(result.objectId).toBe("123");
});
describe("newb modal", () => {
@@ -411,7 +415,7 @@ describe("QB Actions > initializeQB", () => {
it("throws not found error when opening question with /model URL", async () => {
const { dispatch } = await setup({
card: card,
- location: { pathname: `/model/${card}` },
+ location: createMockLocation({ pathname: `/model/${card}` }),
});
expect(dispatch).toHaveBeenCalledWith(
@@ -851,10 +855,10 @@ describe("QB Actions > initializeQB", () => {
hash = "#?" + hash;
}
- const location: LocationDescriptorObject = {
+ const location = createMockLocation({
pathname: "/question",
hash,
- };
+ });
const params = {
db: db ? String(db) : undefined,
@@ -968,11 +972,7 @@ describe("QB Actions > initializeQB", () => {
opts: Omit<BaseSetupOpts, "location" | "params"> = {},
) {
const slug = `${tableId}-orders`;
- const location: LocationDescriptorObject = {
- pathname: `/table/${slug}`,
- hash: "",
- query: {},
- };
+ const location = createMockLocation({ pathname: `/table/${slug}` });
return baseSetup({ location, params: { slug }, ...opts });
}
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 3508d3b3848..14a7854d506 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -16,6 +16,7 @@ export * from "./use-router";
export * from "./use-search-params";
export * from "./with-route-props";
export { getRawBrowserHistory } from "./v7/blocking-history";
+export { queryToSearch, searchToQuery } from "./v7/location";
export {
createLocationMirror,
type LocationMirror,
diff --git a/frontend/src/metabase/router/router-link.tsx b/frontend/src/metabase/router/router-link.tsx
index 370ba1e6e35..01cb5385128 100644
--- a/frontend/src/metabase/router/router-link.tsx
+++ b/frontend/src/metabase/router/router-link.tsx
@@ -7,7 +7,6 @@ import {
} from "react-router";
import type { RouterLinkProps } from "./types";
-import { queryToSearch } from "./v7/location";
function hrefFor(target: V7LinkProps["to"]): string {
if (typeof target === "string") {
@@ -18,9 +17,8 @@ function hrefFor(target: V7LinkProps["to"]): string {
type V3To = RouterLinkProps["to"];
-// v3 descriptors carry the query as a `query` object and `state` inline; v7 uses
-// a `search` string and a separate `state` prop. Translate so existing call sites
-// keep working on v7.
+// v3 descriptors carry `state` inline; v7 takes it as a separate prop. Translate
+// so existing call sites keep working on v7.
/**
* v3 resolved a bare path against the root, so call sites write `to="reference"`
* meaning `/reference`. v7 resolves it against the current route instead, which
@@ -48,14 +46,11 @@ function toV7Target(to: V3To): { to: V7LinkProps["to"]; state?: unknown } {
// v3's function form of `to` has no v7 analog and is not used in the app.
return { to: "" };
}
- const { pathname, search, hash, query, state } = to;
- // `query` wins over `search`, matching history@3: call sites build
- // `{ ...location, query }`, where the spread carries a stale `search`.
- const searchString = query ? queryToSearch(query) : search;
+ const { pathname, search, hash, state } = to;
return {
to: {
pathname: pathname == null ? "" : toRootRelative(pathname),
- search: searchString,
+ search,
hash,
},
state,
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 02b66366de2..2b093b49f15 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -69,27 +69,19 @@ export interface Location<Q = DefaultQuery> {
}
/**
- * The loose query accepted when building a navigation target, where values may
- * still be numbers or other primitives before serialization. Mirrors history@3's
- * `QueryLike`, distinct from the parsed `DefaultQuery` a `Location` carries.
- */
-type QueryLike = Record<string, any>;
-
-/**
- * A location to navigate to, as an object. Mirrors history@3's
- * `LocationDescriptorObject`; the string form is `LocationDescriptor`.
+ * A location to navigate to, as an object. Carries the query as a `search`
+ * string, the only form v7 reads; call sites that hold a query object serialize
+ * it with `queryToSearch` first.
*/
export interface LocationDescriptorObject {
pathname?: string;
search?: string;
- query?: QueryLike;
hash?: string;
state?: LocationState;
}
/**
* A location to navigate to: either a path string or a descriptor object.
- * Mirrors history@3's `LocationDescriptor`.
*/
export type LocationDescriptor = LocationDescriptorObject | string;
diff --git a/frontend/src/metabase/router/v7/location.ts b/frontend/src/metabase/router/v7/location.ts
index e8cc12f9171..3ffdc2f8741 100644
--- a/frontend/src/metabase/router/v7/location.ts
+++ b/frontend/src/metabase/router/v7/location.ts
@@ -20,9 +20,9 @@ export function searchToQuery(
}
/**
- * Serialize v3's `location.query` object back into a search string, the only form
- * v7 understands. Repeated values become repeated keys, mirroring what
- * `searchToQuery` parses. Returns `""` for an empty query.
+ * Serialize a query object into the `search` string a navigation target carries.
+ * Repeated values become repeated keys, mirroring what `searchToQuery` parses.
+ * Returns `""` for an empty query.
*
* Keys are sorted, because history@3 stringified the query with `query-string`,
* which sorts by default. Call sites build the query from an object whose key
diff --git a/frontend/src/metabase/router/v7/location.unit.spec.ts b/frontend/src/metabase/router/v7/location.unit.spec.ts
new file mode 100644
index 00000000000..0819a03e855
--- /dev/null
+++ b/frontend/src/metabase/router/v7/location.unit.spec.ts
@@ -0,0 +1,57 @@
+import { queryToSearch, searchToQuery } from "./location";
+
+// Call sites hold a query object and navigation targets carry a `search` string,
+// so this is what stands between the two. Its encoding is not plain
+// `URLSearchParams.toString()`, and the differences are user visible.
+describe("queryToSearch", () => {
+ it("repeats a key for array values", () => {
+ expect(queryToSearch({ id: ["1", "2"] })).toBe("?id=1&id=2");
+ });
+
+ it("skips null and undefined values", () => {
+ expect(queryToSearch({ a: "1", b: null, c: undefined })).toBe("?a=1");
+ });
+
+ it("returns an empty string for an empty query", () => {
+ expect(queryToSearch({})).toBe("");
+ });
+
+ // history@3 stringified with `query-string`, which sorts keys. The URL is user
+ // visible and asserted against, so the order must not follow insertion.
+ it("sorts keys regardless of insertion order", () => {
+ expect(queryToSearch({ state: "AK", city: "" })).toBe("?city=&state=AK");
+ expect(queryToSearch({ city: "", state: "AK" })).toBe("?city=&state=AK");
+ });
+
+ // history@3 wrote a space as `+` but left `~` literal, and both show up in URLs
+ // the app asserts on (a date filter reads `next30days~`).
+ it("writes a space as `+` and leaves `~` literal", () => {
+ expect(queryToSearch({ date_filter: "next30days~" })).toBe(
+ "?date_filter=next30days~",
+ );
+ expect(queryToSearch({ task: "field values scanning" })).toBe(
+ "?task=field+values+scanning",
+ );
+ });
+
+ it("still escapes characters that would break the query string", () => {
+ expect(queryToSearch({ q: "a&b=c" })).toBe("?q=a%26b%3Dc");
+ });
+});
+
+describe("searchToQuery", () => {
+ it("collects a repeated key into an array", () => {
+ expect(searchToQuery("?id=1&id=2")).toEqual({ id: ["1", "2"] });
+ });
+
+ it("keeps a valueless key as an empty string", () => {
+ expect(searchToQuery("?city=&state=AK")).toEqual({
+ city: "",
+ state: "AK",
+ });
+ });
+
+ it("returns an empty query for an empty search", () => {
+ expect(searchToQuery("")).toEqual({});
+ });
+});
diff --git a/frontend/src/metabase/router/v7/navigator.ts b/frontend/src/metabase/router/v7/navigator.ts
index b283759e2eb..6201eec1aff 100644
--- a/frontend/src/metabase/router/v7/navigator.ts
+++ b/frontend/src/metabase/router/v7/navigator.ts
@@ -3,8 +3,6 @@ import type { NavigateFunction, NavigateOptions, To } from "react-router";
import type { RouterNavigator } from "../middleware";
import type { Location as HistoryLocation, LocationDescriptor } from "../types";
-import { queryToSearch } from "./location";
-
/**
* The live v7 `navigate`, registered by `V7RouterBridge` once the router mounts.
* The redux navigator adapter is built at store creation, before the router
@@ -61,7 +59,7 @@ export function notifyLocationListeners(location: HistoryLocation): void {
}
/**
- * Turn a v3 `LocationDescriptor` (string or `{ pathname, search, hash, state }`)
+ * Turn a `LocationDescriptor` (string or `{ pathname, search, hash, state }`)
* into v7 `navigate(to, options)` arguments. Shared by the imperative-router
* shim and the redux navigator so both map descriptors the same way.
*/
@@ -72,18 +70,10 @@ export function toNavigateArgs(
if (typeof location === "string") {
return [location, options];
}
- // v3 descriptors carry the query as a `query` object, which v7 does not read, so
- // serialize it into the search string. Dropping it silently loses params (e.g.
- // the dashboard's tab and filter slugs). `query` wins over `search`, matching
- // history@3's `useQueries`: callers build `{ ...location, query }`, so the
- // spread's stale `search` must not shadow the query they just set.
- const search = location.query
- ? queryToSearch(location.query)
- : location.search;
return [
{
pathname: location.pathname,
- search,
+ search: location.search,
hash: location.hash,
},
{ ...options, state: location.state },
diff --git a/frontend/src/metabase/router/v7/navigator.unit.spec.ts b/frontend/src/metabase/router/v7/navigator.unit.spec.ts
index 68908380641..a1523544d2c 100644
--- a/frontend/src/metabase/router/v7/navigator.unit.spec.ts
+++ b/frontend/src/metabase/router/v7/navigator.unit.spec.ts
@@ -1,42 +1,19 @@
-import { queryToSearch } from "./location";
import { createV7Navigator, setV7Navigate, toNavigateArgs } from "./navigator";
-// v3 location descriptors carry the query as an object. v7 only reads `search`,
-// so the navigator has to serialize it; dropping it silently loses params (the
-// dashboard's tab and filter slugs went missing this way).
describe("toNavigateArgs", () => {
- it("serializes a v3 `query` object into the search string", () => {
+ it("maps a descriptor's URL parts onto a v7 target", () => {
const [to] = toNavigateArgs({
pathname: "/dashboard/1",
- query: { tab: "2-tab-two", "filter-date": "2024-01-01" },
+ search: "?filter-date=2024-01-01&tab=2-tab-two",
});
expect(to).toEqual({
pathname: "/dashboard/1",
- // sorted, as history@3 stringified it
search: "?filter-date=2024-01-01&tab=2-tab-two",
hash: undefined,
});
});
- // Call sites build `{ ...location, query }`, so the spread carries the previous
- // `search`. The query they just set has to win, as it does on history@3.
- it("prefers `query` over a stale search carried by a spread location", () => {
- const [to] = toNavigateArgs({
- pathname: "/dashboard/1",
- search: "",
- query: { tab: "2-tab-two" },
- });
-
- expect(to).toMatchObject({ search: "?tab=2-tab-two" });
- });
-
- it("falls back to `search` when there is no `query`", () => {
- const [to] = toNavigateArgs({ pathname: "/dashboard/1", search: "?a=1" });
-
- expect(to).toMatchObject({ search: "?a=1" });
- });
-
it("passes a string target through untouched", () => {
expect(toNavigateArgs("/dashboard/1?tab=2")).toEqual([
"/dashboard/1?tab=2",
@@ -95,39 +72,3 @@ describe("createV7Navigator pre-mount buffering", () => {
expect(navigate).not.toHaveBeenCalled();
});
});
-
-describe("queryToSearch", () => {
- it("repeats a key for array values", () => {
- expect(queryToSearch({ id: ["1", "2"] })).toBe("?id=1&id=2");
- });
-
- it("skips null and undefined values", () => {
- expect(queryToSearch({ a: "1", b: null, c: undefined })).toBe("?a=1");
- });
-
- it("returns an empty string for an empty query", () => {
- expect(queryToSearch({})).toBe("");
- });
-
- // history@3 stringified with `query-string`, which sorts keys. The URL is user
- // visible and asserted against, so the order must not follow insertion.
- it("sorts keys regardless of insertion order", () => {
- expect(queryToSearch({ state: "AK", city: "" })).toBe("?city=&state=AK");
- expect(queryToSearch({ city: "", state: "AK" })).toBe("?city=&state=AK");
- });
-
- // history@3 wrote a space as `+` but left `~` literal, and both show up in URLs
- // the app asserts on (a date filter reads `next30days~`).
- it("writes a space as `+` and leaves `~` literal", () => {
- expect(queryToSearch({ date_filter: "next30days~" })).toBe(
- "?date_filter=next30days~",
- );
- expect(queryToSearch({ task: "field values scanning" })).toBe(
- "?task=field+values+scanning",
- );
- });
-
- it("still escapes characters that would break the query string", () => {
- expect(queryToSearch({ q: "a&b=c" })).toBe("?q=a%26b%3Dc");
- });
-});
diff --git a/frontend/src/metabase/search/containers/SearchApp.tsx b/frontend/src/metabase/search/containers/SearchApp.tsx
index a1b57ded4f3..f1a1a2b4f7b 100644
--- a/frontend/src/metabase/search/containers/SearchApp.tsx
+++ b/frontend/src/metabase/search/containers/SearchApp.tsx
@@ -23,7 +23,7 @@ import type {
import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/redux";
import type { LocationDescriptorObject } from "metabase/router";
-import { push, useRouter } from "metabase/router";
+import { push, queryToSearch, useRouter } from "metabase/router";
import { SearchSidebar } from "metabase/search/components/SearchSidebar";
import {
SearchBody,
@@ -85,7 +85,7 @@ export function SearchApp() {
(newFilters: URLSearchFilterQueryParams) => {
onChangeLocation({
pathname: "search",
- query: { q: searchText.trim(), ...newFilters },
+ search: queryToSearch({ q: searchText.trim(), ...newFilters }),
});
},
[onChangeLocation, searchText],
@@ -94,11 +94,11 @@ export function SearchApp() {
const advancePage = (howMany = 1) => {
onChangeLocation({
pathname: "search",
- query: {
+ search: queryToSearch({
q: searchText.trim(),
...searchFilters,
page: String(page + howMany),
- },
+ }),
});
};
diff --git a/frontend/src/metabase/visualizations/lib/action.unit.spec.ts b/frontend/src/metabase/visualizations/lib/action.unit.spec.ts
index dcff29ac847..6e368fd0db2 100644
--- a/frontend/src/metabase/visualizations/lib/action.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/lib/action.unit.spec.ts
@@ -34,7 +34,6 @@ describe("performAction", () => {
{
hash: "",
pathname: "/auto/dashboard/adhoc/123Abc",
- query: {},
search: "",
},
],
@@ -98,7 +97,6 @@ describe("performAction", () => {
{
hash: "",
pathname: url,
- query: {},
search: "",
},
],
@@ -137,7 +135,6 @@ describe("performAction", () => {
{
hash: "",
pathname: "/" + url,
- query: {},
search: "",
},
],
@@ -177,7 +174,6 @@ describe("performAction", () => {
{
hash: "",
pathname: "/auto/dashboard/adhoc/123Abc",
- query: {},
search: "",
},
],
@@ -217,7 +213,6 @@ describe("performAction", () => {
hash: "",
pathname:
"/invalid_protocol://localhost/metabase/auto/dashboard/adhoc/123Abc",
- query: {},
search: "",
},
],
diff --git a/frontend/src/metabase/visualizations/lib/open-url.ts b/frontend/src/metabase/visualizations/lib/open-url.ts
index 32e20927f69..9999bad42c7 100644
--- a/frontend/src/metabase/visualizations/lib/open-url.ts
+++ b/frontend/src/metabase/visualizations/lib/open-url.ts
@@ -1,11 +1,14 @@
-import querystring from "querystring";
-
import { handleLinkSdkPlugin } from "embedding-sdk-shared/lib/sdk-global-plugins";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import type {
LocationDescriptor,
LocationDescriptorObject,
} from "metabase/router";
+// Imported from the module rather than the `metabase/router` barrel on purpose.
+// This file is reachable from the static-viz entry, which runs inside GraalVM,
+// and the barrel pulls react-router and the redux router middleware in with it:
+// ~1MB on a bundle with a 3.5MB budget. `v7/location` has only type imports.
+import { queryToSearch, searchToQuery } from "metabase/router/v7/location";
import {
clickLink,
getPathnameWithoutSubPath,
@@ -165,11 +168,13 @@ function isAbsoluteUrl(url: string): boolean {
function getLocation(url: string): LocationDescriptor {
try {
const { pathname, search, hash } = new URL(url, window.location.origin);
- const query = querystring.parse(search.substring(1));
return {
pathname: getPathnameWithoutSubPath(pathname),
- search,
- query,
+ // Round-tripped rather than passed through, because a click behavior's
+ // custom destination is a hand-written URL whose params land in whatever
+ // order the author typed them, and the resulting URL is asserted against
+ // with the keys sorted.
+ search: queryToSearch(searchToQuery(search)),
hash,
};
} catch {