Skip to content

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

Adopt v7 navigation semantics, drop the v3 parity guards (#78653)

Romeo Van Snickac2f1ead3679
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 b5ab3ec7589..f054bd07cfe 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,5 +1,6 @@
import { useCallback, useEffect, useState } from "react";
import { useEffectOnce, useLatest } from "react-use";
+import _ from "underscore";
import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
import { useDispatch } from "metabase/redux";
@@ -46,8 +47,12 @@ export function useUrlState<State extends BaseState>(
const updateUrlRef = useLatest(updateUrl);
useEffectOnce(function cleanInvalidQueryParams() {
- const newLocation = { ...location, query: serialize(urlState) };
- dispatch(replace(newLocation));
+ 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)) {
+ dispatch(replace({ ...location, query }));
+ }
});
useEffect(() => {
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
index 10c5ded13b3..765568aea75 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
@@ -121,8 +121,11 @@ export const DashboardApp = () => {
}),
);
}
- const hash = stringifyHashOptions(options);
- await dispatch(replace({ ...location, hash: hash ? "#" + hash : "" }));
+ const hashString = stringifyHashOptions(options);
+ const hash = hashString ? "#" + hashString : "";
+ if (hash !== location.hash) {
+ await dispatch(replace({ ...location, hash }));
+ }
} catch (error) {
// 400: provided entity id format is invalid.
if (
diff --git a/frontend/src/metabase/dashboard/hooks/use-location-sync.ts b/frontend/src/metabase/dashboard/hooks/use-location-sync.ts
index 21aa8f06d0d..13efbed0ff7 100644
--- a/frontend/src/metabase/dashboard/hooks/use-location-sync.ts
+++ b/frontend/src/metabase/dashboard/hooks/use-location-sync.ts
@@ -80,13 +80,13 @@ export const useLocationSync = <
};
const hashString = stringifyHashOptions(updatedOptions);
+ const hash = hashString ? "#" + hashString : "";
- dispatch(
- replace({
- ...location,
- hash: hashString ? "#" + hashString : "",
- }),
- );
+ // The effect reads `location` and replaces it, so a replace that lands on
+ // the same URL would re-enter it through the resulting location change.
+ if (hash !== location.hash) {
+ dispatch(replace({ ...location, hash }));
+ }
}
}, [
dispatch,
diff --git a/frontend/src/metabase/dashboard/hooks/use-location-sync.unit.spec.tsx b/frontend/src/metabase/dashboard/hooks/use-location-sync.unit.spec.tsx
new file mode 100644
index 00000000000..b542ac2fb6b
--- /dev/null
+++ b/frontend/src/metabase/dashboard/hooks/use-location-sync.unit.spec.tsx
@@ -0,0 +1,73 @@
+import { useRef, useState } from "react";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import type { Location } from "metabase/router";
+import { Route, useLocation } from "metabase/router";
+
+import { useLocationSync } from "./use-location-sync";
+
+function TestDashboard() {
+ // The hook takes the legacy compat `Location`, which adds `query` and `action`
+ // on top of what `useLocation` returns. It only reads `hash`, so the narrower
+ // location stands in for the route prop the dashboard passes.
+ const location = useLocation() as Location;
+ const renderCount = useRef(0);
+ renderCount.current += 1;
+
+ const [isFullscreen, setIsFullscreen] = useState(false);
+ const [refreshPeriod, setRefreshPeriod] = useState<number | null>(null);
+
+ useLocationSync<boolean>({
+ key: "fullscreen",
+ value: isFullscreen,
+ onChange: (value) => setIsFullscreen(value ?? false),
+ location,
+ });
+
+ useLocationSync<number | null>({
+ key: "refresh",
+ value: refreshPeriod,
+ onChange: setRefreshPeriod,
+ location,
+ });
+
+ return (
+ <div>
+ <span data-testid="render-count">{renderCount.current}</span>
+ <span data-testid="url">{`${location.pathname}${location.hash}`}</span>
+ <span data-testid="fullscreen">{String(isFullscreen)}</span>
+ </div>
+ );
+}
+
+const setup = (initialRoute: string) =>
+ renderWithProviders(
+ <Route path="/dashboard/1" element={<TestDashboard />} />,
+ {
+ withRouter: true,
+ initialRoute,
+ },
+ );
+
+describe("useLocationSync", () => {
+ it("settles instead of looping replaces when the url already matches", async () => {
+ setup("/dashboard/1");
+
+ expect(await screen.findByTestId("url")).toHaveTextContent("/dashboard/1");
+ expect(Number(screen.getByTestId("render-count").textContent)).toBeLessThan(
+ 10,
+ );
+ });
+
+ it("settles when the hash carries a non-default value", async () => {
+ setup("/dashboard/1#fullscreen=true");
+
+ expect(await screen.findByTestId("fullscreen")).toHaveTextContent("true");
+ expect(screen.getByTestId("url")).toHaveTextContent(
+ "/dashboard/1#fullscreen",
+ );
+ expect(Number(screen.getByTestId("render-count").textContent)).toBeLessThan(
+ 10,
+ );
+ });
+});
diff --git a/frontend/src/metabase/documents/components/DocumentPage.tsx b/frontend/src/metabase/documents/components/DocumentPage.tsx
index e069e1bc526..17477767161 100644
--- a/frontend/src/metabase/documents/components/DocumentPage.tsx
+++ b/frontend/src/metabase/documents/components/DocumentPage.tsx
@@ -479,6 +479,9 @@ export const DocumentPage = () => {
usePageTitle(documentData?.name || t`New document`, { titleIndex: 1 });
+ // A "New document" click from `/document/new` targets the URL we are already
+ // on, so nothing unmounts. v7 mints a fresh `location.key` for it (the click
+ // resolves as a replace), and that key is what marks the re-entry.
const isLeaveConfirmModalOpen = useMemo(
() =>
hasUnsavedChanges() &&
diff --git a/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsx b/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsx
index 0eea08a2110..4a2bb4d7a32 100644
--- a/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsx
+++ b/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsx
@@ -5,7 +5,7 @@ import {
setupCommentEndpoints,
setupDocumentEndpoints,
} from "__support__/server-mocks";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
import { Route } from "metabase/router";
import { createMockDocument } from "metabase-types/api/mocks";
@@ -33,6 +33,18 @@ const setup = () => {
);
};
+const setupNewDocument = () => {
+ setupBookmarksEndpoints([]);
+
+ return renderWithProviders(
+ <Route path="/document/:entityId" element={<DocumentPage />} />,
+ {
+ withRouter: true,
+ initialRoute: "/document/new",
+ },
+ );
+};
+
const getDocumentTitle = async () =>
await screen.findByRole("textbox", { name: /document title/i });
@@ -63,4 +75,19 @@ describe("Document Page", () => {
).not.toBeInTheDocument(),
);
});
+
+ it("warns about unsaved changes only once a navigation lands back on /document/new", async () => {
+ const { history } = setupNewDocument();
+
+ await userEvent.type(await getDocumentTitle(), "Draft");
+
+ expect(screen.queryByTestId("leave-confirmation")).not.toBeInTheDocument();
+
+ // The "New document" menu item links to the URL we are already on, which v7
+ // resolves as a replace. The page stays mounted, so the fresh location is
+ // what tells it the user asked to start over.
+ act(() => history?.replace("/document/new"));
+
+ expect(await screen.findByTestId("leave-confirmation")).toBeInTheDocument();
+ });
});
diff --git a/frontend/src/metabase/router/router-link.tsx b/frontend/src/metabase/router/router-link.tsx
index 54182ad0702..370ba1e6e35 100644
--- a/frontend/src/metabase/router/router-link.tsx
+++ b/frontend/src/metabase/router/router-link.tsx
@@ -109,7 +109,6 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>(
{...navRest}
to={v7To}
state={state}
- replace={false}
ref={linkRef}
end={onlyActiveOnIndex}
className={({ isActive }) =>
@@ -124,12 +123,6 @@ export const RouterLink = forwardRef<HTMLAnchorElement, Props>(
);
}
- // v7's `<Link>` silently downgrades a click to a `replace` when the target
- // equals the current URL. v3 always pushed, and call sites rely on it: the
- // "New document" menu item links to `/document/new` from `/document/new`,
- // and the unsaved-changes prompt keys off the new location. Push always.
- return (
- <V7Link {...rest} to={v7To} state={state} replace={false} ref={linkRef} />
- );
+ return <V7Link {...rest} to={v7To} state={state} ref={linkRef} />;
},
);
diff --git a/frontend/src/metabase/router/router-link.unit.spec.tsx b/frontend/src/metabase/router/router-link.unit.spec.tsx
index 6ade781fbfd..92232f8d059 100644
--- a/frontend/src/metabase/router/router-link.unit.spec.tsx
+++ b/frontend/src/metabase/router/router-link.unit.spec.tsx
@@ -1,6 +1,6 @@
import userEvent from "@testing-library/user-event";
-import { renderWithProviders, screen } from "__support__/ui";
+import { act, renderWithProviders, screen } from "__support__/ui";
import { Link, Outlet, Route, useLocation, useNavigate } from "metabase/router";
function Home() {
@@ -84,14 +84,16 @@ describe("RouterLink", () => {
});
// v7's `<Link>` downgrades a click to a `replace` when the target equals the
- // current URL, which leaves the location key untouched. v3 always pushed, and
- // the documents page shows its unsaved-changes prompt when the key changes.
- it("pushes a new entry when linking to the current url", async () => {
- renderWithProviders(tree, {
+ // current URL, so the entry is reused rather than stacked. The navigation is
+ // still observable: the location gets a fresh key, which is what the documents
+ // page keys its unsaved-changes prompt off.
+ it("replaces the entry when linking to the current url, with a new location key", async () => {
+ const { history } = renderWithProviders(tree, {
withRouter: true,
- initialRoute: "/other",
+ initialRoute: "/",
});
+ await userEvent.click(screen.getByRole("link", { name: "go" }));
await screen.findByTestId("other");
const keyBefore = screen.getByTestId("location-key").textContent;
@@ -100,6 +102,11 @@ describe("RouterLink", () => {
expect(screen.getByTestId("location-key")).not.toHaveTextContent(
String(keyBefore),
);
+
+ // The second click reused the entry instead of stacking one, so a single
+ // step back lands on the page we came from.
+ await act(() => history?.goBack());
+ expect(await screen.findByTestId("location")).toHaveTextContent("/");
});
it("applies activeClassName to the link that matches the route", async () => {
diff --git a/frontend/src/metabase/router/v7/blocking-history.ts b/frontend/src/metabase/router/v7/blocking-history.ts
index 9227876dddf..7c1db752a1f 100644
--- a/frontend/src/metabase/router/v7/blocking-history.ts
+++ b/frontend/src/metabase/router/v7/blocking-history.ts
@@ -107,18 +107,6 @@ function toBlockedLocation(
return toV3Location(location, action);
}
-function isSameUrl(
- to: To,
- current: { pathname: string; search: string; hash: string },
-): boolean {
- const path = typeof to === "string" ? parsePath(to) : to;
- return (
- (path.pathname ?? current.pathname) === current.pathname &&
- (path.search ?? "") === current.search &&
- (path.hash ?? "") === current.hash
- );
-}
-
/**
* Wrap a history so a registered leave hook can cancel navigation, restoring the
* v3 `setRouteLeaveHook` behavior on the declarative v7 engine. react-router
@@ -141,14 +129,6 @@ export function withBlocking(history: History): History {
};
const replace: History["replace"] = (to, state) => {
- // v3/history@3 did not notify listeners when replacing to the current URL, so
- // effects that sync state into the URL by replacing the location they just
- // read stayed stable. v7's `v5Compat` history notifies on every replace,
- // which loops those effects (e.g. the dashboard's `useLocationSync`). Skip the
- // redundant replace to keep the v3 behavior.
- if (isSameUrl(to, history.location)) {
- return;
- }
if (!isBlocked(toBlockedLocation(to, "REPLACE", state))) {
history.replace(to, state);
}
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 a2045c5dcfe..3ac363dba2c 100644
--- a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
+++ b/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts
@@ -49,16 +49,19 @@ describe("withBlocking", () => {
expect(history.location.pathname).toBe("/b");
});
- it("does not notify listeners when replacing to the current URL", () => {
+ // history@3 stayed silent here, so v3 call sites could replace the location they
+ // had just read. v7 notifies on every replace, and the call sites skip the
+ // redundant navigation themselves.
+ it("notifies listeners when replacing to the current URL", () => {
const history = setup(["/a?x=1"]);
const listener = jest.fn();
history.listen(listener);
history.replace("/a?x=1");
- expect(listener).not.toHaveBeenCalled();
+ expect(listener).toHaveBeenCalledTimes(1);
history.replace("/b");
- expect(listener).toHaveBeenCalledTimes(1);
+ expect(listener).toHaveBeenCalledTimes(2);
});
it("blocks a replace while a hook returns false", () => {