The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Author route paths in v7 syntax, shim to v3 (#78079)
Romeo Van Snicka9396323f509
diff --git a/enterprise/frontend/src/metabase-enterprise/table-editing/routes.tsx b/enterprise/frontend/src/metabase-enterprise/table-editing/routes.tsxindex e5d6ff0654d..6eb8af36294 100644--- a/enterprise/frontend/src/metabase-enterprise/table-editing/routes.tsx+++ b/enterprise/frontend/src/metabase-enterprise/table-editing/routes.tsx@@ -7,7 +7,7 @@ const RoutedEditTableDataContainer = withRouteProps(EditTableDataContainer);export function getRoutes() {return (<Route- path="databases/:dbId/tables/:tableId/edit(/:objectId)"+ path="databases/:dbId/tables/:tableId/edit/:objectId?"element={<RoutedEditTableDataContainer />}/>);diff --git a/frontend/src/metabase/router/route.tsx b/frontend/src/metabase/router/route.tsxindex 16bfff014b7..6f04206adea 100644--- a/frontend/src/metabase/router/route.tsx+++ b/frontend/src/metabase/router/route.tsx@@ -12,6 +12,7 @@ import {type RouteProps,createRoutes,} from "./react-router";+import { translatePatternToV3 } from "./translate-pattern";/*** Props accepted by the `<Route>` element. Adds react-router v7's `index` and@@ -64,11 +65,17 @@ export const Route: RouteConfigElement = Object.assign(// Rebuild the element as a raw v3 `<Route>` so v3's own builder turns it (and// its children) into a route object without dispatching back into this static.const { index, ...props } = element.props;+ // The tree is authored in v7 path syntax; translate to v3 so the v3 engine+ // matches it. A no-op for ordinary paths. Goes away with the v3 engine.+ const v3Props =+ typeof props.path === "string"+ ? { ...props, path: translatePatternToV3(props.path) }+ : props;// v3 copies our `element` prop onto the route config but `PlainRoute` does// not type it, so widen the result to read it below.- const [route] = createRoutes(createElement(ReactRouterRoute, props)) as [- (PlainRoute & { element?: ReactNode }) | undefined,- ];+ const [route] = createRoutes(+ createElement(ReactRouterRoute, v3Props),+ ) as [(PlainRoute & { element?: ReactNode }) | undefined];// Bridge `element` onto v3: render it through a `component` that publishes// the matched child on `<Outlet/>`'s context. The `element` stays on thediff --git a/frontend/src/metabase/router/translate-pattern.conformance.unit.spec.ts b/frontend/src/metabase/router/translate-pattern.conformance.unit.spec.tsnew file mode 100644index 00000000000..039dc1da0c9--- /dev/null+++ b/frontend/src/metabase/router/translate-pattern.conformance.unit.spec.ts@@ -0,0 +1,137 @@+import { matchPattern } from "react-router/lib/PatternUtils";+import { matchPath } from "react-router-v7";++import { translatePatternToV3 } from "./translate-pattern";++/**+ * Proves the v7->v3 translation preserves matching: for each route path (authored+ * in v7 syntax), the v3 matcher fed the translated pattern extracts the same+ * params from the same URL as the v7 matcher fed the original. This is what keeps+ * the live v3 engine correct while the tree is authored in v7 shape.+ */++type Case = {+ /** The route path as authored in the tree, in v7 syntax. */+ v7: string;+ urls: Array<[url: string, params: Record<string, string>]>;+};++// v3's splat param is `splat`; v7's is `*`, and v3 keeps a leading slash. An+// unmatched optional is `null` on v3, absent on v7. Normalize all of it away.+function normalize(params: Record<string, string | null | undefined>) {+ const out: Record<string, string> = {};+ for (const [rawKey, rawValue] of Object.entries(params)) {+ if (rawValue == null || rawValue === "") {+ continue;+ }+ const key = rawKey === "splat" ? "*" : rawKey;+ out[key] = key === "*" ? rawValue.replace(/^\//, "") : rawValue;+ }+ return out;+}++function v3Params(v7Pattern: string, url: string) {+ const match = matchPattern(translatePatternToV3(v7Pattern), url);+ if (!match || match.remainingPathname !== "") {+ throw new Error(+ `v3 pattern for "${v7Pattern}" did not fully match "${url}"`,+ );+ }+ const params: Record<string, string | null> = {};+ match.paramNames.forEach((name: string, index: number) => {+ params[name] = match.paramValues[index];+ });+ return normalize(params);+}++function v7Params(v7Pattern: string, url: string) {+ const rooted = v7Pattern.startsWith("/") ? v7Pattern : `/${v7Pattern}`;+ const match = matchPath({ path: rooted, end: true }, url);+ expect(match).not.toBeNull();+ return normalize(match!.params);+}++const CASES: Case[] = [+ {+ v7: "/admin/tools/notifications/:notificationId?",+ urls: [+ ["/admin/tools/notifications", {}],+ ["/admin/tools/notifications/7", { notificationId: "7" }],+ ],+ },+ {+ v7: "dashboard/:slug/:tabSlug?",+ urls: [+ ["/dashboard/5-sales", { slug: "5-sales" }],+ ["/dashboard/5-sales/2-tab", { slug: "5-sales", tabSlug: "2-tab" }],+ ],+ },+ {+ v7: "dashboard/:uuid/:tabSlug?",+ urls: [+ ["/dashboard/9a-uuid", { uuid: "9a-uuid" }],+ ["/dashboard/9a-uuid/3-tab", { uuid: "9a-uuid", tabSlug: "3-tab" }],+ ],+ },+ {+ v7: "/dashboard/:slug?",+ urls: [+ ["/dashboard", {}],+ ["/dashboard/5-sales", { slug: "5-sales" }],+ ],+ },+ {+ v7: "databases/:dbId/tables/:tableId/edit/:objectId?",+ urls: [+ ["/databases/1/tables/2/edit", { dbId: "1", tableId: "2" }],+ [+ "/databases/1/tables/2/edit/9",+ { dbId: "1", tableId: "2", objectId: "9" },+ ],+ ],+ },+ {+ v7: "question/entity/:entity_id/*",+ urls: [+ ["/question/entity/abc123", { entity_id: "abc123" }],+ ["/question/entity/abc123/tail", { entity_id: "abc123", "*": "tail" }],+ ],+ },+ {+ v7: "collection/entity/:entity_id/*",+ urls: [["/collection/entity/xY9", { entity_id: "xY9" }]],+ },+ {+ v7: "files/*",+ urls: [+ ["/files", {}],+ ["/files/a/b", { "*": "a/b" }],+ ],+ },+];++describe("translatePatternToV3 conformance (v7 matchPath vs v3 matchPattern)", () => {+ it.each(CASES)("$v7", ({ v7, urls }) => {+ for (const [url, expected] of urls) {+ const fromV3 = v3Params(v7, url);+ const fromV7 = v7Params(v7, url);+ expect(fromV3).toMatchObject(expected);+ expect(fromV7).toMatchObject(expected);+ expect(fromV3).toEqual(fromV7);+ }+ });+});++describe("translatePatternToV3", () => {+ it.each([+ ["dashboard/:slug/:tabSlug?", "dashboard/:slug(/:tabSlug)"],+ ["/dashboard/:slug?", "/dashboard(/:slug)"],+ ["question/entity/:entity_id/*", "question/entity/:entity_id(**)"],+ ["files/*", "files(/**)"],+ ["/collections/:collectionId", "/collections/:collectionId"],+ ["*", "*"],+ ["/admin/databases", "/admin/databases"],+ ])("translates %s -> %s", (v7, expected) => {+ expect(translatePatternToV3(v7)).toBe(expected);+ });+});diff --git a/frontend/src/metabase/router/translate-pattern.ts b/frontend/src/metabase/router/translate-pattern.tsnew file mode 100644index 00000000000..a7a522d9aeb--- /dev/null+++ b/frontend/src/metabase/router/translate-pattern.ts@@ -0,0 +1,28 @@+/**+ * Translate a react-router v7 route `path` into the equivalent v3 pattern.+ *+ * The route tree is authored in v7 syntax (the migration target). While the v3+ * engine is still live, the facade's `Route` builder runs each path through this+ * so v3 keeps matching exactly as before; the v7 engine uses the paths as-is.+ * Throwaway: deleted with the v3 engine in Phase 4, leaving a v7-native tree.+ *+ * It is a strict no-op for ordinary paths (no `?`, no `/*`), so only the handful+ * of routes using v7-only syntax are ever rewritten:+ *+ * - optional segment: `/:tabSlug?` -> `(/:tabSlug)`+ * - a param's splat tail: `:entity_id/*` -> `:entity_id(**)`+ * - a static splat tail: `files/*` -> `files(/**)`+ *+ * A bare `*` / `/*` catch-all is valid in both engines and is left untouched.+ */+export function translatePatternToV3(v7Pattern: string): string {+ return (+ v7Pattern+ // Optional dynamic segment.+ .replace(/\/(:[A-Za-z0-9_]+)\?/g, "(/$1)")+ // A param followed by a splat (entity-id links).+ .replace(/(:[A-Za-z0-9_]+)\/\*/g, "$1(**)")+ // A static segment followed by a trailing splat.+ .replace(/([A-Za-z0-9_]+)\/\*$/g, "$1(/**)")+ );+}diff --git a/frontend/src/metabase/routes-public.tsx b/frontend/src/metabase/routes-public.tsxindex 1fb4d5b8a3c..f519682c09a 100644--- a/frontend/src/metabase/routes-public.tsx+++ b/frontend/src/metabase/routes-public.tsx@@ -23,7 +23,7 @@ export const getRoutes = () => {element={<RoutedPublicOrEmbeddedQuestion />}/><Route- path="dashboard/:uuid(/:tabSlug)"+ path="dashboard/:uuid/:tabSlug?"element={<RoutedPublicOrEmbeddedDashboardPage />}/><Route path="document/:uuid" element={<RoutedPublicDocument />} />diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsxindex 17ab88443b7..7a0265375ca 100644--- a/frontend/src/metabase/routes.tsx+++ b/frontend/src/metabase/routes.tsx@@ -166,7 +166,7 @@ export const getRoutes = (store: AppStore) => {</Route><Route- path="collection/entity/:entity_id(**)"+ path="collection/entity/:entity_id/*"element={createEntityIdRedirect({parametersToTranslate: [{@@ -210,7 +210,7 @@ export const getRoutes = (store: AppStore) => {</Route><Route- path="dashboard/entity/:entity_id(**)"+ path="dashboard/entity/:entity_id/*"element={createEntityIdRedirect({parametersToTranslate: [{@@ -237,7 +237,7 @@ export const getRoutes = (store: AppStore) => {<Route path="/question"><Route- path="/question/entity/:entity_id(**)"+ path="/question/entity/:entity_id/*"element={createEntityIdRedirect({parametersToTranslate: [{