Skip to content

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

Drop the last v3 parity behaviours in metabase/router (#79294)

Romeo Van Snick8f68857a6720
diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsx
index 8206220ecb8..d83f66f9bd3 100644
--- a/frontend/src/metabase/admin/routes.tsx
+++ b/frontend/src/metabase/admin/routes.tsx
@@ -125,13 +125,13 @@ export const getRoutes = (
<Route
path="database/:databaseId/schema/:schemaId/table/:tableId/settings"
element={redirect(
- "database/:databaseId/schema/:schemaId/table/:tableId",
+ "../database/:databaseId/schema/:schemaId/table/:tableId",
)}
/>
<Route
path="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId/:section"
element={redirect(
- "database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId",
+ "../database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId",
)}
/>
</Route>
diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx
index 5e7ace20bc1..c9936ae4117 100644
--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx
@@ -267,7 +267,7 @@ async function setup({
<Route
path="database/:databaseId/schema/:schemaId/table/:tableId"
element={redirect(
- "database/:databaseId/schema/:schemaId/table/:tableId/details",
+ "../database/:databaseId/schema/:schemaId/table/:tableId/details",
)}
/>
<Route
diff --git a/frontend/src/metabase/data-studio/data-model/routes.tsx b/frontend/src/metabase/data-studio/data-model/routes.tsx
index 0cf55d7407b..b424519a145 100644
--- a/frontend/src/metabase/data-studio/data-model/routes.tsx
+++ b/frontend/src/metabase/data-studio/data-model/routes.tsx
@@ -74,7 +74,7 @@ export function getDataStudioMetadataRoutes(IsAdmin: ComponentType) {
<Route
path="database/:databaseId/schema/:schemaId/table/:tableId"
element={redirect(
- "database/:databaseId/schema/:schemaId/table/:tableId/details",
+ "../database/:databaseId/schema/:schemaId/table/:tableId/details",
)}
/>
<Route
@@ -88,13 +88,13 @@ export function getDataStudioMetadataRoutes(IsAdmin: ComponentType) {
<Route
path="database/:databaseId/schema/:schemaId/table/:tableId/settings"
element={redirect(
- "database/:databaseId/schema/:schemaId/table/:tableId/details",
+ "../database/:databaseId/schema/:schemaId/table/:tableId/details",
)}
/>
<Route
path="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId/:section"
element={redirect(
- "database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId",
+ "../database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId",
)}
/>
</>
diff --git a/frontend/src/metabase/models/routes.tsx b/frontend/src/metabase/models/routes.tsx
index 600460fed0d..7dcecbb66c7 100644
--- a/frontend/src/metabase/models/routes.tsx
+++ b/frontend/src/metabase/models/routes.tsx
@@ -21,9 +21,9 @@ export const getRoutes = () => {
</Route>
<Route path=":rowId" element={<ModelDetailPage />} />
<Route index element={redirect("actions")} />
- <Route path="usage" element={redirect("actions")} />
- <Route path="schema" element={redirect("actions")} />
- <Route path="*" element={redirect("actions")} />
+ <Route path="usage" element={redirect("../actions")} />
+ <Route path="schema" element={redirect("../actions")} />
+ <Route path="*" element={redirect("../actions")} />
</Route>
);
};
diff --git a/frontend/src/metabase/router/Navigate.tsx b/frontend/src/metabase/router/Navigate.tsx
deleted file mode 100644
index 6f04152e2b6..00000000000
--- a/frontend/src/metabase/router/Navigate.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useEffect } from "react";
-import { useLocation, useNavigate } from "react-router";
-
-import type { To } from "./types";
-
-export interface NavigateProps {
- to: To;
- replace?: boolean;
- state?: unknown;
-}
-
-/**
- * react-router v7's `<Navigate>`: navigates to `to` on mount, and again whenever
- * `to`/`replace`/`state` change. Defaults to a push, pass `replace` to replace
- * the current history entry.
- *
- * @see https://reactrouter.com/7.18.1/api/components/Navigate
- */
-export function Navigate({ to, replace = false, state }: NavigateProps): null {
- const navigate = useNavigate();
- // A mounted `<Navigate>` re-asserts its target when the location moves out
- // from under it, so going back lands forward again. That used to fall out of
- // `navigate`'s identity churning per location, which only the declarative
- // `useNavigate` does: inside a data router it is stable across navigations.
- // Depend on the pathname directly so the behavior does not rest on which
- // variant is in play.
- const { pathname } = useLocation();
-
- // Key the effect on the serialized path (always string-valued, so safe to
- // stringify) so an equal `to` object recreated each render does not
- // re-navigate. `state` stays raw in the deps and is passed by reference, both
- // matching v7's <Navigate>.
- const jsonTo = JSON.stringify(to);
-
- useEffect(() => {
- navigate(to, { replace, state });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [navigate, pathname, jsonTo, replace, state]);
-
- return null;
-}
diff --git a/frontend/src/metabase/router/Navigate.unit.spec.tsx b/frontend/src/metabase/router/Navigate.unit.spec.tsx
index 633af683c4e..832830fa218 100644
--- a/frontend/src/metabase/router/Navigate.unit.spec.tsx
+++ b/frontend/src/metabase/router/Navigate.unit.spec.tsx
@@ -2,17 +2,15 @@ import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
-import { Route } from "metabase/router";
+import { Navigate, Route } from "metabase/router";
-import { Navigate } from "./Navigate";
-
-// Stable references: `<Navigate>` keeps `state` raw in its effect deps (like v7),
-// so a fresh object literal each render would re-navigate and loop.
+// Stable references: `<Navigate>` keeps `state` raw in its effect deps, so a
+// fresh object literal each render would re-navigate and loop.
const HOME_STATE = { from: "home" };
const RICH_STATE = { when: new Date(0), n: NaN };
describe("router/Navigate", () => {
- it("pushes to the destination on mount, re-asserting it on back", async () => {
+ it("pushes to the destination on mount, and stays put when the location moves back", async () => {
const Host = () => <Navigate to="/dest" />;
const { history } = renderWithProviders(
<Route path="*" element={<Host />} />,
@@ -26,11 +24,12 @@ describe("router/Navigate", () => {
expect(history?.getCurrentLocation().pathname).toBe("/dest"),
);
- // Like v7: `navigate`'s identity changes with each navigation, so a mounted
- // <Navigate> re-fires on the way back and snaps forward to its target again.
+ // The catch-all route keeps this <Navigate> mounted across the navigation,
+ // and its target has not changed, so going back does not re-assert it. Every
+ // call site redirects with `replace`, which leaves nothing to go back to.
act(() => history?.goBack());
await waitFor(() =>
- expect(history?.getCurrentLocation().pathname).toBe("/dest"),
+ expect(history?.getCurrentLocation().pathname).toBe("/home"),
);
});
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 83f07d23c33..32794e41358 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -1,4 +1,5 @@
export {
+ Navigate,
Outlet,
Route,
useLocation,
@@ -9,7 +10,6 @@ export {
} from "react-router";
export * from "./middleware";
export * from "./navigation";
-export * from "./Navigate";
export * from "./redirect";
export * from "./router-link";
export * from "./to-route-objects";
diff --git a/frontend/src/metabase/router/location.ts b/frontend/src/metabase/router/location.ts
index 1d6645c0783..4d60924498e 100644
--- a/frontend/src/metabase/router/location.ts
+++ b/frontend/src/metabase/router/location.ts
@@ -6,10 +6,9 @@ import type { Location as HistoryLocation } from "./types";
* Serialize a query object into the `search` string a navigation target carries.
* 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
- * order is incidental, and the URL is user visible and asserted against, so the
- * order has to stay stable rather than follow insertion.
+ * Keys are sorted so the URL is deterministic. Call sites build the query from
+ * an object whose key order is incidental, and these URLs are user visible and
+ * asserted against, so the order must not follow insertion.
*/
export function queryToSearch(query: Record<string, unknown>): string {
const params = new URLSearchParams();
@@ -25,9 +24,9 @@ export function queryToSearch(query: Record<string, unknown>): string {
params.append(key, String(item));
}
}
- // `URLSearchParams` matches history@3 apart from `~`, which it escapes and
- // history@3 left alone. Both write a space as `+`. These URLs are user visible
- // and asserted against, so a date filter has to read `next30days~`.
+ // `~` separates the two ends of a date filter range, and those URLs are shared
+ // and asserted against, so a date filter has to read `next30days~` rather than
+ // the `next30days%7E` that `URLSearchParams` writes.
const search = params.toString().replace(/%7E/gi, "~");
return search ? `?${search}` : "";
}
diff --git a/frontend/src/metabase/router/location.unit.spec.ts b/frontend/src/metabase/router/location.unit.spec.ts
index af0bfa8b0df..831d5c94ea1 100644
--- a/frontend/src/metabase/router/location.unit.spec.ts
+++ b/frontend/src/metabase/router/location.unit.spec.ts
@@ -16,15 +16,15 @@ describe("queryToSearch", () => {
expect(queryToSearch({})).toBe("");
});
- // history@3 stringified with `query-string`, which sorts keys. The URL is user
- // visible and asserted against, so the order must not follow insertion.
+ // Call sites build the query object in whatever order suits them, and the URL
+ // is user visible and asserted against, so the order must not follow insertion.
it("sorts keys regardless of insertion order", () => {
expect(queryToSearch({ state: "AK", city: "" })).toBe("?city=&state=AK");
expect(queryToSearch({ city: "", state: "AK" })).toBe("?city=&state=AK");
});
- // history@3 wrote a space as `+` but left `~` literal, and both show up in URLs
- // the app asserts on (a date filter reads `next30days~`).
+ // `~` separates the two ends of a date filter range, so it has to survive into
+ // shared links: a date filter reads `next30days~`, not `next30days%7E`.
it("writes a space as `+` and leaves `~` literal", () => {
expect(queryToSearch({ date_filter: "next30days~" })).toBe(
"?date_filter=next30days~",
diff --git a/frontend/src/metabase/router/redirect.tsx b/frontend/src/metabase/router/redirect.tsx
index a1823ebacb1..b5f54262010 100644
--- a/frontend/src/metabase/router/redirect.tsx
+++ b/frontend/src/metabase/router/redirect.tsx
@@ -1,51 +1,15 @@
-import { useContext, useState } from "react";
-import { UNSAFE_RouteContext, useLocation, useParams } from "react-router";
-
-import { Navigate } from "./Navigate";
-
-type RouteParams = Record<string, string | undefined>;
-
-/**
- * Interpolate a route pattern's `:params` and `*` splat with the matched values,
- * replacing v3's `formatPattern`. Params are re-encoded, matching v3, so a
- * segment that arrived encoded (`1%3APUBLIC`) stays encoded rather than doubling
- * the path. Only the pattern syntax the app uses (`:name`, `*`) is handled; v3's
- * optional groups are gone from the route tree.
- */
-function formatPattern(pattern: string, params: RouteParams): string {
- return pattern
- .replace(/:([A-Za-z0-9_]+)\??/g, (_, name) =>
- encodeURIComponent(params[name] ?? ""),
- )
- .replace(/\*/g, () => params["*"] ?? "");
-}
-
-/**
- * The matched pathname of the parent of the route this redirect renders in.
- * A relative `to` resolves against it, which is where v3's `<Redirect>` resolved
- * from and is one route shallower than v7 would resolve a relative `<Navigate>`.
- *
- * Read off the route context rather than `useMatches`, which is data-router only.
- */
-function useParentPathname(): string {
- const { matches } = useContext(UNSAFE_RouteContext);
- return matches.at(-2)?.pathname ?? "/";
-}
+import { useState } from "react";
+import { Navigate, generatePath, useLocation, useParams } from "react-router";
function RedirectRoute({ to }: { to: string }): JSX.Element {
- const parentPathname = useParentPathname();
const params = useParams();
const location = useLocation();
// Resolve the target once, from the match this redirect was rendered into.
// The match updates as soon as the redirect fires, so a later render (before
- // this component unmounts) would resolve a relative `to` against the
- // already-changed, deeper location. v3's <Redirect> computed its target once
- // in `onEnter`, so freeze it here to match.
+ // this component unmounts) would interpolate the already-changed params.
const [target] = useState(() => ({
- pathname: to.startsWith("/")
- ? formatPattern(to, params)
- : parentPathname.replace(/\/*$/, "/") + formatPattern(to, params),
+ pathname: generatePath(to, params),
search: location.search,
state: location.state,
}));
@@ -60,11 +24,13 @@ function RedirectRoute({ to }: { to: string }): JSX.Element {
}
/**
- * Reproduces react-router v3's `<Redirect>` as a v7-style redirecting route
- * element. Used as `<Route path="x" element={redirect("y")} />`, it interpolates
- * `:params` and the `*` splat into `to`, resolves a relative `to` against the
- * parent route, and preserves the current query string and history state
- * (dropping the hash, as v3 did).
+ * A redirecting route element, used as `<Route path="x" element={redirect("y")} />`.
+ * It interpolates the matched `:params` and the `*` splat into `to`, and carries
+ * the current query string and history state over. The hash is dropped.
+ *
+ * A relative `to` resolves the way react-router resolves a relative `<Navigate>`,
+ * against the route this element renders in, so `..` steps up one route. An index
+ * route contributes no path, so its target is already parent relative.
*/
export function redirect(to: string): JSX.Element {
return <RedirectRoute to={to} />;
diff --git a/frontend/src/metabase/router/redirect.unit.spec.tsx b/frontend/src/metabase/router/redirect.unit.spec.tsx
index f8034b644c9..bee19058505 100644
--- a/frontend/src/metabase/router/redirect.unit.spec.tsx
+++ b/frontend/src/metabase/router/redirect.unit.spec.tsx
@@ -61,10 +61,10 @@ describe("router/redirect", () => {
);
});
- it("resolves a relative target against the parent of the `from` match", async () => {
+ it("resolves a `..` target against the parent route", async () => {
const history = mountRoutes(
<Route path="collection" element={<Parent />}>
- <Route path="archive" element={redirect("trash")} />
+ <Route path="archive" element={redirect("../trash")} />
</Route>,
"/collection/archive",
);
@@ -77,7 +77,10 @@ describe("router/redirect", () => {
it("interpolates params into a relative target", async () => {
const history = mountRoutes(
<Route path="browse" element={<Parent />}>
- <Route path=":dbId/:slug" element={redirect("databases/:dbId/:slug")} />
+ <Route
+ path=":dbId/:slug"
+ element={redirect("../databases/:dbId/:slug")}
+ />
</Route>,
"/browse/5/orders",
);
@@ -89,9 +92,9 @@ describe("router/redirect", () => {
);
});
- it("resolves a relative target under a multi-segment `from`", async () => {
+ it("steps a whole route per `..`, not a single segment", async () => {
const from = "table/:tableId/field/:fieldId/:section";
- const to = "table/:tableId/field/:fieldId";
+ const to = "../table/:tableId/field/:fieldId";
const history = mountRoutes(
<Route path="model" element={<Parent />}>
<Route path={from} element={redirect(to)} />
@@ -106,9 +109,9 @@ describe("router/redirect", () => {
);
});
- it("resolves against the route tree, re-encoding params like v3", async () => {
+ it("re-encodes an interpolated param", async () => {
const from = "database/:databaseId/schema/:schemaId/table/:tableId";
- const to = `${from}/details`;
+ const to = `../${from}/details`;
const history = mountRoutes(
<Route path="data-studio/data" element={<Parent />}>
<Route path={from} element={redirect(to)} />
@@ -117,8 +120,8 @@ describe("router/redirect", () => {
"/data-studio/data/database/1/schema/1%3APUBLIC/table/2",
);
- // v3's formatPattern re-encodes the interpolated param, so the target keeps
- // the encoded schema segment rather than doubling the path.
+ // `useParams` hands back a decoded param, so `generatePath` re-encodes it and
+ // the target keeps the encoded schema segment rather than doubling the path.
await waitFor(() =>
expect(history?.getCurrentLocation().pathname).toBe(
"/data-studio/data/database/1/schema/1%3APUBLIC/table/2/details",
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 05e4a8a422d..153507c8fe3 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -172,7 +172,7 @@ export const getRoutes = (store: AppStore): RouteObject[] => [
{ path: "search", element: <SearchApp /> },
// Send historical /archive route to trash - can remove in v52
- { path: "archive", element: redirect("trash") },
+ { path: "archive", element: redirect("../trash") },
{ path: "trash", element: <TrashCollectionLanding /> },
{
@@ -359,7 +359,7 @@ export const getRoutes = (store: AppStore): RouteObject[] => [
{ path: ":dbIdAndSlug", element: <LegacyBrowseRedirect /> },
{
path: ":dbId/schema/:schemaName",
- element: redirect("databases/:dbId/schema/:schemaName"),
+ element: redirect("../databases/:dbId/schema/:schemaName"),
},
],
},