Skip to content

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

GDGT-3380: Keep sessions search when opening a session row (#84766)

Egor Grushinb28f4b8a4efb
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.tsx
index 2d4d9489ee8..79777b9f344 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.tsx
@@ -51,7 +51,10 @@ export const SessionsPage = () => {
const navigate = useNavigate();
const { sessionId } = useParams<RouteParams>();
const { ref: containerRef, width: containerWidth } = useElementSize();
- const [urlState, { patchUrlState }] = useUrlState(location, urlStateConfig);
+ const [urlState, { patchUrlState, searchString }] = useUrlState(
+ location,
+ urlStateConfig,
+ );
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const clearSelection = useCallback(() => setRowSelection({}), []);
@@ -151,10 +154,10 @@ export const SessionsPage = () => {
id === undefined
? Urls.monitorSessions()
: Urls.monitorSessionDetail(id),
- search: location.search,
+ search: searchString,
});
},
- [navigate, location.search],
+ [navigate, searchString],
);
const handleSidebarClose = useCallback(
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 fe5ba7c098a..0767757d04d 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
@@ -1,10 +1,15 @@
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useEffectOnce, useLatest } from "react-use";
import _ from "underscore";
import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
import type { Location } from "metabase/router";
-import { queryToSearch, useNavigate } from "metabase/router";
+import {
+ getIsNavigationPending,
+ getRouterLocation,
+ queryToSearch,
+ useNavigate,
+} from "metabase/router";
import { parseSearchQuery } from "metabase/utils/browser";
import type { UrlStateQuery } from "./types";
@@ -23,11 +28,12 @@ type PatchUrlStateOptions = {
immediate?: boolean;
};
-type UrlStateActions<State extends BaseState> = {
+type UrlStateApi<State extends BaseState> = {
patchUrlState: (
patch: Partial<State>,
options?: PatchUrlStateOptions,
) => void;
+ searchString: string;
};
export const URL_UPDATE_DEBOUNCE_DELAY = 300;
@@ -39,7 +45,7 @@ export const URL_UPDATE_DEBOUNCE_DELAY = 300;
export function useUrlState<State extends BaseState>(
location: Location,
{ parse, serialize }: UrlStateConfig<State>,
-): [State, UrlStateActions<State>] {
+): [State, UrlStateApi<State>] {
const navigate = useNavigate();
const [state, setState] = useState(() =>
parse(parseSearchQuery(location.search)),
@@ -68,23 +74,39 @@ export function useUrlState<State extends BaseState>(
[],
);
+ const toSearchString = useCallback(
+ (state: State) => queryToSearch(serialize(state)),
+ [serialize],
+ );
+
const updateUrl = useCallback(
(state: State) => {
- const search = queryToSearch(serialize(state));
+ const routerLocationKey = getRouterLocation()?.key;
+ const hasNavigatedSinceRender =
+ routerLocationKey !== undefined && routerLocationKey !== location.key;
+ if (hasNavigatedSinceRender || getIsNavigationPending()) {
+ return;
+ }
+ const search = toSearchString(state);
// skip when the URL already carries this state, so adopting a URL below
// does not push it onto the history a second time
if (search !== location.search) {
navigate({ ...location, search });
}
},
- [location, serialize, navigate],
+ [location, toSearchString, navigate],
+ );
+
+ const searchString = useMemo(
+ () => toSearchString(state),
+ [toSearchString, state],
);
const updateUrlRef = useLatest(updateUrl);
const urlStateRef = useLatest(urlState);
useEffectOnce(function cleanInvalidQueryParams() {
- const search = queryToSearch(serialize(urlState));
+ const search = toSearchString(urlState);
// Replacing to the identical URL notifies the router, which re-renders every
// location consumer on the page for nothing.
if (search !== location.search) {
@@ -108,5 +130,5 @@ export function useUrlState<State extends BaseState>(
updateUrlRef.current(urlState);
}, [updateUrlRef, urlState]);
- return [state, { patchUrlState }];
+ return [state, { patchUrlState, searchString }];
}
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 7314af6d34e..f826a899340 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
@@ -1,9 +1,15 @@
import { createMockLocation } from "__support__/state";
import { act, renderHookWithProviders, waitFor } from "__support__/ui";
+import * as Router from "metabase/router";
import { type Location, useLocation } from "metabase/router";
+import { delay } from "metabase/utils/promise";
import type { QueryParam } from "./types";
-import { type UrlStateConfig, useUrlState } from "./use-url-state";
+import {
+ URL_UPDATE_DEBOUNCE_DELAY,
+ type UrlStateConfig,
+ useUrlState,
+} from "./use-url-state";
import { getFirstParamValue } from "./utils";
type UrlState = {
@@ -48,6 +54,10 @@ const setup = ({ location = createMockLocation() }: SetupOpts = {}) => {
};
describe("useUrlState", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
it("works with missing query params", () => {
const { result } = setup();
const [state] = result.current;
@@ -178,6 +188,54 @@ describe("useUrlState", () => {
expect(router?.location.search).toEqual("");
});
});
+
+ it("exposes the search for the patched state before the URL catches up", async () => {
+ const location = createLocation("?name=abc&score=123");
+ const { result, router } = setup({ location });
+
+ act(() => {
+ const [, { patchUrlState }] = result.current;
+ patchUrlState({ score: 456 });
+ });
+
+ const [, { searchString }] = result.current;
+ expect(searchString).toEqual("?name=abc&score=456");
+ expect(router?.location.search).toEqual("?name=abc&score=123");
+ await waitFor(() => {
+ expect(router?.location.search).toEqual("?name=abc&score=456");
+ });
+ });
+
+ it("does not write the URL while a navigation is pending", async () => {
+ const location = createLocation("?name=abc");
+ const { result, router } = setup({ location });
+ jest.spyOn(Router, "getIsNavigationPending").mockReturnValue(true);
+
+ act(() => {
+ const [, { patchUrlState }] = result.current;
+ patchUrlState({ score: 456 });
+ });
+
+ await act(() => delay(URL_UPDATE_DEBOUNCE_DELAY + 50));
+ expect(router?.location.search).toEqual("?name=abc");
+ });
+
+ it("does not write the URL after the router navigated away (GDGT-3380)", async () => {
+ const location = createLocation("?name=abc");
+ const { result, router } = setup({ location });
+ // a real navigation re-renders before the debounced write, so this is the only way to open the window
+ jest
+ .spyOn(Router, "getRouterLocation")
+ .mockReturnValue(createMockLocation({ key: "navigated-away" }));
+
+ act(() => {
+ const [, { patchUrlState }] = result.current;
+ patchUrlState({ score: 456 });
+ });
+
+ await act(() => delay(URL_UPDATE_DEBOUNCE_DELAY + 50));
+ expect(router?.location.search).toEqual("?name=abc");
+ });
});
function createLocation(search: string) {
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 62e7575982d..ad7792b8963 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -33,6 +33,7 @@ export { queryToSearch, toFacadeLocation } from "./location";
export { createLocationMirror, type LocationMirror } from "./location-mirror";
export {
getIsNavigationPending,
+ getRouterLocation,
navigate,
notifyLocationListeners,
subscribeLocation,
diff --git a/frontend/src/metabase/router/navigator.ts b/frontend/src/metabase/router/navigator.ts
index a7ff176233e..368c7d79bfa 100644
--- a/frontend/src/metabase/router/navigator.ts
+++ b/frontend/src/metabase/router/navigator.ts
@@ -1,5 +1,6 @@
import type {
DataRouter,
+ Location,
NavigateFunction,
NavigateOptions,
To,
@@ -80,6 +81,9 @@ export function getIsNavigationPending(): boolean {
);
}
+export const getRouterLocation = (): Location | undefined =>
+ currentRouter?.state.location;
+
export function setRouterNavigate(navigate: NavigateFunction | null): void {
currentNavigate = navigate;
if (!navigate) {