Skip to content

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

Move the location.query readers to search params (#78670)

Romeo Van Snick8594eb45c730
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx
index 5fb72d81bcf..0a6dc98a402 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationStatsPage/ConversationStatsPage.unit.spec.tsx
@@ -11,6 +11,7 @@ import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
+import { parseSearchQuery } from "metabase/utils/browser";
import type { ClickObject } from "metabase-lib";
import type { Dataset, RawSeries, RowValue } from "metabase-types/api";
import {
@@ -307,7 +308,9 @@ describe("ConversationStatsPage", () => {
expect(await screen.findByText(title)).toBeInTheDocument();
}
await waitFor(() => {
- expect(history?.getCurrentLocation().query).toMatchObject({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toMatchObject({
metric,
});
});
@@ -394,7 +397,9 @@ describe("ConversationStatsPage", () => {
);
await waitFor(() => {
- expect(history?.getCurrentLocation().query).toMatchObject({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toMatchObject({
tenant: String(BOBBY_TENANT.id),
});
});
@@ -417,7 +422,9 @@ describe("ConversationStatsPage", () => {
);
await waitFor(() => {
- expect(history?.getCurrentLocation().query).toMatchObject({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toMatchObject({
user: String(ROBERT.id),
});
});
@@ -433,7 +440,9 @@ describe("ConversationStatsPage", () => {
await selectFilterOption("conversation-filters-group-select", "data");
await waitFor(() => {
- expect(history?.getCurrentLocation().query).toMatchObject({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toMatchObject({
group: String(DATA_GROUP.id),
});
});
@@ -483,7 +492,9 @@ describe("ConversationStatsPage", () => {
await drillInto(chart, label);
expect(history?.getCurrentLocation().pathname).toBe(CONVERSATIONS_PATH);
- expect(history?.getCurrentLocation().query).toEqual(query);
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual(query);
},
);
@@ -494,7 +505,9 @@ describe("ConversationStatsPage", () => {
await drillInto("Users with most conversations", "Bobby Tables");
- expect(history?.getCurrentLocation().query).toEqual({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({
date: "past6days~",
group: String(ADMIN_GROUP.id),
user: String(BOBBY.id),
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.unit.spec.tsx
index 25f775dfe58..63bcff86539 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/components/ConversationsPage/ConversationsPage.unit.spec.tsx
@@ -12,6 +12,7 @@ import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
+import { parseSearchQuery } from "metabase/utils/browser";
import {
createMockTokenFeatures,
createMockUser,
@@ -265,7 +266,9 @@ describe("ConversationsPage", () => {
await assertRequestedWithParams({ user_id: String(ROBERT.id) });
await waitFor(() => {
- expect(history?.getCurrentLocation().query).toMatchObject({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toMatchObject({
user: String(ROBERT.id),
});
});
@@ -305,7 +308,9 @@ describe("ConversationsPage", () => {
await assertRequestedWithParams({ tenant_id: String(ROBERT_TENANT.id) });
await waitFor(() => {
- expect(history?.getCurrentLocation().query).toMatchObject({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toMatchObject({
tenant: String(ROBERT_TENANT.id),
});
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
index 5866cb9fcb5..8844c3eacac 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/LibraryPage/hooks/useLibraryTreeTableInstance.tsx
@@ -9,7 +9,7 @@ import { useBuildSnippetTree } from "metabase/data-studio/common/hooks/use-build
import type { TreeItem } from "metabase/data-studio/common/types";
import { isEmptyStateData } from "metabase/data-studio/common/utils";
import { useSelector } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { useSearchParams } from "metabase/router";
import {
EntityNameCell,
Flex,
@@ -44,21 +44,20 @@ export function useLibraryTreeTableInstance({
searchQuery,
onPublishTableClick,
}: Params) {
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
const isRemoteSyncReadOnly = useSelector(getIsRemoteSyncReadOnly);
const expandedIdsFromUrl = useMemo(() => {
- const rawIds = location.query?.expandedId;
- if (!rawIds) {
+ const ids = searchParams.getAll("expandedId");
+ if (ids.length === 0) {
return null;
}
- const ids = Array.isArray(rawIds) ? rawIds : [rawIds];
// Unjustified type cast. FIXME
return _.object(
ids.map((id) => [`collection:${id}`, true]),
) as ExpandedState;
- }, [location.query?.expandedId]);
+ }, [searchParams]);
const { libraryCollection, tableCollection, metricCollection } =
useLibraryCollections(collections);
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/DependencyGraphPage.tsx b/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/DependencyGraphPage.tsx
index 95c42971d38..0585c0308eb 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/DependencyGraphPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/DependencyGraphPage.tsx
@@ -3,7 +3,7 @@ import { useContext } from "react";
import { skipToken } from "metabase/api";
import { AppSwitcher } from "metabase/nav/components/AppSwitcher";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
-import { useRouter } from "metabase/router";
+import { useSearchParams } from "metabase/router";
import { Stack } from "metabase/ui";
import * as Urls from "metabase/urls";
import { useGetDependencyGraphQuery } from "metabase-enterprise/api";
@@ -14,14 +14,12 @@ import { isSameNode } from "../../utils";
import S from "./DependencyGraphPage.module.css";
import { parseDependencyEntry } from "./utils";
-export type DependencyGraphPageQuery = {
- id?: string;
- type?: string;
-};
-
export function DependencyGraphPage() {
- const { location } = useRouter();
- const entry = parseDependencyEntry(location.query?.id, location.query.type);
+ const [searchParams] = useSearchParams();
+ const entry = parseDependencyEntry(
+ searchParams.get("id") ?? undefined,
+ searchParams.get("type") ?? undefined,
+ );
const { defaultEntry, baseUrl } = useContext(
PLUGIN_DEPENDENCIES.DependencyGraphPageContext,
);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx
index 6f4745b987a..64c6329b263 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.tsx
@@ -37,10 +37,11 @@ function DependencyDiagnosticsPage({ mode }: DependencyDiagnosticsPageProps) {
});
const params = useMemo(() => {
- return isEmptyParams(location)
+ const searchParams = new URLSearchParams(location.search);
+ return isEmptyParams(searchParams)
? parseUserParams(rawLastUsedParams)
- : parseUrlParams(location);
- }, [location, rawLastUsedParams]);
+ : parseUrlParams(searchParams);
+ }, [location.search, rawLastUsedParams]);
const handleParamsChange = (
params: Urls.DependencyDiagnosticsParams,
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.unit.spec.tsx
index 9dbff6e6bfa..cc8bf1db412 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/DependencyDiagnosticsPage.unit.spec.tsx
@@ -14,6 +14,7 @@ import {
import { MonitorContent } from "metabase/monitor/components/MonitorLayout/MonitorContent";
import { Route } from "metabase/router";
import type * as Urls from "metabase/urls";
+import { parseSearchQuery } from "metabase/utils/browser";
import type { DependencyDiagnosticsMode } from "metabase-enterprise/monitor/dependency-diagnostics/components/types";
import type {
DependencyDiagnosticsUserParams,
@@ -159,7 +160,9 @@ describe("DependencyDiagnosticsPage", () => {
const popover = await getFilterPopover();
await userEvent.click(getTypeCheckbox(popover, "Table"));
- expect(history?.getCurrentLocation().query).toEqual({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({
"group-types": ["question", "model"],
});
});
@@ -176,7 +179,9 @@ describe("DependencyDiagnosticsPage", () => {
const popover = await getFilterPopover();
await userEvent.click(getTypeCheckbox(popover, "Model"));
- expect(history?.getCurrentLocation().query).toEqual({});
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({});
});
it("should set the include-personal-collections parameter when it is unchecked", async () => {
@@ -194,7 +199,9 @@ describe("DependencyDiagnosticsPage", () => {
});
await userEvent.click(checkbox);
- expect(history?.getCurrentLocation().query).toEqual({
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({
"include-personal-collections": "false",
});
});
@@ -214,7 +221,9 @@ describe("DependencyDiagnosticsPage", () => {
});
await userEvent.click(checkbox);
- expect(history?.getCurrentLocation().query).toEqual({});
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({});
});
it("should set the page parameter when navigating to the next page and it is not the first page", async () => {
@@ -228,7 +237,9 @@ describe("DependencyDiagnosticsPage", () => {
await waitForListToLoad();
await userEvent.click(screen.getByLabelText("Next page"));
- expect(history?.getCurrentLocation().query).toEqual({ page: "1" });
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({ page: "1" });
});
it("should set the page parameter when navigating to the previous page and it is not the first page", async () => {
@@ -242,7 +253,9 @@ describe("DependencyDiagnosticsPage", () => {
await waitForListToLoad();
await userEvent.click(screen.getByLabelText("Previous page"));
- expect(history?.getCurrentLocation().query).toEqual({ page: "1" });
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({ page: "1" });
});
it("should not set the page parameter when it is the first page", async () => {
@@ -256,7 +269,9 @@ describe("DependencyDiagnosticsPage", () => {
await waitForListToLoad();
await userEvent.click(screen.getByLabelText("Previous page"));
- expect(history?.getCurrentLocation().query).toEqual({});
+ expect(
+ parseSearchQuery(history?.getCurrentLocation().search ?? ""),
+ ).toEqual({});
});
});
@@ -334,7 +349,7 @@ describe("DependencyDiagnosticsPage", () => {
await waitForListToLoad();
const currentLocation = history?.getCurrentLocation();
- expect(currentLocation?.query).toEqual({
+ expect(parseSearchQuery(currentLocation?.search ?? "")).toEqual({
"group-types": ["table", "question"],
});
});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/utils.ts b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/utils.ts
index fc2e7933e4f..a3791384eeb 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/dependency-diagnostics/pages/utils.ts
@@ -1,4 +1,3 @@
-import type { Location } from "metabase/router";
import * as Urls from "metabase/urls";
import type { DependencyDiagnosticsMode } from "metabase-enterprise/monitor/dependency-diagnostics/components/types";
import {
@@ -18,28 +17,26 @@ export function getPageUrl(
}
export function parseUrlParams(
- location: Location,
+ searchParams: URLSearchParams,
): Urls.DependencyDiagnosticsParams {
- const {
- page,
- query,
- "group-types": groupTypes,
- "include-personal-collections": includePersonalCollections,
- "sort-column": sortColumn,
- "sort-direction": sortDirection,
- } = location.query;
-
return {
- page: Urls.parseNumberParam(page),
- query: Urls.parseStringParam(query),
- groupTypes: Urls.parseListParam(groupTypes, (item) =>
- Urls.parseEnumParam(item, DEPENDENCY_GROUP_TYPES),
+ page: Urls.parseNumberParam(searchParams.get("page")),
+ query: Urls.parseStringParam(searchParams.get("query")),
+ groupTypes: Urls.parseListParam(
+ searchParams.getAll("group-types"),
+ (item) => Urls.parseEnumParam(item, DEPENDENCY_GROUP_TYPES),
),
includePersonalCollections: Urls.parseBooleanParam(
- includePersonalCollections,
+ searchParams.get("include-personal-collections"),
+ ),
+ sortColumn: Urls.parseEnumParam(
+ searchParams.get("sort-column"),
+ DEPENDENCY_SORT_COLUMNS,
+ ),
+ sortDirection: Urls.parseEnumParam(
+ searchParams.get("sort-direction"),
+ SORT_DIRECTIONS,
),
- sortColumn: Urls.parseEnumParam(sortColumn, DEPENDENCY_SORT_COLUMNS),
- sortDirection: Urls.parseEnumParam(sortDirection, SORT_DIRECTIONS),
};
}
@@ -70,6 +67,6 @@ export function getUserParams(
};
}
-export function isEmptyParams(location: Location): boolean {
- return Object.values(location.query).every((value) => value == null);
+export function isEmptyParams(searchParams: URLSearchParams): boolean {
+ return [...searchParams.keys()].length === 0;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/SchemaViewerPage.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/SchemaViewerPage.tsx
index 4917f53efba..3d5b8b96dbc 100644
--- a/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/SchemaViewerPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/pages/SchemaViewerPage/SchemaViewerPage.tsx
@@ -3,7 +3,7 @@ import { t } from "ttag";
import { skipToken } from "metabase/api";
import { usePageTitle } from "metabase/hooks/use-page-title";
-import { useRouter } from "metabase/router";
+import { useSearchParams } from "metabase/router";
import { Stack } from "metabase/ui";
import { getSchemaViewerParams } from "metabase/urls";
import { useGetErdQuery } from "metabase-enterprise/api";
@@ -15,23 +15,22 @@ import { useSchemaPreferencesStore } from "../../components/SchemaViewer/hooks/u
import { useRedirectToLastDatabase } from "./useRedirectToLastDatabase";
export function SchemaViewerPage() {
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
usePageTitle(t`Schema viewer`);
- const rawDatabaseId = location?.query?.["database-id"];
- const rawTableIds = location?.query?.["table-ids"];
- const schema = location?.query?.schema;
+ const rawDatabaseId = searchParams.get("database-id");
+ const schema = searchParams.get("schema") ?? undefined;
+ // Joined rather than kept as the array `getAll` returns, so the memo below has
+ // a stable dependency across renders.
+ const rawTableIds = searchParams.getAll("table-ids").join(",");
const databaseId: DatabaseId | undefined =
rawDatabaseId != null ? Number(rawDatabaseId) : undefined;
- const tableIds: ConcreteTableId[] | undefined = useMemo(() => {
- if (rawTableIds == null) {
- return undefined;
- }
- const ids = Array.isArray(rawTableIds) ? rawTableIds : [rawTableIds];
- return ids.map(Number);
- }, [rawTableIds]);
+ const tableIds: ConcreteTableId[] | undefined = useMemo(
+ () => (rawTableIds === "" ? undefined : rawTableIds.split(",").map(Number)),
+ [rawTableIds],
+ );
useRedirectToLastDatabase({ databaseId, schema });
diff --git a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.tsx b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.tsx
index 9331cc81c26..1dd74d9f302 100644
--- a/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/security_center/components/SecurityCenterPage/SecurityCenterPage.tsx
@@ -6,7 +6,7 @@ import { useSyncSecurityAdvisoriesMutation } from "metabase/api";
import { EmptyState } from "metabase/common/components/EmptyState";
import { useSetting, useToast } from "metabase/common/hooks";
import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";
-import { useRouter } from "metabase/router";
+import { useSearchParams } from "metabase/router";
import {
Box,
Button,
@@ -41,7 +41,7 @@ const DEFAULT_FILTER: AdvisoryFilter = {
const MAX_POLL_COUNT = 30;
export function SecurityCenterPage() {
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
const [isPolling, setIsPolling] = useState(false);
const {
data: advisories,
@@ -54,7 +54,7 @@ export function SecurityCenterPage() {
useSyncSecurityAdvisoriesMutation();
const [filter, setFilter] = useState<AdvisoryFilter>(DEFAULT_FILTER);
const [settingsOpen, setSettingsOpen] = useState(
- () => location.query?.open === "notifications",
+ () => searchParams.get("open") === "notifications",
);
const notificationConfig = useNotificationConfigState();
const version = useSetting("version");
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-adhoc-table-query.ts b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-adhoc-table-query.ts
index f65a4641fbe..18e2034c5f7 100644
--- a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-adhoc-table-query.ts
+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-adhoc-table-query.ts
@@ -13,7 +13,7 @@ import type { OpaqueDatasetQuery } from "metabase-types/api";
type UseAdHocTableQueryProps = {
tableId: number;
databaseId: number;
- location: Location<{ query?: string }>;
+ location: Location;
};
export const useAdHocTableQuery = ({
@@ -24,13 +24,10 @@ export const useAdHocTableQuery = ({
const metadata = useSelector(getMetadata);
const dispatch = useDispatch();
- const queryParam = useMemo(
- () =>
- location.query?.query
- ? deserializeQueryFromUrl(location.query.query)
- : null,
- [location.query.query],
- );
+ const queryParam = useMemo(() => {
+ const query = new URLSearchParams(location.search).get("query");
+ return query ? deserializeQueryFromUrl(query) : null;
+ }, [location.search]);
const metadataProvider = useMemo(
() => Lib.metadataProvider(databaseId, metadata),
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-edit-table-data.ts b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-edit-table-data.ts
index 81b78f29476..a13491937b9 100644
--- a/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-edit-table-data.ts
+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/table-edit/use-edit-table-data.ts
@@ -11,7 +11,7 @@ import { useAdHocTableQuery } from "./use-adhoc-table-query";
type Props = {
tableId: number;
databaseId: number;
- location: Location<{ query?: string }>;
+ location: Location;
};
export type TableDataGetColumnSortDirection = (
diff --git a/frontend/src/metabase/account/notifications/containers/ArchiveAlertModal/DeleteAlertModal.tsx b/frontend/src/metabase/account/notifications/containers/ArchiveAlertModal/DeleteAlertModal.tsx
index a23dcf4ad3b..f93146f0487 100644
--- a/frontend/src/metabase/account/notifications/containers/ArchiveAlertModal/DeleteAlertModal.tsx
+++ b/frontend/src/metabase/account/notifications/containers/ArchiveAlertModal/DeleteAlertModal.tsx
@@ -8,7 +8,7 @@ import {
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useToast } from "metabase/common/hooks/use-toast";
import { DeleteAlertConfirmModal } from "metabase/notifications/modals/DeleteAlertConfirmModal";
-import type { Location } from "metabase/router";
+import { useSearchParams } from "metabase/router";
import type { Notification } from "metabase-types/api";
import { getAlertId } from "../../selectors";
@@ -17,20 +17,19 @@ type DeleteAlertModalProps = {
params: {
alertId?: string;
};
- location: Location<{ unsubscribed?: boolean }>;
onClose: () => void;
};
export const DeleteAlertModal = ({
params,
- location,
onClose,
}: DeleteAlertModalProps) => {
const id = getAlertId(params?.alertId);
const [sendToast] = useToast();
+ const [searchParams] = useSearchParams();
- const hasUnsubscribed = location.query?.unsubscribed;
+ const hasUnsubscribed = Boolean(searchParams.get("unsubscribed"));
const {
data: notification,
diff --git a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx
index 41fc08ced2c..94e91ad2355 100644
--- a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx
+++ b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx
@@ -6,7 +6,7 @@ import {
} from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useSelector } from "metabase/redux";
-import type { Location } from "metabase/router";
+import { useSearchParams } from "metabase/router";
import { getUser } from "metabase/selectors/user";
import { ArchiveNotificationModal } from "../../components/ArchiveModal";
@@ -14,17 +14,13 @@ import { getPulseId } from "../../selectors";
type ArchivePulseModalProps = {
params: { pulseId?: string };
- location: Location;
onClose: () => void;
};
-export function ArchivePulseModal({
- params,
- location,
- onClose,
-}: ArchivePulseModalProps) {
+export function ArchivePulseModal({ params, onClose }: ArchivePulseModalProps) {
const pulseId = getPulseId({ params });
const user = useSelector(getUser);
+ const [searchParams] = useSearchParams();
const {
data: pulse,
@@ -50,7 +46,7 @@ export function ArchivePulseModal({
item={pulse}
type="pulse"
user={user}
- hasUnsubscribed={Boolean(location.query?.unsubscribed)}
+ hasUnsubscribed={Boolean(searchParams.get("unsubscribed"))}
onArchive={handleArchive}
onClose={onClose}
/>
diff --git a/frontend/src/metabase/admin/ai/AISettingsPage.tsx b/frontend/src/metabase/admin/ai/AISettingsPage.tsx
index 18bc81546f5..6a8d1558dd0 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 { queryToSearch, useRouter } from "metabase/router";
+import { queryToSearch, useSearchParams } from "metabase/router";
import { Divider, Flex, Stack, Switch, Tabs } from "metabase/ui";
import { AIProviderSettingsSection } from "./AIProviderSettingsSection";
@@ -38,9 +38,7 @@ const METABOT_SETTINGS_PATH = "/admin/metabot";
const METABOT_ID_QUERY_PARAM = "metabot_id";
export function AISettingsPage() {
- const {
- location: { query },
- } = useRouter();
+ const [searchParams] = useSearchParams();
const isConfigured = !!useSetting("llm-metabot-configured?");
const hasEmbedding =
@@ -54,7 +52,7 @@ export function AISettingsPage() {
const areAiFeaturesEnabled = aiFeaturesEnabledValue !== false;
const selectedMetabotId = getSelectedMetabotId(
- query?.[METABOT_ID_QUERY_PARAM],
+ searchParams.get(METABOT_ID_QUERY_PARAM),
);
const handleAiFeaturesEnabledChange = async (checked: boolean) => {
@@ -265,7 +263,7 @@ function DisabledSection({
);
}
-function getSelectedMetabotId(metabotId: string | undefined): MetabotTabId {
+function getSelectedMetabotId(metabotId: string | null): MetabotTabId {
if (metabotId === String(FIXED_METABOT_IDS.EMBEDDED)) {
return FIXED_METABOT_IDS.EMBEDDED;
}
diff --git a/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx
index 212461aa35d..d9ce3637423 100644
--- a/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/ai/AISettingsPage.unit.spec.tsx
@@ -288,7 +288,7 @@ describe("AISettingsPage", () => {
expect(history?.getCurrentLocation()).toMatchObject({
pathname: "/admin/metabot",
- query: { metabot_id: String(FIXED_METABOT_IDS.EMBEDDED) },
+ search: `?metabot_id=${FIXED_METABOT_IDS.EMBEDDED}`,
hash: "",
});
});
diff --git a/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx b/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx
index dceb20d3026..fab4c6a87b6 100644
--- a/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx
+++ b/frontend/src/metabase/admin/datamodel/hoc/FilteredToUrlTable.tsx
@@ -13,20 +13,14 @@ import { getMetadata } from "metabase/selectors/metadata";
import { Icon } from "metabase/ui";
import type { ConcreteTableId, Segment } from "metabase-types/api";
-type LocationWithQuery = Location<{
- table?: string;
-}>;
-
type FilteredToUrlTableInnerProps = {
- location: LocationWithQuery;
+ location: Location;
push: (location: LocationDescriptorObject) => void;
segments: Segment[];
};
-function getTableIdFromLocation(
- location: LocationWithQuery,
-): ConcreteTableId | null {
- const tableId = location.query?.table;
+function getTableIdFromLocation(location: Location): ConcreteTableId | null {
+ const tableId = new URLSearchParams(location.search).get("table");
return tableId != null ? parseInt(tableId, 10) : null;
}
diff --git a/frontend/src/metabase/auth/components/ForgotPassword/ForgotPassword.tsx b/frontend/src/metabase/auth/components/ForgotPassword/ForgotPassword.tsx
index 09b706d9c34..9c183ece70f 100644
--- a/frontend/src/metabase/auth/components/ForgotPassword/ForgotPassword.tsx
+++ b/frontend/src/metabase/auth/components/ForgotPassword/ForgotPassword.tsx
@@ -20,12 +20,8 @@ import {
type ViewType = "form" | "disabled" | "success";
-interface ForgotPasswordQueryString {
- email?: string;
-}
-
interface ForgotPasswordProps {
- location?: Location<ForgotPasswordQueryString>;
+ location?: Location;
}
export const ForgotPassword = ({
@@ -34,7 +30,8 @@ export const ForgotPassword = ({
const isEmailConfigured = useSelector(getIsEmailConfigured);
const isLdapEnabled = useSelector(getIsLdapEnabled);
const canResetPassword = isEmailConfigured && !isLdapEnabled;
- const initialEmail = location?.query?.email;
+ const initialEmail =
+ new URLSearchParams(location?.search).get("email") ?? undefined;
const [view, setView] = useState<ViewType>(
canResetPassword ? "form" : "disabled",
diff --git a/frontend/src/metabase/auth/components/Login/Login.tsx b/frontend/src/metabase/auth/components/Login/Login.tsx
index 32728202dc7..44591cdb689 100644
--- a/frontend/src/metabase/auth/components/Login/Login.tsx
+++ b/frontend/src/metabase/auth/components/Login/Login.tsx
@@ -4,7 +4,7 @@ import _ from "underscore";
import { usePageTitle } from "metabase/hooks/use-page-title";
import type { AuthProvider } from "metabase/plugins/types";
import { useSelector } from "metabase/redux";
-import { useParams, useRouter } from "metabase/router";
+import { useParams, useSearchParams } from "metabase/router";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Box, Divider } from "metabase/ui";
@@ -16,11 +16,11 @@ type LoginQueryParams = {
};
export const Login = (): JSX.Element => {
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
const params = useParams<LoginQueryParams>();
const providers = useSelector(getAuthProviders);
const selection = getSelectedProvider(providers, params.provider);
- const redirectUrl = location.query?.redirect;
+ const redirectUrl = searchParams.get("redirect") ?? undefined;
const applicationName = useSelector(getApplicationName);
usePageTitle(t`Login`);
diff --git a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
index 228d045df2c..66935c72fcd 100644
--- a/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
+++ b/frontend/src/metabase/auth/components/ResetPassword/ResetPassword.tsx
@@ -7,7 +7,7 @@ import { useValidatePassword } from "metabase/common/hooks";
import { useToast } from "metabase/common/hooks/use-toast";
import { useDispatch } from "metabase/redux";
import { resetPassword } from "metabase/redux/auth";
-import { replace, useParams, useRouter } from "metabase/router";
+import { replace, useParams, useSearchParams } from "metabase/router";
import { Button } from "metabase/ui";
import * as Urls from "metabase/urls";
@@ -23,10 +23,10 @@ type ResetPasswordQueryParams = {
};
export const ResetPassword = (): JSX.Element | null => {
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
const { token = "" } = useParams<ResetPasswordQueryParams>();
- const redirectUrl = location.query?.redirect;
- const email = location.query?.email;
+ const redirectUrl = searchParams.get("redirect") ?? undefined;
+ const email = searchParams.get("email") ?? undefined;
const dispatch = useDispatch();
const [sendToast] = useToast();
const validatePassword = useValidatePassword();
diff --git a/frontend/src/metabase/common/collections/hooks.ts b/frontend/src/metabase/common/collections/hooks.ts
index 1e456d4c47b..4ce98156fc7 100644
--- a/frontend/src/metabase/common/collections/hooks.ts
+++ b/frontend/src/metabase/common/collections/hooks.ts
@@ -49,10 +49,9 @@ export function useInitialCollectionId({
disabled ? skipToken : collectionIdParam(idFromSlug),
);
- // Unjustified type cast. FIXME
- const idFromQuery = location?.query?.collectionId as
- | Collection["id"]
- | undefined;
+ const idFromQuery = Urls.extractCollectionId(
+ new URLSearchParams(location?.search).get("collectionId") ?? undefined,
+ );
const { data: fromQuery } = useGetCollectionQuery(
disabled ? skipToken : collectionIdParam(idFromQuery),
);
diff --git a/frontend/src/metabase/common/components/ModalRoute.tsx b/frontend/src/metabase/common/components/ModalRoute.tsx
index ef6f0e18ca3..9bb3f5f9b5a 100644
--- a/frontend/src/metabase/common/components/ModalRoute.tsx
+++ b/frontend/src/metabase/common/components/ModalRoute.tsx
@@ -52,7 +52,6 @@ export function modalRoute(
) {
function ModalRouteComponent() {
const params = useParams();
- // The raw v3 location (with `query`), which some modals still read.
const { location } = useRouter();
const route = useRoute() ?? undefined;
const navigate = useNavigate();
diff --git a/frontend/src/metabase/common/components/Unsubscribe.tsx b/frontend/src/metabase/common/components/Unsubscribe.tsx
index 416a04cbfc9..4ed5a15b323 100644
--- a/frontend/src/metabase/common/components/Unsubscribe.tsx
+++ b/frontend/src/metabase/common/components/Unsubscribe.tsx
@@ -14,7 +14,7 @@ import { LighthouseIllustration } from "metabase/common/components/LighthouseIll
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { LogoIcon } from "metabase/common/components/LogoIcon";
import { useSelector } from "metabase/redux";
-import { useRouter } from "metabase/router";
+import { useSearchParams } from "metabase/router";
import { getLoginPageIllustration } from "metabase/selectors/whitelabel";
import { Button, Center, Stack, Text } from "metabase/ui";
@@ -39,15 +39,16 @@ const SUBSCRIPTION = {
type Subscription = (typeof SUBSCRIPTION)[keyof typeof SUBSCRIPTION];
export const UnsubscribePage = (): JSX.Element => {
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
const [subscriptionChange, setSubscriptionChange] = useState<Subscription>(
SUBSCRIPTION.UNSUBSCRIBE,
);
- const hash = location.query?.hash;
- const email = location.query?.email;
- const pulseId = location.query?.["pulse-id"];
- const notificationHandlerId = location.query?.["notification-handler-id"];
+ const hash = searchParams.get("hash") ?? undefined;
+ const email = searchParams.get("email") ?? undefined;
+ const pulseId = searchParams.get("pulse-id") ?? undefined;
+ const notificationHandlerId =
+ searchParams.get("notification-handler-id") ?? undefined;
const { data, isLoading, error } = useUnsubscribeRequest({
hash,
diff --git a/frontend/src/metabase/common/components/upsells/components/InsightsTabOrLink/tests/premium.unit.spec.tsx b/frontend/src/metabase/common/components/upsells/components/InsightsTabOrLink/tests/premium.unit.spec.tsx
index df0bf3025f5..5b3fa202b69 100644
--- a/frontend/src/metabase/common/components/upsells/components/InsightsTabOrLink/tests/premium.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/upsells/components/InsightsTabOrLink/tests/premium.unit.spec.tsx
@@ -23,9 +23,7 @@ describe("InsightsTabOrLink (EE with token)", () => {
const routerLink = await screen.findByText("Insights");
await userEvent.click(routerLink);
expect(history?.getCurrentLocation().pathname).toBe("/dashboard/201");
- expect(history?.getCurrentLocation().query).toEqual({
- dashboard_id: "1",
- });
+ expect(history?.getCurrentLocation().search).toBe("?dashboard_id=1");
expect(
await screen.findByTestId("usage-analytics-dashboard"),
).toBeInTheDocument();
@@ -41,7 +39,7 @@ describe("InsightsTabOrLink (EE with token)", () => {
const routerLink = await screen.findByText("Insights");
await userEvent.click(routerLink);
expect(history?.getCurrentLocation().pathname).toBe("/dashboard/202");
- expect(history?.getCurrentLocation().query).toEqual({ question_id: "0" });
+ expect(history?.getCurrentLocation().search).toBe("?question_id=0");
expect(
await screen.findByTestId("usage-analytics-dashboard"),
).toBeInTheDocument();
@@ -59,9 +57,7 @@ describe("InsightsTabOrLink (EE with token)", () => {
const routerLink = await screen.findByText("Insights");
await userEvent.click(routerLink);
expect(history?.getCurrentLocation().pathname).toBe("/dashboard/201");
- expect(history?.getCurrentLocation().query).toEqual({
- dashboard_id: "1",
- });
+ expect(history?.getCurrentLocation().search).toBe("?dashboard_id=1");
expect(
await screen.findByTestId("usage-analytics-dashboard"),
).toBeInTheDocument();
diff --git a/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
index 012d96298a5..7553e10a5b8 100644
--- a/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
+++ b/frontend/src/metabase/common/hooks/use-confirm-route-leave-modal.ts
@@ -3,6 +3,7 @@ import { match } from "ts-pattern";
import { useDispatch } from "metabase/redux";
import {
+ type Action,
type InjectedRouter,
type Location,
type PlainRoute,
@@ -51,7 +52,10 @@ export const useConfirmRouteLeaveModal = ({
isLocationAllowed = IS_LOCATION_ALLOWED,
}: UseConfirmLeaveModalInput): UseConfirmLeaveModalResult => {
const dispatch = useDispatch();
- const [nextLocation, setNextLocation] = useState<Location | undefined>();
+ const [nextNavigation, setNextNavigation] = useState<{
+ location: Location;
+ navigationType: Action;
+ }>();
const [opened, setOpened] = useState<boolean>(false);
const close = useCallback(() => setOpened(false), []);
@@ -62,21 +66,29 @@ export const useConfirmRouteLeaveModal = ({
useBeforeUnload(isEnabled);
useEffect(() => {
- const removeLeaveHook = router.setRouteLeaveHook(route, (location) => {
- if (isEnabled && !isConfirmed && !isLocationAllowed?.(location)) {
- setOpened(true);
- setNextLocation(location);
- return false;
- }
- });
+ const removeLeaveHook = router.setRouteLeaveHook(
+ route,
+ (location, navigationType) => {
+ if (isEnabled && !isConfirmed && !isLocationAllowed?.(location)) {
+ setOpened(true);
+ setNextNavigation(
+ location && navigationType
+ ? { location, navigationType }
+ : undefined,
+ );
+ return false;
+ }
+ },
+ );
return removeLeaveHook;
}, [isLocationAllowed, router, route, isEnabled, isConfirmed]);
useEffect(
function confirmNavigation() {
- if (isConfirmed && nextLocation) {
- match(nextLocation.action)
+ if (isConfirmed && nextNavigation) {
+ const { location, navigationType } = nextNavigation;
+ match(navigationType)
.with("POP", () => {
/**
* Ideally we should be using dispatch(go(numberOfPages)), but there is no simple
@@ -86,15 +98,15 @@ export const useConfirmRouteLeaveModal = ({
dispatch(goBack());
})
.with("PUSH", () => {
- dispatch(push(nextLocation));
+ dispatch(push(location));
})
.with("REPLACE", () => {
- dispatch(replace(nextLocation));
+ dispatch(replace(location));
})
.exhaustive();
}
},
- [dispatch, isConfirmed, nextLocation],
+ [dispatch, isConfirmed, nextNavigation],
);
useEffect(
@@ -113,6 +125,6 @@ export const useConfirmRouteLeaveModal = ({
opened,
close,
confirm,
- nextLocation,
+ nextLocation: nextNavigation?.location,
};
};
diff --git a/frontend/src/metabase/common/hooks/use-url-state/types.ts b/frontend/src/metabase/common/hooks/use-url-state/types.ts
index d531f343a16..2e8d9d9dafb 100644
--- a/frontend/src/metabase/common/hooks/use-url-state/types.ts
+++ b/frontend/src/metabase/common/hooks/use-url-state/types.ts
@@ -1,3 +1,11 @@
-import type { Query } from "metabase/router";
+/**
+ * A URL query as this hook passes it around: parsed out of the search string,
+ * where a repeated key comes through as an array, and serialized back, where a
+ * key the state no longer needs is `undefined`.
+ */
+export type UrlStateQuery = Record<
+ string,
+ string | string[] | null | undefined
+>;
-export type QueryParam = Query[keyof Query];
+export type QueryParam = UrlStateQuery[string];
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 7004074254b..1585a71c943 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
@@ -4,14 +4,17 @@ 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 type { Location } from "metabase/router";
import { push, queryToSearch, replace } from "metabase/router";
+import { parseSearchQuery } from "metabase/utils/browser";
+
+import type { UrlStateQuery } from "./types";
type BaseState = Record<string, unknown>;
export type UrlStateConfig<State extends BaseState> = {
- parse: (query: Query) => State;
- serialize: (state: State) => Query;
+ parse: (query: UrlStateQuery) => State;
+ serialize: (state: State) => UrlStateQuery;
};
type UrlStateActions<State extends BaseState> = {
@@ -29,7 +32,9 @@ export function useUrlState<State extends BaseState>(
{ parse, serialize }: UrlStateConfig<State>,
): [State, UrlStateActions<State>] {
const dispatch = useDispatch();
- const [state, setState] = useState(parse(location.query));
+ const [state, setState] = useState(() =>
+ parse(parseSearchQuery(location.search)),
+ );
const urlState = useDebouncedValue(state, URL_UPDATE_DEBOUNCE_DELAY);
const patchUrlState = useCallback((patch: Partial<State>) => {
@@ -53,7 +58,7 @@ export function useUrlState<State extends BaseState>(
const query = serialize(urlState);
// Replacing to the identical URL notifies the router, which re-renders every
// location consumer on the page for nothing.
- if (!_.isEqual(query, location.query)) {
+ if (!_.isEqual(query, parseSearchQuery(location.search))) {
dispatch(replace({ ...location, search: queryToSearch(query) }));
}
});
diff --git a/frontend/src/metabase/common/hooks/use-url-state/use-url-state.unit.spec.ts b/frontend/src/metabase/common/hooks/use-url-state/use-url-state.unit.spec.ts
index b0b77ae3956..a20689c1ecc 100644
--- a/frontend/src/metabase/common/hooks/use-url-state/use-url-state.unit.spec.ts
+++ b/frontend/src/metabase/common/hooks/use-url-state/use-url-state.unit.spec.ts
@@ -133,7 +133,5 @@ describe("useUrlState", () => {
});
function createLocation(search: string) {
- const params = new URLSearchParams(search);
- const query = Object.fromEntries(params.entries());
- return createMockLocation({ search, query });
+ return createMockLocation({ search });
}
diff --git a/frontend/src/metabase/common/search/search-location/search-location.ts b/frontend/src/metabase/common/search/search-location/search-location.ts
index 42206237001..27cf88c0686 100644
--- a/frontend/src/metabase/common/search/search-location/search-location.ts
+++ b/frontend/src/metabase/common/search/search-location/search-location.ts
@@ -1,29 +1,29 @@
import _ from "underscore";
import { SearchFilterKeys } from "metabase/common/search/constants";
-import type {
- SearchAwareLocation,
- URLSearchFilterQueryParams,
-} from "metabase/common/search/types";
+import type { URLSearchFilterQueryParams } from "metabase/common/search/types";
+import type { Location } from "metabase/router";
+import { parseSearchQuery } from "metabase/utils/browser";
-export function isSearchPageLocation(location?: SearchAwareLocation): boolean {
+export function isSearchPageLocation(location?: Location): boolean {
return location ? /^\/?search$/.test(location.pathname) : false;
}
-export function getSearchTextFromLocation(
- location: SearchAwareLocation,
-): string {
+export function getSearchTextFromLocation(location: Location): string {
if (isSearchPageLocation(location)) {
- return location.query.q || "";
+ return new URLSearchParams(location.search).get("q") || "";
}
return "";
}
export function getFiltersFromLocation(
- location: SearchAwareLocation,
+ location: Location,
): URLSearchFilterQueryParams {
if (isSearchPageLocation(location)) {
- return _.pick(location.query, Object.values(SearchFilterKeys));
+ return _.pick(
+ parseSearchQuery(location.search),
+ Object.values(SearchFilterKeys),
+ );
}
return {};
}
diff --git a/frontend/src/metabase/common/search/search-location/search-location.unit.spec.ts b/frontend/src/metabase/common/search/search-location/search-location.unit.spec.ts
index ee8369f2442..3222df76cd1 100644
--- a/frontend/src/metabase/common/search/search-location/search-location.unit.spec.ts
+++ b/frontend/src/metabase/common/search/search-location/search-location.unit.spec.ts
@@ -4,98 +4,76 @@ import {
isSearchPageLocation,
} from "metabase/common/search";
import { SearchFilterKeys } from "metabase/common/search/constants";
-import type { SearchAwareLocation } from "metabase/common/search/types";
+import { createMockLocation } from "metabase/redux/store/mocks";
describe("isSearchPageLocation", () => {
it("should return true for a search page location", () => {
- const location = { pathname: "/search" };
- // Unjustified type cast. FIXME
- const result = isSearchPageLocation(location as SearchAwareLocation);
- expect(result).toBe(true);
+ const location = createMockLocation({ pathname: "/search" });
+ expect(isSearchPageLocation(location)).toBe(true);
});
it("should return true for a search page location with query params", () => {
- const location = { pathname: "/search", search: "?q=test" };
- // Unjustified type cast. FIXME
- const result = isSearchPageLocation(location as SearchAwareLocation);
- expect(result).toBe(true);
+ const location = createMockLocation({
+ pathname: "/search",
+ search: "?q=test",
+ });
+ expect(isSearchPageLocation(location)).toBe(true);
});
it('should return false for non-search location that might have "search" in the path', () => {
- const location = { pathname: "/collection/1-search" };
- // Unjustified type cast. FIXME
- const result = isSearchPageLocation(location as SearchAwareLocation);
- expect(result).toBe(false);
+ const location = createMockLocation({ pathname: "/collection/1-search" });
+ expect(isSearchPageLocation(location)).toBe(false);
});
it("should return false for non-search location", () => {
- const location = { pathname: "/some-page" };
- // Unjustified type cast. FIXME
- const result = isSearchPageLocation(location as SearchAwareLocation);
- expect(result).toBe(false);
+ const location = createMockLocation({ pathname: "/some-page" });
+ expect(isSearchPageLocation(location)).toBe(false);
});
});
describe("getSearchTextFromLocation", () => {
it("should return the search text when on the search page", () => {
- const location = {
+ const location = createMockLocation({
pathname: "/search",
- query: { q: "test" },
- };
- // Unjustified type cast. FIXME
- expect(getSearchTextFromLocation(location as SearchAwareLocation)).toBe(
- "test",
- );
+ search: "?q=test",
+ });
+ expect(getSearchTextFromLocation(location)).toBe("test");
});
it("should return an empty string when not on the search page", () => {
- const location = {
+ const location = createMockLocation({
pathname: "/collection/root",
- query: {
- q: "test",
- },
- };
- // Unjustified type cast. FIXME
- expect(getSearchTextFromLocation(location as SearchAwareLocation)).toBe("");
+ search: "?q=test",
+ });
+ expect(getSearchTextFromLocation(location)).toBe("");
});
});
describe("getFiltersFromLocation", () => {
it("should return the filters when on the search page", () => {
- const location = {
+ const location = createMockLocation({
pathname: "/search",
- query: {
- [SearchFilterKeys.Type]: ["app", "database"],
- },
- };
- // Unjustified type cast. FIXME
- expect(getFiltersFromLocation(location as SearchAwareLocation)).toEqual({
+ search: `?${SearchFilterKeys.Type}=app&${SearchFilterKeys.Type}=database`,
+ });
+ expect(getFiltersFromLocation(location)).toEqual({
[SearchFilterKeys.Type]: ["app", "database"],
});
});
it("should return an empty object when on a non-search page", () => {
- const location = {
+ const location = createMockLocation({
pathname: "/collection/root",
- query: {
- [SearchFilterKeys.Type]: ["app", "database"],
- },
- };
- // Unjustified type cast. FIXME
- expect(getFiltersFromLocation(location as SearchAwareLocation)).toEqual({});
+ search: `?${SearchFilterKeys.Type}=app&${SearchFilterKeys.Type}=database`,
+ });
+ expect(getFiltersFromLocation(location)).toEqual({});
});
it("should return only the filters that exist in SearchFilterKeys", () => {
- const location = {
+ const location = createMockLocation({
pathname: "/search",
- query: {
- [SearchFilterKeys.Type]: ["app", "database"],
- someOtherFilter: [1, 2, 3],
- },
- };
- // using `any` here since location.query doesn't match the query
- // of SearchAwareLocation
- expect(getFiltersFromLocation(location as any)).toEqual({
+ search: `?${SearchFilterKeys.Type}=app&${SearchFilterKeys.Type}=database&someOtherFilter=1`,
+ });
+ expect(getFiltersFromLocation(location)).toEqual({
[SearchFilterKeys.Type]: ["app", "database"],
});
});
diff --git a/frontend/src/metabase/common/search/types.ts b/frontend/src/metabase/common/search/types.ts
index 3481f16155a..655e1b56276 100644
--- a/frontend/src/metabase/common/search/types.ts
+++ b/frontend/src/metabase/common/search/types.ts
@@ -1,7 +1,6 @@
import type { ComponentType } from "react";
import type { SearchFilterKeys } from "metabase/common/search/constants";
-import type { Location } from "metabase/router";
import type { EnabledSearchModel, IconName, UserId } from "metabase-types/api";
export type TypeFilterProps = EnabledSearchModel[];
@@ -34,9 +33,6 @@ export type SearchQueryParamValue = string | string[] | null | undefined;
export type URLSearchFilterQueryParams = Partial<
Record<FilterTypeKeys, SearchQueryParamValue>
>;
-export type SearchAwareLocation = Location<
- { q?: string; page?: string } & URLSearchFilterQueryParams
->;
export type SearchFilters = Partial<SearchFilterPropTypes>;
diff --git a/frontend/src/metabase/dashboard/actions/parameters.tsx b/frontend/src/metabase/dashboard/actions/parameters.tsx
index 5116f1bc99d..2dc6708378d 100644
--- a/frontend/src/metabase/dashboard/actions/parameters.tsx
+++ b/frontend/src/metabase/dashboard/actions/parameters.tsx
@@ -24,7 +24,6 @@ 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 { Query } from "metabase/router";
import { getMetadata } from "metabase/selectors/metadata";
import { Text } from "metabase/ui";
import { isQuestionDashCard } from "metabase/utils/dashboard";
@@ -42,6 +41,7 @@ import type {
Parameter,
ParameterId,
ParameterTarget,
+ ParameterValuesMap,
TemporalUnit,
ValuesQueryType,
ValuesSourceConfig,
@@ -1070,7 +1070,7 @@ export const setOrUnsetParameterValues =
};
export const setParameterValuesFromQueryParams =
- (queryParams: Query = {}) =>
+ (queryParams: ParameterValuesMap = {}) =>
(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 c3bf9cc7aff..9ce3f49c11a 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
@@ -21,9 +21,10 @@ 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, searchToQuery } from "metabase/router";
+import { push } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Flex, Group, type IconProps, Menu, Title } from "metabase/ui";
+import { parseSearchQuery } from "metabase/utils/browser";
import { isVirtualDashCard } from "metabase/utils/dashboard";
import { measureTextWidth } from "metabase/utils/measure-text";
import { getVisualizationRaw, isCartesianChart } from "metabase/visualizations";
@@ -180,7 +181,9 @@ export function DashCardVisualization({
(location: LocationDescriptorObject) => {
dispatch(push(location));
dispatch(
- setParameterValuesFromQueryParams(searchToQuery(location.search ?? "")),
+ setParameterValuesFromQueryParams(
+ parseSearchQuery(location.search ?? ""),
+ ),
);
},
[dispatch],
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
index ca4748e48fb..649c4b14eff 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
@@ -1,4 +1,4 @@
-import { type MouseEvent, forwardRef, useState } from "react";
+import { type MouseEvent, forwardRef, useMemo, useState } from "react";
import { c, t } from "ttag";
import { Link, type LinkProps } from "metabase/common/components/Link";
@@ -9,6 +9,7 @@ import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut"
import { PLUGIN_CACHING, PLUGIN_MODERATION } from "metabase/plugins";
import { useRouter } from "metabase/router";
import { Icon, Menu } from "metabase/ui";
+import { parseSearchQuery } from "metabase/utils/browser";
import {
AutoRefreshMenuItem,
@@ -51,9 +52,14 @@ const DashboardActionMenuInner = ({
}
};
+ const parameterQueryParams = useMemo(
+ () => parseSearchQuery(location?.search ?? ""),
+ [location?.search],
+ );
+
const { refreshDashboard } = useRefreshDashboard({
dashboardId: dashboard?.id ?? null,
- parameterQueryParams: location?.query,
+ parameterQueryParams,
});
const moderationItems = PLUGIN_MODERATION.useDashboardMenuItems(
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
index 765568aea75..ce3d02848fe 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
@@ -1,5 +1,5 @@
import cx from "classnames";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import ErrorBoundary from "metabase/ErrorBoundary";
import { isRouteInSync } from "metabase/common/hooks/is-route-in-sync";
@@ -34,7 +34,11 @@ import { setErrorPage } from "metabase/redux/app";
import type { Location } from "metabase/router";
import { Outlet, replace, useRouter } from "metabase/router";
import * as Urls from "metabase/urls";
-import { parseHashOptions, stringifyHashOptions } from "metabase/utils/browser";
+import {
+ parseHashOptions,
+ parseSearchQuery,
+ stringifyHashOptions,
+} from "metabase/utils/browser";
import type { DashboardId, Dashboard as IDashboard } from "metabase-types/api";
import { useRegisterDashboardMetabotContext } from "../../hooks/use-register-dashboard-metabot-context";
@@ -79,7 +83,10 @@ export const DashboardApp = () => {
const [error, setError] = useState<string>();
- const parameterQueryParams = location.query;
+ const parameterQueryParams = useMemo(
+ () => parseSearchQuery(location.search),
+ [location.search],
+ );
// Unjustified type cast. FIXME
const dashboardId = Urls.extractEntityId(params.slug) as DashboardId;
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 18b22a89cf9..eba85734ee6 100644
--- a/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
+++ b/frontend/src/metabase/dashboard/hooks/use-dashboard-url-query.ts
@@ -14,6 +14,7 @@ import {
replace,
} from "metabase/router";
import * as Urls from "metabase/urls";
+import { parseSearchQuery } from "metabase/utils/browser";
import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";
import {
@@ -22,7 +23,7 @@ import {
getTabs,
getValuePopulatedParameters,
} from "../selectors";
-import { createTabSlug } from "../utils";
+import { createTabSlug, parseTabSlug } from "../utils";
export function useDashboardUrlQuery(
router: InjectedRouter,
@@ -80,7 +81,7 @@ export function useDashboardUrlQuery(
return;
}
- const currentQuery = location?.query ?? {};
+ const currentQuery = parseSearchQuery(location.search);
const nextQueryParams = toLocationQuery(queryParams);
const currentQueryParams = _.omit(currentQuery, ...QUERY_PARAMS_ALLOW_LIST);
@@ -114,8 +115,8 @@ export function useDashboardUrlQuery(
return;
}
- const currentTabId = parseTabId(location);
- const nextTabId = parseTabId(nextLocation);
+ const currentTabId = parseTabSlug(location);
+ const nextTabId = parseTabSlug(nextLocation);
if (nextTabId && currentTabId !== nextTabId) {
dispatch(selectTab({ tabId: nextTabId }));
@@ -128,15 +129,6 @@ export function useDashboardUrlQuery(
const QUERY_PARAMS_ALLOW_LIST = ["objectId", "returnToEmbeddingSetupGuide"];
-function parseTabId(location: Location) {
- const slug = location.query?.tab;
- if (typeof slug === "string" && slug.length > 0) {
- const id = parseInt(slug, 10);
- return Number.isSafeInteger(id) ? id : null;
- }
- return null;
-}
-
function toLocationQuery(object: Record<string, any>) {
return _.mapObject(object, (value) => (value == null ? "" : value));
}
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 a3d88e6d173..39745b2822e 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
@@ -44,7 +44,7 @@ type SetupOptions = {
tabs?: { id: number; name: string }[];
selectedTabId?: number | null;
pathname?: string;
- query?: Record<string, unknown>;
+ search?: string;
};
function setup({
@@ -54,7 +54,7 @@ function setup({
tabs,
selectedTabId = null,
pathname = `/dashboard/${DASHBOARD_ID}`,
- query = {},
+ search = "",
}: SetupOptions = {}) {
const listeners: ((location: Location) => void)[] = [];
const unsubscribe = jest.fn();
@@ -68,8 +68,7 @@ function setup({
// Unjustified type cast. FIXME
const location = {
pathname,
- query,
- search: "",
+ search,
hash: "",
state: null,
} as unknown as Location;
@@ -186,7 +185,7 @@ describe("useDashboardUrlQuery", () => {
act(() => {
listeners[0]({
...location,
- query: { tab: "5-tab-5" },
+ search: "?tab=5-tab-5",
});
});
@@ -202,7 +201,7 @@ describe("useDashboardUrlQuery", () => {
listeners[0]({
...location,
pathname: "/dashboard/999",
- query: { tab: "5-tab-5" },
+ search: "?tab=5-tab-5",
});
});
@@ -234,7 +233,7 @@ describe("useDashboardUrlQuery", () => {
setup({
parameters: [createMockParameter({ id: "1", slug: "text" })],
parameterValues: { "1": "bar" },
- query: { objectId: "42" },
+ search: "?objectId=42",
});
expect(replace).toHaveBeenCalledTimes(1);
diff --git a/frontend/src/metabase/dashboard/utils.ts b/frontend/src/metabase/dashboard/utils.ts
index dc5a91d2f20..8e65c2effe9 100644
--- a/frontend/src/metabase/dashboard/utils.ts
+++ b/frontend/src/metabase/dashboard/utils.ts
@@ -403,8 +403,10 @@ export const isDashboardCacheable = (
): dashboard is CacheableDashboard => typeof dashboard.id !== "string";
export function parseTabSlug(location: Location) {
- const slug = location.query?.tab;
- if (typeof slug === "string" && slug.length > 0) {
+ const slugs = new URLSearchParams(location.search).getAll("tab");
+ // A repeated `tab` is ambiguous, so treat it as no tab at all.
+ const slug = slugs.length === 1 ? slugs[0] : "";
+ if (slug.length > 0) {
const id = parseInt(slug, 10);
return Number.isSafeInteger(id) ? id : null;
}
diff --git a/frontend/src/metabase/dashboard/utils.unit.spec.ts b/frontend/src/metabase/dashboard/utils.unit.spec.ts
index a2171f4f6c0..6ac38c61edf 100644
--- a/frontend/src/metabase/dashboard/utils.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/utils.unit.spec.ts
@@ -14,7 +14,6 @@ import {
syncParametersAndEmbeddingParams,
} from "metabase/dashboard/utils";
import { createMockLocation } from "metabase/redux/store/mocks";
-import type { Location } from "metabase/router";
import { SERVER_ERROR_TYPES } from "metabase/utils/errors";
import { checkNotNull } from "metabase/utils/types";
import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";
@@ -43,8 +42,13 @@ const DISABLED_ACTIONS_DATABASE = createMockDatabase({
});
const NO_ACTIONS_DATABASE = createMockDatabase({ id: 3 });
-function getMockLocationWithTab(slug: Location["query"][string]) {
- return createMockLocation({ query: { tab: slug } });
+function getMockLocationWithTab(slug: string | string[] | null | undefined) {
+ const params = new URLSearchParams();
+ for (const value of slug == null ? [] : [slug].flat()) {
+ params.append("tab", value);
+ }
+ const search = params.toString();
+ return createMockLocation({ search: search ? `?${search}` : "" });
}
describe("Dashboard utils", () => {
@@ -516,9 +520,7 @@ describe("Dashboard utils", () => {
getMockLocationWithTab(["1-tab-name", "2-another-tab-name"]),
),
).toBe(null);
- expect(parseTabSlug({ ...getMockLocationWithTab(""), query: {} })).toBe(
- null,
- );
+ expect(parseTabSlug(createMockLocation())).toBe(null);
});
});
diff --git a/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx b/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx
index e6d10f2d8fd..aba4aad7f2d 100644
--- a/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx
@@ -5,14 +5,14 @@ import {
useUserMetabotPermissions,
} from "metabase/metabot/hooks";
import { useDispatch } from "metabase/redux";
-import { Route, replace, useRouter } from "metabase/router";
+import { Route, replace, useSearchParams } from "metabase/router";
import { Loader } from "metabase/ui";
function MetabotNewRoute() {
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
const { canUseMetabot, isLoading } = useUserMetabotPermissions();
const { submitInput } = useMetabotAgent("omnibot");
- const prompt = String(location.query?.q ?? "");
+ const prompt = searchParams.get("q") ?? "";
const dispatch = useDispatch();
const [hasSubmitted, setHasSubmitted] = useState(false);
diff --git a/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx b/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
index daaacce287a..de23074d94d 100644
--- a/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
+++ b/frontend/src/metabase/metrics/pages/NewMetricPage/NewMetricPage.tsx
@@ -52,7 +52,7 @@ export function NewMetricPage({
const [isModalOpened, { open: openModal, close: closeModal }] =
useDisclosure();
const initialCollectionId = Urls.extractCollectionId(
- location.query.collectionId,
+ new URLSearchParams(location.search).get("collectionId") ?? undefined,
);
const defaultCollectionId = useGetDefaultCollectionId();
const dispatch = useDispatch();
diff --git a/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx b/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
index a9839fe0cd2..1af21031f14 100644
--- a/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
+++ b/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
@@ -30,8 +30,7 @@ const NewModelOptions = () => {
);
const collectionId = Urls.extractEntityId(
- // Unjustified type cast. FIXME
- location.query.collectionId as string,
+ new URLSearchParams(location.search).get("collectionId") ?? undefined,
);
const showMetabaseLinks = useSelector(getShowMetabaseLinks);
diff --git a/frontend/src/metabase/monitor/route-guards.unit.spec.tsx b/frontend/src/metabase/monitor/route-guards.unit.spec.tsx
index 3e36a675989..aa07149cc41 100644
--- a/frontend/src/metabase/monitor/route-guards.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/route-guards.unit.spec.tsx
@@ -41,9 +41,11 @@ describe("monitor route-guards", () => {
expect(history?.getCurrentLocation().pathname).toBe("/auth/login");
});
- expect(history?.getCurrentLocation().query).toEqual(
- expect.objectContaining({ redirect: "/monitor" }),
- );
+ expect(
+ new URLSearchParams(history?.getCurrentLocation().search).get(
+ "redirect",
+ ),
+ ).toBe("/monitor");
});
it("redirects users without monitor access to unauthorized", async () => {
@@ -58,7 +60,7 @@ describe("monitor route-guards", () => {
expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
});
- expect(history?.getCurrentLocation().query).toEqual({});
+ expect(history?.getCurrentLocation().search).toBe("");
});
it("renders for analysts", () => {
@@ -119,7 +121,7 @@ describe("monitor route-guards", () => {
expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
});
- expect(history?.getCurrentLocation().query).toEqual({});
+ expect(history?.getCurrentLocation().search).toBe("");
expect(screen.queryByText("alerts page")).not.toBeInTheDocument();
});
@@ -135,7 +137,7 @@ describe("monitor route-guards", () => {
expect(history?.getCurrentLocation().pathname).toBe("/unauthorized");
});
- expect(history?.getCurrentLocation().query).toEqual({});
+ expect(history?.getCurrentLocation().search).toBe("");
expect(screen.queryByText("alerts page")).not.toBeInTheDocument();
});
});
diff --git a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
index 153a3e1d6fa..91abf3ecf6b 100644
--- a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
+++ b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.tsx
@@ -22,7 +22,12 @@ 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, queryToSearch, useRouter } from "metabase/router";
+import {
+ push,
+ queryToSearch,
+ useNavigationType,
+ useRouter,
+} from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
import { Box, Flex, Icon, UnstyledButton, rem } from "metabase/ui";
import { modelToUrl } from "metabase/urls";
@@ -52,6 +57,7 @@ function SearchBar({
onSearchItemSelect: onSearchItemSelectProp,
}: Props) {
const { location } = useRouter();
+ const navigationType = useNavigationType();
const isTypeaheadEnabled = useSelector((state) =>
getSetting(state, "search-typeahead-enabled"),
);
@@ -140,11 +146,11 @@ function SearchBar({
}, [previousLocation, location]);
useEffect(() => {
- if (previousLocation !== location && location.action !== "REPLACE") {
+ if (previousLocation !== location && navigationType !== "REPLACE") {
// deactivate search when page changes
setInactive();
}
- }, [previousLocation, location, setInactive]);
+ }, [previousLocation, location, navigationType, setInactive]);
const goToSearchApp = useCallback(() => {
const shouldPersistFilters = isSearchPageLocation(previousLocation);
diff --git a/frontend/src/metabase/palette/components/Palette.tsx b/frontend/src/metabase/palette/components/Palette.tsx
index 8bd43bd1842..f85131ca513 100644
--- a/frontend/src/metabase/palette/components/Palette.tsx
+++ b/frontend/src/metabase/palette/components/Palette.tsx
@@ -1,11 +1,12 @@
import { KBarPortal, VisualState, useKBar } from "kbar";
-import { useEffect, useRef } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { useOnClickOutside } from "metabase/common/hooks/use-on-click-outside";
import { useSelector } from "metabase/redux";
-import { type Query, useRouter } from "metabase/router";
+import { useRouter } from "metabase/router";
import { getUser } from "metabase/selectors/user";
import { Box, Card, Center, Icon, Overlay, Stack, rem } from "metabase/ui";
+import { type SearchQuery, parseSearchQuery } from "metabase/utils/browser";
import { isWithinIframe } from "metabase/utils/iframe";
import { useCommandPalette } from "../hooks/useCommandPalette";
@@ -23,6 +24,10 @@ export const Palette = () => {
const routerProps = useRouter();
const { location } = routerProps;
const isLoggedIn = useSelector((state) => !!getUser(state));
+ const locationQuery = useMemo(
+ () => parseSearchQuery(location.search),
+ [location.search],
+ );
const isDisabledForPath = PALETTE_DISABLED_PATHS.some((path) =>
location.pathname.startsWith(path),
@@ -40,10 +45,7 @@ export const Palette = () => {
<KBarPortal>
<Overlay backgroundOpacity={0.5}>
<Center pt="10vh">
- <PaletteContainer
- disabled={disabled}
- locationQuery={location.query}
- />
+ <PaletteContainer disabled={disabled} locationQuery={locationQuery} />
</Center>
</Overlay>
</KBarPortal>
@@ -55,7 +57,7 @@ export const PaletteContainer = ({
locationQuery,
}: {
disabled: boolean;
- locationQuery: Query;
+ locationQuery: SearchQuery;
}) => {
const { query } = useKBar();
const ref = useRef(null);
diff --git a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
index 28a64b8c038..5f872d3c1c2 100644
--- a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
@@ -104,6 +104,12 @@ describe("Mouse/keyboard interactions", () => {
});
describe("The 'View and filter all N results' command palette item", () => {
+ // The link target is still a v3-style descriptor; the location it lands on
+ // carries the query as a search string.
+ const searchTarget = {
+ pathname: "/search",
+ search: "?q=hedgehogs",
+ };
const searchLocation = {
pathname: "/search",
search: "?q=hedgehogs",
@@ -117,7 +123,7 @@ describe("Mouse/keyboard interactions", () => {
icon: "link",
perform: () => {},
extra: {
- href: searchLocation,
+ href: searchTarget,
},
};
diff --git a/frontend/src/metabase/palette/components/PaletteResults.tsx b/frontend/src/metabase/palette/components/PaletteResults.tsx
index 47b983caa7d..cf88529040f 100644
--- a/frontend/src/metabase/palette/components/PaletteResults.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResults.tsx
@@ -7,7 +7,6 @@ import NoResults from "assets/img/no_results.svg";
import { Link } from "metabase/common/components/Link";
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 { queryToSearch } from "metabase/router";
import {
Flex,
@@ -20,6 +19,7 @@ import {
Text,
rem,
} from "metabase/ui";
+import type { SearchQuery } from "metabase/utils/browser";
import type { SearchResponse } from "metabase-types/api";
import type { PaletteActionImpl } from "../types";
@@ -37,7 +37,7 @@ const FullSearchCTA = ({
debouncedSearchTerm,
onClick,
}: {
- locationQuery: Query;
+ locationQuery: SearchQuery;
searchResults: SearchResponse;
debouncedSearchTerm: string;
onClick: () => void;
@@ -79,7 +79,7 @@ const FullSearchCTA = ({
};
type Props = Omit<StackProps, "children"> & {
- locationQuery: Query;
+ locationQuery: SearchQuery;
searchRequestId?: string;
searchResults?: SearchResponse;
liveSearchTerm: string;
diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
index 8ea77a7289d..1e7e1b71e94 100644
--- a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
+++ b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
@@ -19,6 +19,7 @@ import {
createMockState,
} from "metabase/redux/store/mocks";
import { Route, useRouter } from "metabase/router";
+import { parseSearchQuery } from "metabase/utils/browser";
import type { RecentItem, Settings } from "metabase-types/api";
import {
createMockCollection,
@@ -40,6 +41,7 @@ const TestComponent = ({
isLoggedIn: boolean;
}) => {
const routerProps = useRouter();
+ const locationQuery = parseSearchQuery(routerProps.location.search);
useCommandPaletteBasicActions({ ...routerProps, isLoggedIn });
const {
searchRequestId,
@@ -48,7 +50,7 @@ const TestComponent = ({
debouncedSearchTerm,
} = useCommandPalette({
disabled: false,
- locationQuery: routerProps.location.query,
+ locationQuery,
});
const { query } = useKBar();
@@ -62,7 +64,7 @@ const TestComponent = ({
return (
<PaletteResults
- locationQuery={routerProps.location.query}
+ locationQuery={locationQuery}
searchRequestId={searchRequestId}
searchResults={searchResults}
liveSearchTerm={liveSearchTerm}
diff --git a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
index b84e33e09e0..ee139dda0d6 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
@@ -11,7 +11,6 @@ import { useSetting } from "metabase/common/hooks";
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";
@@ -19,6 +18,7 @@ import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
import { Icon, Text } from "metabase/ui";
import * as Urls from "metabase/urls";
import { modelToUrl } from "metabase/urls";
+import type { SearchQuery } from "metabase/utils/browser";
import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";
import { getName } from "metabase/utils/name";
import {
@@ -36,7 +36,7 @@ export const useCommandPalette = ({
locationQuery,
}: {
disabled: boolean;
- locationQuery: Query;
+ locationQuery: SearchQuery;
}) => {
const getIcon = useGetIcon();
const showMetabaseLinks = useSelector(getShowMetabaseLinks);
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx
index 6c485c5b608..4f8c481ff40 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/PublicOrEmbeddedDashboardPage.tsx
@@ -1,3 +1,5 @@
+import { useMemo } from "react";
+
import { PublicOrEmbeddedDashCardMenu } from "metabase/dashboard/components/DashCard/PublicOrEmbeddedDashCardMenu";
import { DASHBOARD_DISPLAY_ACTIONS } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants";
import { useDashboardLocationSync } from "metabase/dashboard/containers/DashboardApp/use-dashboard-location-sync";
@@ -10,6 +12,7 @@ import { useDispatch, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
import { useParams, useRouter } from "metabase/router";
import { getCanWhitelabel } from "metabase/selectors/whitelabel";
+import { parseSearchQuery } from "metabase/utils/browser";
import { isActionDashCard, isQuestionCard } from "metabase/utils/dashboard";
import { Mode } from "metabase/visualizations/click-actions/Mode";
import { PublicMode } from "metabase/visualizations/click-actions/modes/PublicMode";
@@ -33,7 +36,10 @@ export const PublicOrEmbeddedDashboardPage = () => {
const { location } = useRouter();
const { uuid, token } = useParams<{ uuid: string; token: EntityToken }>();
- const parameterQueryParams = location.query;
+ const parameterQueryParams = useMemo(
+ () => parseSearchQuery(location.search),
+ [location.search],
+ );
const dashboardId = uuid || token;
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx
index bcdc1448528..b709966634c 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx
@@ -18,6 +18,7 @@ import { useParams, useRouter } from "metabase/router";
import { FieldSchema } from "metabase/schema";
import { getMetadata } from "metabase/selectors/metadata";
import { getCanWhitelabel } from "metabase/selectors/whitelabel";
+import { parseSearchQuery } from "metabase/utils/browser";
import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";
import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";
import { getParametersFromCard } from "metabase-lib/v1/parameters/utils/template-tags";
@@ -92,7 +93,7 @@ export const PublicOrEmbeddedQuestion = () => {
);
const parameterValuesById = getParameterValuesByIdFromQueryParams(
parameters,
- location.query,
+ parseSearchQuery(location.search),
);
setCard(card);
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index 1d21dd5a1f4..06e80bbccce 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -26,6 +26,7 @@ import { FieldSchema } from "metabase/schema";
import { getMetadata } from "metabase/selectors/metadata";
import { canUserCreateQueries, getUser } from "metabase/selectors/user";
import * as Urls from "metabase/urls";
+import { parseSearchQuery } from "metabase/utils/browser";
import { isNotNull } from "metabase/utils/types";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
@@ -302,7 +303,8 @@ async function handleQBInit(
);
});
- const queryParams = location.query;
+ const searchParams = new URLSearchParams(location.search ?? "");
+ const queryParams = parseSearchQuery(location.search ?? "");
const isTableRoute = location.pathname?.startsWith("/table");
const slugEntityId = Urls.extractEntityId(params.slug);
// On the /table/:slug route the slug identifies a table, not a saved card.
@@ -463,7 +465,8 @@ async function handleQBInit(
metadata,
});
- const objectId = params?.objectId || queryParams?.objectId;
+ const objectId =
+ params?.objectId || (searchParams.get("objectId") ?? undefined);
uiControls.notebookNativePreviewSidebarWidth =
getNotebookNativePreviewSidebarWidth(getState());
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 5be032c0e45..8a0d20e1002 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
@@ -310,10 +310,9 @@ describe("QB Actions > initializeQB", () => {
expect(result.objectId).toBe(123);
});
- it("passes object ID from location query params correctly", async () => {
+ it("passes object ID from the search string correctly", async () => {
const location = getLocationForCard(card, {
search: "?objectId=123",
- query: { objectId: "123" },
});
const { result } = await setup({ card, location });
expect(result.objectId).toBe("123");
@@ -355,10 +354,9 @@ describe("QB Actions > initializeQB", () => {
expect(result.objectId).toBe(123);
});
- it("passes object ID from location query params correctly", async () => {
+ it("passes object ID from the search string correctly", async () => {
const location = getLocationForCard(card, {
search: "?objectId=123",
- query: { objectId: "123" },
});
const { result } = await setup({ card: card, location });
expect(result.objectId).toBe("123");
diff --git a/frontend/src/metabase/query_builder/actions/core/parameterUtils.ts b/frontend/src/metabase/query_builder/actions/core/parameterUtils.ts
index 2f049644b1b..3d8f8df22c4 100644
--- a/frontend/src/metabase/query_builder/actions/core/parameterUtils.ts
+++ b/frontend/src/metabase/query_builder/actions/core/parameterUtils.ts
@@ -10,19 +10,7 @@ import { setErrorPage } from "metabase/redux/app";
import type { Dispatch } from "metabase/redux/store";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";
-import type { Card, Parameter } from "metabase-types/api";
-
-type BlankQueryOptions = {
- db?: string;
- table?: string;
- segment?: string;
- metric?: string;
-};
-
-type QueryParams = BlankQueryOptions & {
- slug?: string;
- objectId?: string;
-};
+import type { Card, Parameter, ParameterValuesMap } from "metabase-types/api";
function shouldPropagateDashboardParameters({
cardId,
@@ -87,7 +75,7 @@ export function getParameterValuesForQuestion({
metadata,
}: {
card: Card;
- queryParams?: QueryParams;
+ queryParams?: ParameterValuesMap;
metadata: Metadata;
}) {
const parameters = getCardUiParameters(card, metadata);
diff --git a/frontend/src/metabase/query_builder/actions/navigation.ts b/frontend/src/metabase/query_builder/actions/navigation.ts
index 011a91ee16c..7842ca69ebc 100644
--- a/frontend/src/metabase/query_builder/actions/navigation.ts
+++ b/frontend/src/metabase/query_builder/actions/navigation.ts
@@ -3,7 +3,7 @@ import _ from "underscore";
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 type { Action, Location } from "metabase/router";
import {
getCard,
@@ -30,9 +30,10 @@ export const popState = createThunkAction(
const zoomedObjectId = getZoomedObjectId(getState());
if (zoomedObjectId) {
// The POP has already committed, so `location` is the entry we navigated
- // to; its state/query hold the object we were previously zoomed into.
+ // to; its state/search hold the object we were previously zoomed into.
const previouslyZoomedObjectId =
- location.state?.objectId || location.query?.objectId;
+ location.state?.objectId ||
+ new URLSearchParams(location.search).get("objectId");
if (
previouslyZoomedObjectId &&
@@ -100,7 +101,12 @@ const getURL = (location: Location, { includeMode = false } = {}) =>
// Logic for handling location changes, dispatched by top-level QueryBuilder component
export const locationChanged =
- (location: Location, nextLocation: Location, nextParams: QueryParams) =>
+ (
+ location: Location,
+ nextLocation: Location,
+ nextParams: QueryParams,
+ navigationType: Action,
+ ) =>
(dispatch: Dispatch) => {
if (location !== nextLocation) {
// Treat both undefined and null as "no state" — the browser leaves
@@ -111,7 +117,7 @@ export const locationChanged =
const urlChanged =
getURL(nextLocation, { includeMode: true }) !==
getURL(location, { includeMode: true });
- if (nextLocation.action === "POP") {
+ if (navigationType === "POP") {
if (urlChanged) {
// the browser forward/back button was pressed
dispatch(popState(nextLocation));
@@ -124,7 +130,7 @@ export const locationChanged =
}
}
} else if (
- (nextLocation.action === "PUSH" || nextLocation.action === "REPLACE") &&
+ (navigationType === "PUSH" || navigationType === "REPLACE") &&
// ignore PUSH/REPLACE with `state` because they were initiated by the `updateUrl` action
isExternalUrlChange
) {
diff --git a/frontend/src/metabase/query_builder/actions/navigation.unit.spec.ts b/frontend/src/metabase/query_builder/actions/navigation.unit.spec.ts
index ef5375bc4c4..76edfa52354 100644
--- a/frontend/src/metabase/query_builder/actions/navigation.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/navigation.unit.spec.ts
@@ -1,6 +1,6 @@
// Pins the QB location-change read seam, the counterpart to url.ts which
// produces the pushes. locationChanged decides between re-running initializeQB
-// and dispatching popState based on location.action plus location.state. The
+// and dispatching popState based on the navigation type plus location.state. The
// router migration re-plumbs this read seam, so this locks the current matrix.
import type { Location } from "metabase/router";
@@ -13,7 +13,6 @@ const loc = (over: Partial<Location> = {}): Location =>
pathname: "/question/1",
search: "",
hash: "",
- action: "PUSH",
state: null,
...over,
}) as Location;
@@ -40,7 +39,7 @@ describe("locationChanged", () => {
it("does nothing when location and nextLocation are the same reference", () => {
const location = loc();
- locationChanged(location, location, {})(dispatch);
+ locationChanged(location, location, {}, "PUSH")(dispatch);
expect(dispatch).not.toHaveBeenCalled();
expect(initSpy).not.toHaveBeenCalled();
@@ -50,12 +49,11 @@ describe("locationChanged", () => {
const location = loc({ pathname: "/question/1" });
const nextLocation = loc({
pathname: "/question/2",
- action: "PUSH",
state: null,
});
const nextParams = { slug: "2" };
- locationChanged(location, nextLocation, nextParams)(dispatch);
+ locationChanged(location, nextLocation, nextParams, "PUSH")(dispatch);
expect(initSpy).toHaveBeenCalledTimes(1);
expect(initSpy).toHaveBeenCalledWith(nextLocation, nextParams);
@@ -66,11 +64,10 @@ describe("locationChanged", () => {
const location = loc({ pathname: "/question/1" });
const nextLocation = loc({
pathname: "/question/2",
- action: "PUSH",
state: { card: { id: 2 } },
});
- locationChanged(location, nextLocation, {})(dispatch);
+ locationChanged(location, nextLocation, {}, "PUSH")(dispatch);
expect(initSpy).not.toHaveBeenCalled();
expect(dispatch).not.toHaveBeenCalled();
@@ -80,11 +77,10 @@ describe("locationChanged", () => {
const location = loc({ pathname: "/question/1" });
const nextLocation = loc({
pathname: "/question/2",
- action: "REPLACE",
state: null,
});
- locationChanged(location, nextLocation, {})(dispatch);
+ locationChanged(location, nextLocation, {}, "REPLACE")(dispatch);
expect(initSpy).toHaveBeenCalledTimes(1);
expect(dispatchedAThunk(dispatch)).toBe(false);
@@ -94,11 +90,10 @@ describe("locationChanged", () => {
const location = loc({ pathname: "/question/1" });
const nextLocation = loc({
pathname: "/question/2",
- action: "REPLACE",
state: { card: { id: 2 } },
});
- locationChanged(location, nextLocation, {})(dispatch);
+ locationChanged(location, nextLocation, {}, "REPLACE")(dispatch);
expect(initSpy).not.toHaveBeenCalled();
expect(dispatch).not.toHaveBeenCalled();
@@ -108,11 +103,10 @@ describe("locationChanged", () => {
const location = loc({ pathname: "/question/1" });
const nextLocation = loc({
pathname: "/question/2",
- action: "POP",
state: null,
});
- locationChanged(location, nextLocation, {})(dispatch);
+ locationChanged(location, nextLocation, {}, "POP")(dispatch);
expect(initSpy).toHaveBeenCalledTimes(1);
expect(dispatchedAThunk(dispatch)).toBe(true);
@@ -122,11 +116,10 @@ describe("locationChanged", () => {
const location = loc({ pathname: "/question/1" });
const nextLocation = loc({
pathname: "/question/2",
- action: "POP",
state: { card: { id: 2 } },
});
- locationChanged(location, nextLocation, {})(dispatch);
+ locationChanged(location, nextLocation, {}, "POP")(dispatch);
expect(initSpy).not.toHaveBeenCalled();
expect(dispatchedAThunk(dispatch)).toBe(true);
@@ -134,9 +127,9 @@ describe("locationChanged", () => {
it("does nothing on a POP that did not change the url", () => {
const location = loc({ pathname: "/question/1" });
- const nextLocation = loc({ pathname: "/question/1", action: "POP" });
+ const nextLocation = loc({ pathname: "/question/1" });
- locationChanged(location, nextLocation, {})(dispatch);
+ locationChanged(location, nextLocation, {}, "POP")(dispatch);
expect(initSpy).not.toHaveBeenCalled();
expect(dispatch).not.toHaveBeenCalled();
diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
index 5407201e7c7..8fe9dae995b 100644
--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
@@ -50,7 +50,13 @@ import {
setUIControls,
} from "metabase/redux/query-builder";
import type { QueryBuilderUIControls, State } from "metabase/redux/store";
-import { type Location, push, useRoute, useRouter } from "metabase/router";
+import {
+ type Location,
+ push,
+ useNavigationType,
+ useRoute,
+ useRouter,
+} from "metabase/router";
import { getIsNavbarOpen } from "metabase/selectors/app";
import { getMetadata } from "metabase/selectors/metadata";
import { getSetting } from "metabase/selectors/settings";
@@ -343,6 +349,7 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
const { location, params } = useRouter();
const route = useRoute();
useFavicon({ favicon: props.pageFavicon ?? null });
+ const navigationType = useNavigationType();
const { data: fetchedTimelines, isSuccess: areTimelinesLoaded } =
useListTimelinesQuery({
include: "events",
@@ -544,9 +551,9 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
useEffect(() => {
if (previousLocation && location !== previousLocation) {
- locationChanged(previousLocation, location, params);
+ locationChanged(previousLocation, location, params, navigationType);
}
- }, [location, params, previousLocation, locationChanged]);
+ }, [location, params, previousLocation, navigationType, locationChanged]);
const [isShowingToaster, setIsShowingToaster] = useState(false);
diff --git a/frontend/src/metabase/redux/routing-contract.unit.spec.tsx b/frontend/src/metabase/redux/routing-contract.unit.spec.tsx
index 73ddfbd288d..61e098a5aa7 100644
--- a/frontend/src/metabase/redux/routing-contract.unit.spec.tsx
+++ b/frontend/src/metabase/redux/routing-contract.unit.spec.tsx
@@ -84,15 +84,16 @@ describe("routing transport contract", () => {
expect(location()?.state).toEqual({ preserveNavbarState: true });
});
- it("distinguishes push from replace via location.action", async () => {
+ it("push adds a history entry, replace does not", async () => {
const { location, navigate } = setup();
await navigate(push("/a"));
- expect(location()?.action).toBe("PUSH");
-
await navigate(replace("/b"));
expect(location()?.pathname).toBe("/b");
- expect(location()?.action).toBe("REPLACE");
+
+ // `/b` replaced `/a`, so going back lands on the entry before it.
+ await navigate(goBack());
+ expect(location()?.pathname).toBe("/");
});
it("goBack returns to the previous entry", async () => {
diff --git a/frontend/src/metabase/redux/store/mocks/location.ts b/frontend/src/metabase/redux/store/mocks/location.ts
index 2c986e63681..e397e646d6e 100644
--- a/frontend/src/metabase/redux/store/mocks/location.ts
+++ b/frontend/src/metabase/redux/store/mocks/location.ts
@@ -4,10 +4,8 @@ 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/route-guards/auth-guards.unit.spec.tsx b/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx
index 41a38f95657..8907be53404 100644
--- a/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx
+++ b/frontend/src/metabase/route-guards/auth-guards.unit.spec.tsx
@@ -52,10 +52,9 @@ describe("route-guards", () => {
});
const location = history!.getCurrentLocation();
- expect(location.query).toEqual(
- expect.objectContaining({ redirect: "/dashboard/123" }),
+ expect(new URLSearchParams(location.search).get("redirect")).toBe(
+ "/dashboard/123",
);
- expect(location.search).toContain("redirect");
});
});
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index d51897a691c..972d12bc51a 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -10,11 +10,12 @@ export * from "./RouterProvider";
export * from "./types";
export * from "./use-location";
export * from "./use-navigate";
+export * from "./use-navigation-type";
export * from "./use-params";
export * from "./use-router";
export * from "./use-search-params";
export { getRawBrowserHistory } from "./v7/blocking-history";
-export { queryToSearch, searchToQuery, toV3Location } from "./v7/location";
+export { queryToSearch, toFacadeLocation } from "./v7/location";
export {
createLocationMirror,
type LocationMirror,
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 1b0da848071..2ce0b88e04f 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -30,18 +30,6 @@ export type To = string | Partial<Path>;
*/
export type Action = "POP" | "PUSH" | "REPLACE";
-/**
- * The default parsed `query` shape: repeated keys become arrays, matching
- * history@3's parser that the `location.query` readers were written against.
- */
-export type DefaultQuery = Record<string, string | string[] | null | undefined>;
-
-/**
- * The parsed query object carried on a `Location`. The generic is the concrete
- * shape a call site knows its query to have (e.g. `Location<{ tab?: string }>`).
- */
-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 once those call
@@ -50,21 +38,16 @@ export type Query<T = DefaultQuery> = T;
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`) once
- * those call sites migrate off `query`/`action` (follow-up to DEV-2290).
+ * An entry in a history stack. Read the query string off `search`, either with
+ * the `useSearchParams` hook or by constructing a `URLSearchParams`.
*
* @see https://api.reactrouter.com/v7/interfaces/react-router.Location.html
*/
-export interface Location<Q = DefaultQuery> {
+export interface Location {
pathname: string;
search: string;
hash: string;
- query: Query<Q>;
state: LocationState;
- action: Action;
key: string;
}
@@ -96,10 +79,10 @@ type TransitionHook = (
* driver, the sync bridge, and the route-leave tests). Mirrors history@3's
* `History` so the v3 engine and the v7 navigator both satisfy it.
*/
-export interface History<Q = DefaultQuery> {
+export interface History {
listenBefore(hook: TransitionHook): () => void;
listen(listener: LocationListener): () => void;
- transitionTo(location: Location<Q>): void;
+ transitionTo(location: Location): void;
push(path: LocationDescriptor): void;
replace(path: LocationDescriptor): void;
go(n: number): void;
@@ -112,8 +95,8 @@ export interface History<Q = DefaultQuery> {
path?: LocationDescriptor,
action?: Action,
key?: string,
- ): Location<Q>;
- getCurrentLocation(): Location<Q>;
+ ): Location;
+ getCurrentLocation(): Location;
}
/**
@@ -209,9 +192,14 @@ export interface PlainRoute extends RouteProps {
/**
* A route-leave hook, v3's `setRouteLeaveHook` callback: it receives the
- * attempted destination and returns `false` to cancel the navigation.
+ * attempted destination and how it was reached, and returns `false` to cancel
+ * the navigation. The navigation type is a second argument rather than a field
+ * on the location, which carries only the URL parts.
*/
-export type RouteHook = (nextLocation?: Location) => unknown;
+export type RouteHook = (
+ nextLocation?: Location,
+ navigationType?: Action,
+) => unknown;
/**
* v3's imperative router, the `router` prop the facade injects. The v7
@@ -238,12 +226,10 @@ export interface InjectedRouter {
*
* `params` defaults to v3's non-optional string map (not the facade's optional
* `Params`), because the legacy route-prop readers were written against that and
- * treat matched params as always present. `Q` defaults to `any`, matching v3's
- * `Location<any>`, so the legacy `location.query` readers keep their loose typing
- * (tightened when the `state.routing` slice is thinned, DEV-2290).
+ * treat matched params as always present.
*/
-export interface WithRouterProps<P = Record<string, string>, Q = any> {
- location: Location<Q>;
+export interface WithRouterProps<P = Record<string, string>> {
+ location: Location;
params: P;
router: InjectedRouter;
routes: PlainRoute[];
diff --git a/frontend/src/metabase/router/use-location.ts b/frontend/src/metabase/router/use-location.ts
index 7e9154e2c99..c5706270f9a 100644
--- a/frontend/src/metabase/router/use-location.ts
+++ b/frontend/src/metabase/router/use-location.ts
@@ -6,9 +6,7 @@ import {
} 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
- * the route-prop call sites.
+ * react-router v7's `useLocation`.
*
* @see https://reactrouter.com/7.18.1/api/hooks/useLocation
*/
diff --git a/frontend/src/metabase/router/use-navigation-type.ts b/frontend/src/metabase/router/use-navigation-type.ts
new file mode 100644
index 00000000000..49a8bd42ad0
--- /dev/null
+++ b/frontend/src/metabase/router/use-navigation-type.ts
@@ -0,0 +1,13 @@
+import { useNavigationType as useV7NavigationType } from "react-router";
+
+import type { Action } from "./types";
+
+/**
+ * react-router v7's `useNavigationType`: the navigation that produced the
+ * current location. Replaces v3's `location.action`.
+ *
+ * @see https://reactrouter.com/7.18.1/api/hooks/useNavigationType
+ */
+export function useNavigationType(): Action {
+ return useV7NavigationType();
+}
diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsx
index cb6d2a51210..20947350656 100644
--- a/frontend/src/metabase/router/v7/RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx
@@ -4,7 +4,6 @@ import {
type To,
UNSAFE_RouteContext,
type NavigateFunction as V7NavigateFunction,
- useNavigationType,
useLocation as useV7Location,
useNavigate as useV7Navigate,
useParams as useV7Params,
@@ -22,7 +21,7 @@ import type {
} from "../types";
import { registerLeaveHook } from "./blocking-history";
-import { toV3Location } from "./location";
+import { toFacadeLocation } from "./location";
import { subscribeLocation, toNavigateArgs } from "./navigator";
// The facade route stub, plus the route's matched pathname so `setRouteLeaveHook`
@@ -43,7 +42,6 @@ export function RouterBridge({
}): JSX.Element {
const v7Location = useV7Location();
const navigate = useV7Navigate();
- const action = useNavigationType();
const v7Params = useV7Params();
// v7's `useParams` returns v7's readonly `Params`; the context wants v3's shape,
// which is structurally the same string map apart from the splat: v3 exposed the
@@ -87,8 +85,8 @@ export function RouterBridge({
);
const location = useMemo<HistoryLocation>(
- () => toV3Location(v7Location, action),
- [v7Location, action],
+ () => toFacadeLocation(v7Location),
+ [v7Location],
);
// v3 handed consumers a stable `router`, so effects keyed on it (notably the
diff --git a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
index 8248d41fa58..1592da47417 100644
--- a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
+++ b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx
@@ -38,7 +38,7 @@ export function SyncHistoryRouter({
}: PropsWithChildren<{
history: History;
basename?: string;
- onLocationChange?: (location: V7Location, action: NavigationType) => void;
+ onLocationChange?: (location: V7Location) => void;
}>): JSX.Element {
const [state, setState] = useState<{
action: NavigationType;
@@ -56,10 +56,10 @@ export function SyncHistoryRouter({
// Layout, not passive, so the router state is committed before the browser
// paints the click that triggered it.
useLayoutEffect(() => {
- onLocationChangeRef.current?.(history.location, history.action);
+ onLocationChangeRef.current?.(history.location);
return history.listen((update) => {
setState(update);
- onLocationChangeRef.current?.(update.location, update.action);
+ onLocationChangeRef.current?.(update.location);
});
}, [history]);
diff --git a/frontend/src/metabase/router/v7/V7RouterBridge.tsx b/frontend/src/metabase/router/v7/V7RouterBridge.tsx
index d7eb992a03a..e3a0e96e514 100644
--- a/frontend/src/metabase/router/v7/V7RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/V7RouterBridge.tsx
@@ -1,7 +1,6 @@
import { useEffect, useRef } from "react";
import {
type HistoryRouterProps,
- useNavigationType,
useLocation as useV7Location,
useNavigate as useV7Navigate,
} from "react-router";
@@ -32,7 +31,6 @@ export function V7RouterBridge({
}): null {
const navigate = useV7Navigate();
const location = useV7Location();
- const action = useNavigationType();
// Read through a ref so a new callback identity does not re-run the mirror for
// a location that has not changed.
@@ -50,8 +48,8 @@ export function V7RouterBridge({
if (history) {
return;
}
- onLocationChangeRef.current?.(location, action);
- }, [history, location, action]);
+ onLocationChangeRef.current?.(location);
+ }, [history, location]);
return null;
}
diff --git a/frontend/src/metabase/router/v7/blocking-history.ts b/frontend/src/metabase/router/v7/blocking-history.ts
index 7c1db752a1f..f5d82275ca8 100644
--- a/frontend/src/metabase/router/v7/blocking-history.ts
+++ b/frontend/src/metabase/router/v7/blocking-history.ts
@@ -6,9 +6,9 @@ import {
parsePath,
} from "react-router";
-import type { Location as HistoryLocation } from "../types";
+import type { Action, Location as HistoryLocation } from "../types";
-import { toV3Location } from "./location";
+import { toFacadeLocation } from "./location";
// react-router does not export the `History` interface directly, so pull it off
// the history prop of `unstable_HistoryRouter`, which is exactly the type the
@@ -17,9 +17,14 @@ type History = HistoryRouterProps["history"];
/**
* A route-leave hook, matching v3's `setRouteLeaveHook` callback: it receives
- * the attempted destination and returns `false` to cancel the navigation.
+ * the attempted destination and how it was reached, and returns `false` to
+ * cancel the navigation. The navigation type is a second argument rather than a
+ * field on the location, which carries only the URL parts on v7.
*/
-type LeaveHook = (nextLocation?: HistoryLocation) => unknown;
+type LeaveHook = (
+ nextLocation?: HistoryLocation,
+ navigationType?: Action,
+) => unknown;
interface Registration {
hook: LeaveHook;
@@ -79,7 +84,10 @@ function staysWithin(basePath: string | undefined, pathname: string): boolean {
return pathname === base || pathname.startsWith(`${base}/`);
}
-function isBlocked(nextLocation: HistoryLocation): boolean {
+function isBlocked(
+ nextLocation: HistoryLocation,
+ navigationType: Action,
+): boolean {
// Snapshot so a hook that unregisters mid-run cannot skip a sibling.
return [...registrations].some(({ hook, basePath }) => {
// Navigating within the guarded route is not leaving it, so the hook does
@@ -87,15 +95,11 @@ function isBlocked(nextLocation: HistoryLocation): boolean {
if (staysWithin(basePath, nextLocation.pathname)) {
return false;
}
- return hook(nextLocation) === false;
+ return hook(nextLocation, navigationType) === false;
});
}
-function toBlockedLocation(
- to: To,
- action: HistoryLocation["action"],
- state: unknown,
-): HistoryLocation {
+function toBlockedLocation(to: To, state: unknown): HistoryLocation {
const path = typeof to === "string" ? parsePath(to) : to;
const location: V7Location = {
pathname: path.pathname ?? "/",
@@ -104,7 +108,7 @@ function toBlockedLocation(
state: state ?? null,
key: "default",
};
- return toV3Location(location, action);
+ return toFacadeLocation(location);
}
/**
@@ -123,13 +127,13 @@ export function withBlocking(history: History): History {
let revertingPop = false;
const push: History["push"] = (to, state) => {
- if (!isBlocked(toBlockedLocation(to, "PUSH", state))) {
+ if (!isBlocked(toBlockedLocation(to, state), "PUSH")) {
history.push(to, state);
}
};
const replace: History["replace"] = (to, state) => {
- if (!isBlocked(toBlockedLocation(to, "REPLACE", state))) {
+ if (!isBlocked(toBlockedLocation(to, state), "REPLACE")) {
history.replace(to, state);
}
};
@@ -143,7 +147,7 @@ export function withBlocking(history: History): History {
}
const isBlockedPop =
update.action === "POP" &&
- isBlocked(toV3Location(update.location, "POP"));
+ isBlocked(toFacadeLocation(update.location), "POP");
if (isBlockedPop) {
// The browser already moved, so step forward to undo the back. One step
// covers the back button, the dominant leave case; a multi-step go is
diff --git a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts b/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
index 3ac363dba2c..40150b6eaec 100644
--- a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
+++ b/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
@@ -72,7 +72,7 @@ describe("withBlocking", () => {
expect(history.location.pathname).toBe("/a");
});
- it("hands the hook the attempted location with a PUSH action", () => {
+ it("hands the hook the attempted location and how it was reached", () => {
const history = setup();
const hook = jest.fn(() => false);
register(hook);
@@ -83,8 +83,8 @@ describe("withBlocking", () => {
expect.objectContaining({
pathname: "/b",
search: "?x=1",
- action: "PUSH",
}),
+ "PUSH",
);
});
diff --git a/frontend/src/metabase/router/v7/location-mirror.ts b/frontend/src/metabase/router/v7/location-mirror.ts
index b7cebe87385..308cd5e2825 100644
--- a/frontend/src/metabase/router/v7/location-mirror.ts
+++ b/frontend/src/metabase/router/v7/location-mirror.ts
@@ -1,15 +1,12 @@
-import type { NavigationType, Location as V7Location } from "react-router";
+import type { Location as V7Location } from "react-router";
import { LOCATION_CHANGE } from "../location-change";
import type { Location } from "../types";
-import { toV3Location } from "./location";
+import { toFacadeLocation } from "./location";
import { notifyLocationListeners } from "./navigator";
-export type LocationMirror = (
- location: V7Location,
- action: NavigationType,
-) => void;
+export type LocationMirror = (location: V7Location) => void;
/**
* The dispatch half of a redux store, narrowed to what the mirror needs. Taking
@@ -33,9 +30,9 @@ type DispatchLocationChange = (action: {
export function createLocationMirror(
dispatch: DispatchLocationChange,
): LocationMirror {
- return (location, action) => {
- const v3Location = toV3Location(location, action);
- dispatch({ type: LOCATION_CHANGE, payload: v3Location });
- notifyLocationListeners(v3Location);
+ return (location) => {
+ const facadeLocation = toFacadeLocation(location);
+ dispatch({ type: LOCATION_CHANGE, payload: facadeLocation });
+ notifyLocationListeners(facadeLocation);
};
}
diff --git a/frontend/src/metabase/router/v7/location.ts b/frontend/src/metabase/router/v7/location.ts
index 3ffdc2f8741..1ac1e202656 100644
--- a/frontend/src/metabase/router/v7/location.ts
+++ b/frontend/src/metabase/router/v7/location.ts
@@ -2,27 +2,9 @@ import type { Location as V7Location } from "react-router";
import type { Location as HistoryLocation } from "../types";
-/**
- * Parse a search string into v3's `location.query` object: repeated keys become
- * an array, an empty value stays `""`, matching history@3's default parser that
- * the `location.query` readers were written against.
- */
-export function searchToQuery(
- search: string,
-): Record<string, string | string[]> {
- const params = new URLSearchParams(search);
- const query: Record<string, string | string[]> = {};
- for (const key of new Set(params.keys())) {
- const values = params.getAll(key);
- query[key] = values.length > 1 ? values : values[0];
- }
- return 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.
+ * Repeated values become repeated keys. 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
@@ -51,22 +33,18 @@ export function queryToSearch(query: Record<string, unknown>): string {
}
/**
- * Build the v3-shaped `history` location the facade context and the
- * LOCATION_CHANGE payload expect from a v7 location plus the current navigation
- * type.
+ * Build the `Location` the facade context and the LOCATION_CHANGE payload expect
+ * from a v7 location. All that is left to normalize is `state`, which the legacy
+ * readers treat as absent when it is `undefined`.
*/
-export function toV3Location(
- location: V7Location,
- action: HistoryLocation["action"],
-): HistoryLocation {
+export function toFacadeLocation(location: V7Location): HistoryLocation {
return {
pathname: location.pathname,
search: location.search,
hash: location.hash,
- // v3 leaves state `undefined` when absent; v7 uses `null`.
+ // v3 left state `undefined` when absent; v7 uses `null`. The readers test
+ // for `undefined`, so normalize it here.
state: location.state ?? undefined,
key: location.key,
- query: searchToQuery(location.search),
- action,
};
}
diff --git a/frontend/src/metabase/router/v7/location.unit.spec.ts b/frontend/src/metabase/router/v7/location.unit.spec.ts
index 0819a03e855..af0bfa8b0df 100644
--- a/frontend/src/metabase/router/v7/location.unit.spec.ts
+++ b/frontend/src/metabase/router/v7/location.unit.spec.ts
@@ -1,4 +1,4 @@
-import { queryToSearch, searchToQuery } from "./location";
+import { queryToSearch } 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
@@ -38,20 +38,3 @@ describe("queryToSearch", () => {
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/v7-engine.unit.spec.tsx b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
index 0bdf96b9968..77d07bf6cf3 100644
--- a/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
+++ b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx
@@ -8,7 +8,7 @@ import {
useLocation,
useNavigate,
useParams,
- useRouter,
+ useSearchParams,
} from "metabase/router";
import { V7RouterTree } from "./RouterProviderV7";
@@ -26,14 +26,14 @@ function ThingPage() {
const { pathname, search } = useLocation();
const params = useParams();
const navigate = useNavigate();
- const { location } = useRouter();
+ const [searchParams] = useSearchParams();
return (
<div>
<span data-testid="pathname">{pathname}</span>
<span data-testid="search">{search}</span>
<span data-testid="thing-id">{params.thingId}</span>
- <span data-testid="query-tab">{String(location.query.tab)}</span>
+ <span data-testid="query-tab">{searchParams.get("tab")}</span>
<button onClick={() => navigate("/other")}>go absolute</button>
<button onClick={() => navigate("..")}>go up</button>
</div>
@@ -65,7 +65,7 @@ describe("v7 engine (facade over real react-router v7)", () => {
expect(screen.getByTestId("thing-id")).toHaveTextContent("42");
});
- it("exposes a v3-shaped location.query", () => {
+ it("exposes the search params through useSearchParams", () => {
setup("/things/42?tab=x");
expect(screen.getByTestId("query-tab")).toHaveTextContent("x");
});
diff --git a/frontend/src/metabase/search/containers/SearchApp.tsx b/frontend/src/metabase/search/containers/SearchApp.tsx
index f1a1a2b4f7b..f3695327a56 100644
--- a/frontend/src/metabase/search/containers/SearchApp.tsx
+++ b/frontend/src/metabase/search/containers/SearchApp.tsx
@@ -16,13 +16,10 @@ import {
SearchContextTypes,
SearchFilterKeys,
} from "metabase/common/search/constants";
-import type {
- SearchAwareLocation,
- URLSearchFilterQueryParams,
-} from "metabase/common/search/types";
+import type { URLSearchFilterQueryParams } from "metabase/common/search/types";
import { usePageTitle } from "metabase/hooks/use-page-title";
import { useDispatch } from "metabase/redux";
-import type { LocationDescriptorObject } from "metabase/router";
+import type { Location, LocationDescriptorObject } from "metabase/router";
import { push, queryToSearch, useRouter } from "metabase/router";
import { SearchSidebar } from "metabase/search/components/SearchSidebar";
import {
@@ -36,16 +33,14 @@ import { PAGE_SIZE } from "metabase/search/containers/constants";
import { Box, Group, Paper, Text } from "metabase/ui";
import type { SearchRequest } from "metabase-types/api";
-const getPageFromLocation = (location: SearchAwareLocation) => {
- const maybePage = location.query?.page
- ? parseInt(location.query.page, 10)
- : 0;
+const getPageFromLocation = (location: Location) => {
+ const page = new URLSearchParams(location.search).get("page");
+ const maybePage = page ? parseInt(page, 10) : 0;
return maybePage || 0;
};
export function SearchApp() {
- // Unjustified type cast. FIXME
- const location = useRouter().location as SearchAwareLocation;
+ const { location } = useRouter();
const dispatch = useDispatch();
usePageTitle(t`Search`);
diff --git a/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx b/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
index de096e5c540..e9d76d12c47 100644
--- a/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
+++ b/frontend/src/metabase/search/containers/SearchApp.unit.spec.tsx
@@ -195,7 +195,7 @@ describe("SearchApp", () => {
await userEvent.click(popover.getByRole("button", { name: "Apply" }));
const url = history.getCurrentLocation();
- expect(url.query.type).toEqual(model);
+ expect(new URLSearchParams(url.search).get("type")).toEqual(model);
},
);
});
diff --git a/frontend/src/metabase/transforms/pages/JobRunListPage/utils.ts b/frontend/src/metabase/transforms/pages/JobRunListPage/utils.ts
index 2b0e6c223ef..5e1b144655f 100644
--- a/frontend/src/metabase/transforms/pages/JobRunListPage/utils.ts
+++ b/frontend/src/metabase/transforms/pages/JobRunListPage/utils.ts
@@ -12,22 +12,27 @@ import type { JobRunSortOptions } from "./types";
export function getParsedParams(
location: Location,
): Urls.TransformJobRunListParams {
- const {
- page,
- status,
- "run-method": runMethod,
- "start-time": startTime,
- "sort-column": sortColumn,
- "sort-direction": sortDirection,
- } = location.query;
+ const searchParams = new URLSearchParams(location.search);
return {
- page: Urls.parseNumberParam(page),
- status: Urls.parseEnumParam(status, TRANSFORM_JOB_RUN_STATUSES),
- runMethod: Urls.parseEnumParam(runMethod, TRANSFORM_RUN_METHODS),
- startTime: Urls.parseStringParam(startTime),
- sortColumn: Urls.parseEnumParam(sortColumn, TRANSFORM_JOB_RUN_SORT_COLUMNS),
- sortDirection: Urls.parseEnumParam(sortDirection, SORT_DIRECTIONS),
+ page: Urls.parseNumberParam(searchParams.get("page")),
+ status: Urls.parseEnumParam(
+ searchParams.get("status"),
+ TRANSFORM_JOB_RUN_STATUSES,
+ ),
+ runMethod: Urls.parseEnumParam(
+ searchParams.get("run-method"),
+ TRANSFORM_RUN_METHODS,
+ ),
+ startTime: Urls.parseStringParam(searchParams.get("start-time")),
+ sortColumn: Urls.parseEnumParam(
+ searchParams.get("sort-column"),
+ TRANSFORM_JOB_RUN_SORT_COLUMNS,
+ ),
+ sortDirection: Urls.parseEnumParam(
+ searchParams.get("sort-direction"),
+ SORT_DIRECTIONS,
+ ),
};
}
diff --git a/frontend/src/metabase/transforms/pages/RunListPage/utils.ts b/frontend/src/metabase/transforms/pages/RunListPage/utils.ts
index 7104cd70406..5be6cbb3216 100644
--- a/frontend/src/metabase/transforms/pages/RunListPage/utils.ts
+++ b/frontend/src/metabase/transforms/pages/RunListPage/utils.ts
@@ -15,35 +15,34 @@ import type {
export function getParsedParams(
location: Location,
): Urls.TransformRunListParams {
- const {
- page,
- statuses,
- "transform-ids": transformIds,
- "transform-tag-ids": transformTagIds,
- "start-time": startTime,
- "end-time": endTime,
- "run-methods": runMethods,
- "sort-column": sortColumn,
- "sort-direction": sortDirection,
- } = location.query;
+ const searchParams = new URLSearchParams(location.search);
return {
- page: Urls.parseNumberParam(page),
- statuses: Urls.parseListParam(statuses, (v) =>
+ page: Urls.parseNumberParam(searchParams.get("page")),
+ statuses: Urls.parseListParam(searchParams.getAll("statuses"), (v) =>
Urls.parseEnumParam(v, TRANSFORM_RUN_STATUSES),
),
- transformIds: Urls.parseListParam(transformIds, Urls.parseNumberParam),
+ transformIds: Urls.parseListParam(
+ searchParams.getAll("transform-ids"),
+ Urls.parseNumberParam,
+ ),
transformTagIds: Urls.parseListParam(
- transformTagIds,
+ searchParams.getAll("transform-tag-ids"),
Urls.parseNumberParam,
),
- startTime: Urls.parseStringParam(startTime),
- endTime: Urls.parseStringParam(endTime),
- runMethods: Urls.parseListParam(runMethods, (v) =>
+ startTime: Urls.parseStringParam(searchParams.get("start-time")),
+ endTime: Urls.parseStringParam(searchParams.get("end-time")),
+ runMethods: Urls.parseListParam(searchParams.getAll("run-methods"), (v) =>
Urls.parseEnumParam(v, TRANSFORM_RUN_METHODS),
),
- sortColumn: Urls.parseEnumParam(sortColumn, TRANSFORM_RUN_SORT_COLUMNS),
- sortDirection: Urls.parseEnumParam(sortDirection, SORT_DIRECTIONS),
+ sortColumn: Urls.parseEnumParam(
+ searchParams.get("sort-column"),
+ TRANSFORM_RUN_SORT_COLUMNS,
+ ),
+ sortDirection: Urls.parseEnumParam(
+ searchParams.get("sort-direction"),
+ SORT_DIRECTIONS,
+ ),
};
}
diff --git a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.ts b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.ts
index 4edb6e43184..9241b843d9f 100644
--- a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.ts
+++ b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.ts
@@ -16,37 +16,33 @@ import type {
export function getParsedParams(
location: Location,
): Urls.TransformGraphRunListParams {
- const {
- page,
- types,
- statuses,
- "transform-ids": transformIds,
- "start-time": startTime,
- "end-time": endTime,
- "run-methods": runMethods,
- "sort-column": sortColumn,
- "sort-direction": sortDirection,
- } = location.query;
+ const searchParams = new URLSearchParams(location.search);
return {
- page: Urls.parseNumberParam(page),
- types: Urls.parseListParam(types, (v) =>
+ page: Urls.parseNumberParam(searchParams.get("page")),
+ types: Urls.parseListParam(searchParams.getAll("types"), (v) =>
Urls.parseEnumParam(v, TRANSFORM_GRAPH_RUN_TYPES),
),
- statuses: Urls.parseListParam(statuses, (v) =>
+ statuses: Urls.parseListParam(searchParams.getAll("statuses"), (v) =>
Urls.parseEnumParam(v, TRANSFORM_RUN_STATUSES),
),
- transformIds: Urls.parseListParam(transformIds, Urls.parseNumberParam),
- startTime: Urls.parseStringParam(startTime),
- endTime: Urls.parseStringParam(endTime),
- runMethods: Urls.parseListParam(runMethods, (v) =>
+ transformIds: Urls.parseListParam(
+ searchParams.getAll("transform-ids"),
+ Urls.parseNumberParam,
+ ),
+ startTime: Urls.parseStringParam(searchParams.get("start-time")),
+ endTime: Urls.parseStringParam(searchParams.get("end-time")),
+ runMethods: Urls.parseListParam(searchParams.getAll("run-methods"), (v) =>
Urls.parseEnumParam(v, TRANSFORM_RUN_METHODS),
),
sortColumn: Urls.parseEnumParam(
- sortColumn,
+ searchParams.get("sort-column"),
TRANSFORM_GRAPH_RUN_SORT_COLUMNS,
),
- sortDirection: Urls.parseEnumParam(sortDirection, SORT_DIRECTIONS),
+ sortDirection: Urls.parseEnumParam(
+ searchParams.get("sort-direction"),
+ SORT_DIRECTIONS,
+ ),
};
}
diff --git a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
index 2903c31f869..0bc84d70942 100644
--- a/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
+++ b/frontend/src/metabase/transforms/pages/TransformListPage/TransformListPage.tsx
@@ -119,7 +119,9 @@ export const TransformListPage = () => {
const { transformsDatabases = [], isLoadingDatabases } =
useTransformPermissions();
const targetCollectionId =
- Urls.extractEntityId(location.query?.collectionId) ?? null;
+ Urls.extractEntityId(
+ new URLSearchParams(location.search).get("collectionId") ?? undefined,
+ ) ?? null;
const hasScrolledRef = useRef(false);
const [searchQuery, setSearchQuery] = useState("");
const hasPythonTransformsFeature = useHasTokenFeature("transforms-python");
diff --git a/frontend/src/metabase/urls/utils.ts b/frontend/src/metabase/urls/utils.ts
index a11cccbbab4..c500c2de645 100644
--- a/frontend/src/metabase/urls/utils.ts
+++ b/frontend/src/metabase/urls/utils.ts
@@ -88,13 +88,20 @@ export function parseEnumParam<T extends string>(
return item != null ? item : undefined;
}
+/**
+ * An empty array means the param is absent (`URLSearchParams.getAll` returns one
+ * for a key that is not in the URL), so it parses to `undefined` the way `null`
+ * does, keeping "no filter" distinct from "empty filter".
+ */
export function parseListParam<T>(
value: unknown,
parseItem: (item: unknown) => T | undefined,
): T[] | undefined {
if (value != null) {
const array = Array.isArray(value) ? value : [value];
- return array.map(parseItem).filter((item) => item != null);
+ return array.length > 0
+ ? array.map(parseItem).filter((item) => item != null)
+ : undefined;
} else {
return undefined;
}
diff --git a/frontend/src/metabase/urls/utils.unit.spec.ts b/frontend/src/metabase/urls/utils.unit.spec.ts
index fb951698819..a77075dd963 100644
--- a/frontend/src/metabase/urls/utils.unit.spec.ts
+++ b/frontend/src/metabase/urls/utils.unit.spec.ts
@@ -125,4 +125,11 @@ describe("parseListParam", () => {
expect(parseListParam(null, parseStringParam)).toBeUndefined();
expect(parseListParam(undefined, parseStringParam)).toBeUndefined();
});
+
+ it("should return undefined for an absent search param", () => {
+ const params = new URLSearchParams("?other=a");
+ expect(
+ parseListParam(params.getAll("missing"), parseStringParam),
+ ).toBeUndefined();
+ });
});
diff --git a/frontend/src/metabase/utils/browser.ts b/frontend/src/metabase/utils/browser.ts
index ba85287e968..cd6120fbe3d 100644
--- a/frontend/src/metabase/utils/browser.ts
+++ b/frontend/src/metabase/utils/browser.ts
@@ -19,6 +19,24 @@ function parseQueryStringOptions(s: string) {
return options;
}
+export type SearchQuery = Record<string, string | string[]>;
+
+/**
+ * Parse a URL search string into a query object: a repeated key becomes an
+ * array, a valueless key stays `""`. For the call sites that hand a whole query
+ * bag to something else (dashboard parameter values, search filters, the command
+ * palette); read a named param off `URLSearchParams` instead where you can.
+ */
+export function parseSearchQuery(search: string): SearchQuery {
+ const params = new URLSearchParams(search);
+ const query: SearchQuery = {};
+ for (const key of new Set(params.keys())) {
+ const values = params.getAll(key);
+ query[key] = values.length > 1 ? values : values[0];
+ }
+ return query;
+}
+
export function isWebkit() {
const ua = navigator.userAgent || "";
diff --git a/frontend/src/metabase/utils/browser.unit.spec.ts b/frontend/src/metabase/utils/browser.unit.spec.ts
index c1e6a5ba32f..cec660cb85d 100644
--- a/frontend/src/metabase/utils/browser.unit.spec.ts
+++ b/frontend/src/metabase/utils/browser.unit.spec.ts
@@ -2,6 +2,7 @@ import { createMockMediaQueryList } from "__support__/ui";
import {
isTouchDevice,
parseHashOptions,
+ parseSearchQuery,
stringifyHashOptions,
} from "metabase/utils/browser";
@@ -113,6 +114,33 @@ describe("browser", () => {
});
});
+ describe("parseSearchQuery", () => {
+ it.each([
+ { input: "", expected: {}, name: "an empty search" },
+ { input: "?foo=bar", expected: { foo: "bar" }, name: "with '?'" },
+ { input: "foo=bar", expected: { foo: "bar" }, name: "without '?'" },
+ { input: "?foo", expected: { foo: "" }, name: "a valueless key" },
+ { input: "?foo=", expected: { foo: "" }, name: "an empty value" },
+ {
+ input: "?foo=a&foo=b",
+ expected: { foo: ["a", "b"] },
+ name: "a repeated key as an array",
+ },
+ {
+ input: "?foo=a&bar=b",
+ expected: { foo: "a", bar: "b" },
+ name: "several keys",
+ },
+ {
+ input: "?foo=next30days~",
+ expected: { foo: "next30days~" },
+ name: "an encoded value",
+ },
+ ])("should parse $name", ({ input, expected }) => {
+ expect(parseSearchQuery(input)).toEqual(expected);
+ });
+ });
+
describe("stringifyHashOptions", () => {
it.each([
{ input: { foo: "bar" }, expected: "foo=bar", name: "strings" },
diff --git a/frontend/src/metabase/visualizations/lib/open-url.ts b/frontend/src/metabase/visualizations/lib/open-url.ts
index 61242831031..177da921e33 100644
--- a/frontend/src/metabase/visualizations/lib/open-url.ts
+++ b/frontend/src/metabase/visualizations/lib/open-url.ts
@@ -4,8 +4,8 @@ import {
type LocationDescriptor,
type LocationDescriptorObject,
queryToSearch,
- searchToQuery,
} from "metabase/router";
+import { parseSearchQuery } from "metabase/utils/browser";
import {
clickLink,
getPathnameWithoutSubPath,
@@ -171,7 +171,7 @@ function getLocation(url: string): LocationDescriptor {
// 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)),
+ search: queryToSearch(parseSearchQuery(search)),
hash,
};
} catch {
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index 7087385bf46..3344c05c3a5 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -42,7 +42,6 @@ import {
createMockState,
} from "metabase/redux/store/mocks";
import {
- type Action,
type History,
type LocationDescriptor,
type MemoryTestHistory,
@@ -52,8 +51,8 @@ import {
createMemoryTestHistory,
createV7Navigator,
routerMiddleware,
+ toFacadeLocation,
toNavigateArgs,
- toV3Location,
} from "metabase/router";
import { getMetabaseCssVariables } from "metabase/styled-components/theme/css-variables";
import type { MantineThemeOverride } from "metabase/ui";
@@ -365,10 +364,7 @@ export function TestWrapper({
* keeps its type; it implements the subset they use.
*/
function createV3HistoryAdapter(history: MemoryTestHistory): History {
- const getCurrentLocation = () =>
- // v7 types `action` as its own `Action` enum; the values are the same
- // "POP"/"PUSH"/"REPLACE" strings the facade's `Action` union uses.
- toV3Location(history.location, history.action as Action);
+ const getCurrentLocation = () => toFacadeLocation(history.location);
const adapter = {
getCurrentLocation,
@@ -388,11 +384,7 @@ function createV3HistoryAdapter(history: MemoryTestHistory): History {
goForward: () => history.go(1),
listen: (
listener: (location: ReturnType<typeof getCurrentLocation>) => void,
- ) =>
- history.listen(({ location, action }) =>
- // Same enum-vs-union mismatch as in `getCurrentLocation` above.
- listener(toV3Location(location, action as Action)),
- ),
+ ) => history.listen(({ location }) => listener(toFacadeLocation(location))),
};
// The adapter implements the subset of v3's `History` the specs actually call,