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
Delete the react-router v3 engine (#78305)
Romeo Van Snick24220fe19136
diff --git a/bun.lock b/bun.lockindex 81634b98daa..b6db8c32891 100644--- a/bun.lock+++ b/bun.lock@@ -67,7 +67,6 @@"@tiptap/starter-kit": "^3.2.0","@tiptap/suggestion": "^3.2.0","@types/js-yaml": "^4.0.9",- "@types/react-router": "3.0.27","@uiw/react-codemirror": "^4.23.6","@visx/axis": "^3.10.1","@visx/clip-path": "^3.3.0",@@ -102,7 +101,6 @@"formik": "^2.4.5","frimousse": "^0.3.0","fuse.js": "^7.1.0",- "history": "3","html2canvas-pro": "^2.0.2","icepick": "2.4.0","iframe-resizer": "~4.3.2",@@ -146,7 +144,6 @@"react-qr-code": "^2.0.15","react-redux": "^9.1.2","react-resizable": "^3.1.3",- "react-router": "3","react-transition-group": "^4.4.5","react-use": "^17.5.1","react-virtualized": "9.22.6",@@ -381,7 +378,7 @@"raf": "^3.4.0","react-docgen-typescript-plugin": "^1.0.6","react-refresh": "^0.14.2",- "react-router-v7": "npm:[email protected]",+ "react-router": "7.18.1","reg-cli": "^0.17.7","semver": "^7.6.3","shadow-cljs": "^3.3.5",@@ -2011,8 +2008,6 @@"@types/react-resizable": ["@types/[email protected]", "", { "dependencies": { "@types/react": "*" } }, "sha512-+QguN9CDfC1lthq+4noG1fkxh8cqkV2Fv/Mu3mdknCCBiwwNLecnBdk1MmNNN7uJpT23Nx/aVkYsbt5NuWouFw=="],- "@types/react-router": ["@types/[email protected]", "", { "dependencies": { "@types/history": "^3", "@types/react": "*" } }, "sha512-Sq4bfTZ8TuHFTHXyzA3tu/BTGm/d4B8CwtOK4qOyJNoJMkY87qMOazkBizMHNpszVR1+kYOCNLjPdh/wAD7ESw=="],-"@types/react-textarea-autosize": ["@types/[email protected]", "", { "dependencies": { "@types/react": "*" } }, "sha512-cTf8tCem0c8A7CERYbTuF+bRFaqYu7N7HLCa6ZhUhDx8XnUsTpGx5udMWljt87JpciUKuUkImKPEsy6kcKhrcQ=="],"@types/react-transition-group": ["@types/[email protected]", "", { "dependencies": { "@types/react": "*" } }, "sha512-juKD/eiSM3/xZYzjuzH6ZwpP+/lejltmiS3QEzV/vmb/Q8+HfDmxu+Baga8UEMGBqV88Nbg4l2hY/K2DkyaLLA=="],@@ -2725,8 +2720,6 @@"create-hmac": ["[email protected]", "", { "dependencies": { "cipher-base": "^1.0.3", "create-hash": "^1.1.0", "inherits": "^2.0.1", "ripemd160": "^2.0.0", "safe-buffer": "^5.0.1", "sha.js": "^2.4.8" } }, "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg=="],- "create-react-class": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.3.1", "object-assign": "^4.1.1" } }, "sha512-QZv4sFWG9S5RUvkTYWbflxeZX+JG7Cz0Tn33rQBJ+WFQTqTfUTjMjiv9tnfXazjsO5r0KhPs+AqCjyrQX6h2ng=="],-"crelt": ["[email protected]", "", {}, "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g=="],"cron-expression-validator": ["[email protected]", "", {}, "sha512-g0osBTdp+1ryDw2vzlG6UpDPaa4fO94ZChF2R0lEnRurbuUEL74XEVX7xZJ13m4Mq/gb3ni6UQu8+Oqt+eocsw=="],@@ -3445,8 +3438,6 @@"headers-polyfill": ["[email protected]", "", {}, "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ=="],- "history": ["[email protected]", "", { "dependencies": { "invariant": "^2.2.1", "loose-envify": "^1.2.0", "query-string": "^4.2.2", "warning": "^3.0.0" } }, "sha1-/O3M6PEpdTcVRdc1RhAzV5ptrpw="],-"hmac-drbg": ["[email protected]", "", { "dependencies": { "hash.js": "^1.0.3", "minimalistic-assert": "^1.0.0", "minimalistic-crypto-utils": "^1.0.1" } }, "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE="],"hoist-non-react-statics": ["[email protected]", "", { "dependencies": { "react-is": "^16.7.0" } }, "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw=="],@@ -4697,8 +4688,6 @@"qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],- "query-string": ["[email protected]", "", { "dependencies": { "object-assign": "^4.1.0", "strict-uri-encode": "^1.0.0" } }, "sha1-u7aTucqRXCMlFbIosaArYJBD2+s="],-"querystring": ["[email protected]", "", {}, "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA="],"querystring-es3": ["[email protected]", "", {}, "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM="],@@ -4781,9 +4770,7 @@"react-resizable": ["[email protected]", "", { "dependencies": { "prop-types": "15.x", "react-draggable": "^4.5.0" }, "peerDependencies": { "react": ">= 16.3", "react-dom": ">= 16.3" } }, "sha512-liJBNayhX7qA4tBJiBD321FDhJxgGTJ07uzH5zSORXoE8h7PyEZ8mLqmosST7ppf6C4zUsbd2gzDMmBCfFp9Lw=="],- "react-router": ["[email protected]", "", { "dependencies": { "create-react-class": "^15.5.1", "history": "^3.0.0", "hoist-non-react-statics": "^3.3.2", "invariant": "^2.2.1", "loose-envify": "^1.2.0", "prop-types": "^15.7.2", "react-is": "^16.13.0", "warning": "^3.0.0" } }, "sha512-nlxtQE8B22hb/JxdaslI1tfZacxFU8x8BJryXOnR2RxB4vc01zuHYAHAIgmBkdk1kzXaA25hZxK6KAH/+CXArw=="],-- "react-router-v7": ["[email protected]", "", { "dependencies": { "cookie": "^1.0.1", "set-cookie-parser": "^2.6.0" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" }, "optionalPeers": ["react-dom"] }, "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg=="],+ "react-router": ["[email protected]", "", { "dependencies": { "cookie": "^1.0.1", "set-cookie-parser": "^2.6.0" }, "peerDependencies": { "react": ">=18", "react-dom": ">=18" }, "optionalPeers": ["react-dom"] }, "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg=="],"react-style-singleton": ["[email protected]", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" } }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],@@ -5165,8 +5152,6 @@"strict-event-emitter": ["[email protected]", "", {}, "sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ=="],- "strict-uri-encode": ["[email protected]", "", {}, "sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM="],-"string-argv": ["[email protected]", "", {}, "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q=="],"string-length": ["[email protected]", "", { "dependencies": { "strip-ansi": "^7.1.0" } }, "sha512-1U361pxZHEQ+FeSjzqRpV+cu2vTzYeWeafXFLykiFlv4Vc0n3njgU8HrMbyik5uwm77naWMuVG8fhEF+Ovb1Kg=="],@@ -5551,8 +5536,6 @@"walker": ["[email protected]", "", { "dependencies": { "makeerror": "1.0.12" } }, "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ=="],- "warning": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha1-MuU3fLVy3kqwR1O9+IIcAe1gW3w="],-"watchpack": ["[email protected]", "", { "dependencies": { "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.1.2" } }, "sha512-Zn5uXdcFNIA1+1Ei5McRd+iRzfhENPCe7LeABkJtNulSxjma+l7ltNx55BWZkRlwRnpOgHqxnjyaDgJnNXnqzg=="],"watskeburt": ["[email protected]", "", { "bin": { "watskeburt": "dist/run-cli.js" } }, "sha512-g9CXukMjazlJJVQ3OHzXsnG25KFYgSgKMIyoJrD8ggr0DbS9UNF7OzIqWmmKKBMedkxj3T01uqEaGnn+y7QhMA=="],@@ -7039,9 +7022,7 @@"react-remove-scroll-bar/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],- "react-router/react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],-- "react-router-v7/cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],+ "react-router/cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],"react-style-singleton/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/EditTenantModal.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/EditTenantModal.tsxindex 1bd97bcd740..e6d8bd2f1a0 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/EditTenantModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/tenants/containers/EditTenantModal/EditTenantModal.tsx@@ -1,11 +1,11 @@import { useMemo } from "react";-import type { Params } from "react-router/lib/Router";import { t } from "ttag";import _ from "underscore";import { skipToken } from "metabase/api";import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";import { useToast } from "metabase/common/hooks";+import type { Params } from "metabase/router";import { Modal } from "metabase/ui";import {useGetTenantQuery,diff --git a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsxindex 4baabe57d3e..0c7584c8c93 100644--- a/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/tenants/index.tsx@@ -167,12 +167,7 @@ export function initializePlugin() {</Route></Route><Route path=":tenantId" element={<TenantsListingApp />}>- {modalRoute(- "edit",- // @ts-expect-error - params prop can't be inferred- EditTenantModal,- { noWrap: true },- )}+ {modalRoute("edit", EditTenantModal, { noWrap: true })}{modalRoute("deactivate",// @ts-expect-error - params prop can't be inferreddiff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsxindex 2d799f770d2..210349d95b4 100644--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx@@ -1,6 +1,6 @@import type { AnchorHTMLAttributes, MouseEvent, ReactNode } from "react";-import { browserHistory } from "metabase/router";+import { getRawBrowserHistory } from "metabase/router";import { getBasename } from "./DataAppRouter";@@ -15,10 +15,8 @@ export interface DataAppLinkProps extends Omit</*** Internal-only navigation link inside a data app.*- * Deliberately does NOT delegate to react-router 3's `<Link>` —- * v3 components use deprecated React APIs (`getDefaultProps`,- * `childContextTypes`) that emit dev-mode warnings and will be removed- * in React 19.+ * Renders a plain anchor rather than the router's `<Link>`: a data app is+ * mounted outside the app's route tree, so it has no router context to read.*/export const DataAppLink = ({to,@@ -58,7 +56,7 @@ export const DataAppLink = ({}event.preventDefault();- browserHistory.push(href);+ getRawBrowserHistory().push(href);};return (diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts b/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.tsindex fcc1d6d06ff..ffb192e3c07 100644--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts@@ -1,4 +1,4 @@-import { browserHistory } from "metabase/router";+import { getRawBrowserHistory } from "metabase/router";import { DataAppRouter, getBasename } from "./DataAppRouter";@@ -8,12 +8,13 @@ export { useDataAppLocation } from "./useDataAppLocation";/*** Imperative routing surface exposed to the SDK bundle's public API.- * The bundle never depends on a router library directly — it only relies- * on this `{ getBasename, navigate, subscribe }` shape, backed by the- * `browserHistory` singleton's function-based API.+ * The bundle never depends on a router library directly, it only relies on this+ * `{ getBasename, navigate, subscribe }` shape, backed by the browser history the+ * data app drives its iframe URL with.*/export const dataAppRouting = {getBasename,- navigate: (to: string) => browserHistory.push(getBasename() + to),- subscribe: (callback: () => void) => browserHistory.listen(callback),+ navigate: (to: string) => getRawBrowserHistory().push(getBasename() + to),+ subscribe: (callback: () => void) =>+ getRawBrowserHistory().listen(() => callback()),};diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts b/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.tsindex 7ce38764b85..866b4f75f06 100644--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useState } from "react";-import { browserHistory } from "metabase/router";+import { getRawBrowserHistory } from "metabase/router";import { getBasename } from "./DataAppRouter";@@ -31,10 +31,9 @@ export const useDataAppLocation = (): {const [pathname, setPathname] = useState(() => computeSubPath(basename));useEffect(() => {- // `browserHistory.listen` fires for every navigation — `<Link>` clicks,- // imperative `push` calls, and browser back/forward. One subscription- // covers all of them.- return browserHistory.listen(() => {+ // `listen` fires for every navigation: `<Link>` clicks, imperative `push`+ // calls, and browser back/forward. One subscription covers all of them.+ return getRawBrowserHistory().listen(() => {setPathname(computeSubPath(basename));});}, [basename]);@@ -43,7 +42,7 @@ export const useDataAppLocation = (): {(to: string) => {// `to` is bundle-relative (e.g. "/customers/42"). The real URL is// `basename + to`.- browserHistory.push(basename + to);+ getRawBrowserHistory().push(basename + to);},[basename],);diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.unit.spec.tsxnew file mode 100644index 00000000000..15d4059ebe1--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.unit.spec.tsx@@ -0,0 +1,20 @@+import { act, renderHook } from "@testing-library/react";++import { useDataAppLocation } from "./useDataAppLocation";++// The data-app bundle mounts no router, so this navigation runs on the dedicated+// browser history `getRawBrowserHistory()` returns, not the app's router history.+// Regression guard: when it read the app router history (null outside a router),+// every `navigate` was a silent no-op.+describe("useDataAppLocation", () => {+ it("navigate() updates the sub-path and the iframe URL", () => {+ const { result } = renderHook(() => useDataAppLocation());++ act(() => {+ result.current.navigate("/orders/42");+ });++ expect(result.current.pathname).toBe("/orders/42");+ expect(window.location.pathname).toBe("/orders/42");+ });+});diff --git a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsxindex 1d62ce56918..da7b1e518c3 100644--- a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx+++ b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPageDrilldown.unit.spec.tsx@@ -15,7 +15,6 @@ import {import DataPermissionsPage from "metabase/admin/permissions/pages/DataPermissionsPage/DataPermissionsPage";import { GroupsPermissionsPage } from "metabase/admin/permissions/pages/GroupDataPermissionsPage/GroupsPermissionsPage";import { Route, withRouteProps } from "metabase/router";-import type { RouterEngine } from "metabase/router/engine";import { createMockGroup } from "metabase-types/api/mocks/group";import { createSampleDatabase } from "metabase-types/api/mocks/presets";@@ -42,7 +41,7 @@ const GROUPS_PERMISSIONS_PATHS = ["group/:groupId/database/:databaseId/schema/:schemaName",];-const setup = (routerEngine: RouterEngine) => {+const setup = () => {setupDatabasesEndpoints([TEST_DATABASE]);setupPermissionsGraphEndpoints(TEST_GROUPS, [TEST_DATABASE]);setupGroupsEndpoint(TEST_GROUPS);@@ -67,7 +66,6 @@ const setup = (routerEngine: RouterEngine) => {</Route>,{withRouter: true,- routerEngine,initialRoute: `/admin/permissions/data/group/2`,},);@@ -79,22 +77,19 @@ const tableRowCount = () =>// Clicking a database name is a `<Link>` used as a button (onClick, no `to`).// On v7 the engine-aware link must not perform its own navigation, or it clobbers// the push the click handler dispatches and the drill-down never happens.-describe.each<RouterEngine>(["v3", "v7"])(- "GroupsPermissionsPage drill-down on the %s engine",- (routerEngine) => {- it("shows the tables after drilling into a database", async () => {- setup(routerEngine);- await waitForLoaderToBeRemoved();+describe("GroupsPermissionsPage drill-down", () => {+ it("shows the tables after drilling into a database", async () => {+ setup();+ await waitForLoaderToBeRemoved();- // Database-level view: one row for Sample Database (plus header row).- const dbRow = await screen.findByText("Sample Database");- expect(tableRowCount()).toBe(2);+ // Database-level view: one row for Sample Database (plus header row).+ const dbRow = await screen.findByText("Sample Database");+ expect(tableRowCount()).toBe(2);- await userEvent.click(dbRow);+ await userEvent.click(dbRow);- // Table-level view: a row per table in the sample database.- expect(await screen.findByText("Orders")).toBeInTheDocument();- expect(tableRowCount()).toBe(TEST_TABLES.length + 1);- });- },-);+ // Table-level view: a row per table in the sample database.+ expect(await screen.findByText("Orders")).toBeInTheDocument();+ expect(tableRowCount()).toBe(TEST_TABLES.length + 1);+ });+});diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.jsindex 13008bab774..2d04e9b904a 100644--- a/frontend/src/metabase/app.js+++ b/frontend/src/metabase/app.js@@ -23,7 +23,6 @@ import "metabase/plugins/builtin";// Set CSP nonce for dynamic style injection (e.g. CodeMirror)import "metabase/utils/csp";-import { createHistory } from "history";import { DragDropContextProvider } from "react-dnd";import { createPortal } from "react-dom";import { createRoot } from "react-dom/client";@@ -38,47 +37,29 @@ import { MetabotProvider } from "metabase/metabot/context";import { PLUGIN_APP_INIT_FUNCTIONS } from "metabase/plugins";import { MetabaseReduxProvider } from "metabase/redux";import { refreshSiteSettings } from "metabase/redux/settings";-import {- getRouterEngine,- syncHistoryWithStore,- useRouterHistory,-} from "metabase/router";import { createV7Navigator } from "metabase/router/v7/navigator";import { getUserId } from "metabase/selectors/user";import { GlobalStyles } from "metabase/styled-components/containers/GlobalStyles";import { PortalContainer } from "metabase/ui";import { EmotionCacheProvider } from "metabase/ui/components/theme/EmotionCacheProvider";-import { getBasename, setBasename } from "metabase/utils/basename";+import { setBasename } from "metabase/utils/basename";import { captureConsoleErrors } from "metabase/utils/errors";import { initMetaplow } from "metabase/utils/metaplow";import { initTracing, rotateTraceId } from "metabase/utils/otel";import MetabaseSettings from "metabase/utils/settings";import { registerVisualizations } from "metabase/visualizations/register";-import { HistoryProvider } from "./history";import { RouterProvider } from "./router";import { getStore } from "./store";import { OverlayStackProvider } from "./ui/components/overlays/overlay-stack";setBasename(window.MetabaseRoot);-// The v3 engine drives navigation through a `history@3` instance; the v7 engine-// owns its own history and only needs a navigator adapter for redux. Kept for-// instant rollback via the `use-v7-router` flag.-const isV7Router = getRouterEngine() === "v7";-const browserHistory = isV7Router- ? undefined- : // eslint-disable-next-line react-hooks/rules-of-hooks- useRouterHistory(createHistory)({ basename: getBasename() });-initializePlugins();function _init(reducers, getRoutes, callback) {- const store = getStore(reducers, browserHistory ?? createV7Navigator());+ const store = getStore(reducers, createV7Navigator());const routes = getRoutes(store);- const syncedHistory = browserHistory- ? syncHistoryWithStore(browserHistory, store)- : undefined;createSnowplowTracker(() => getUserId(store.getState()));initMetaplow({@@ -89,30 +70,23 @@ function _init(reducers, getRoutes, callback) {// Uses bootstrap data so it's available before the first API call.if (window.MetabaseBootstrap?.["tracing-enabled"]) {initTracing();- // Rotate trace ID on route changes so all API calls within- // a single page view share one trace.- if (syncedHistory) {- syncedHistory.listen(() => rotateTraceId());- } else {- // v7 mirrors the location into state.routing; rotate when it changes.- let lastPathname;- store.subscribe(() => {- const { pathname } =- store.getState().routing.locationBeforeTransitions ?? {};- if (pathname !== lastPathname) {- lastPathname = pathname;- rotateTraceId();- }- });- }+ // Rotate trace ID on route changes so all API calls within a single page view+ // share one trace. The router mirrors the location into state.routing.+ let lastPathname;+ store.subscribe(() => {+ const { pathname } =+ store.getState().routing.locationBeforeTransitions ?? {};+ if (pathname !== lastPathname) {+ lastPathname = pathname;+ rotateTraceId();+ }+ });}initializeInteractiveEmbedding(store.dispatch);const root = createRoot(document.getElementById("root"));- const app = <RouterProvider>{routes}</RouterProvider>;-root.render(<MetabaseReduxProvider store={store}><EmotionCacheProvider>@@ -122,13 +96,7 @@ function _init(reducers, getRoutes, callback) {<GlobalStyles />{createPortal(<PortalContainer />, document.body)}<MetabotProvider>- {syncedHistory ? (- <HistoryProvider history={syncedHistory}>- {app}- </HistoryProvider>- ) : (- app- )}+ <RouterProvider>{routes}</RouterProvider></MetabotProvider></AppThemeProvider></OverlayStackProvider>diff --git a/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx b/frontend/src/metabase/common/components/Link/ForwardRefLink.tsxindex 419d2f31708..448e917981c 100644--- a/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx+++ b/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx@@ -3,14 +3,12 @@import { forwardRef } from "react";-import type { RouterLinkProps as LinkProps } from "metabase/router/react-router";+import type { RouterLinkProps as LinkProps } from "metabase/router";import { RouterLink as Link } from "metabase/router/router-link";// `ref` prop, we have to manually forward it to the correct prop name to make hover work as expected.-export const ForwardRefLink = forwardRef(function _ForwardRefLink(- props: LinkProps,- ref,-) {- // @ts-expect-error - innerRef not in prop types but it is a valid prop. docs can be found here: https://github.com/remix-run/react-router/blob/v3.2.6/docs/API.md#innerref- return <Link {...props} innerRef={ref} />;-});+export const ForwardRefLink = forwardRef<HTMLAnchorElement, LinkProps>(+ function _ForwardRefLink(props, ref) {+ return <Link {...props} innerRef={ref} />;+ },+);diff --git a/frontend/src/metabase/common/components/Link/types.ts b/frontend/src/metabase/common/components/Link/types.tsindex c96d634face..030d2813024 100644--- a/frontend/src/metabase/common/components/Link/types.ts+++ b/frontend/src/metabase/common/components/Link/types.ts@@ -1,4 +1,4 @@-import type { RouterLinkProps } from "metabase/router/react-router";+import type { RouterLinkProps } from "metabase/router";import type { TooltipProps } from "metabase/ui";export interface LinkProps extends Omit<RouterLinkProps, "to"> {diff --git a/frontend/src/metabase/history/HistoryProvider.tsx b/frontend/src/metabase/history/HistoryProvider.tsxdeleted file mode 100644index babfc5a3159..00000000000--- a/frontend/src/metabase/history/HistoryProvider.tsx+++ /dev/null@@ -1,24 +0,0 @@-import { type PropsWithChildren, createContext } from "react";--import type { History } from "metabase/router";--type HistoryContextType = {- history: History;-};--export const HistoryContext = createContext<HistoryContextType | null>(null);--type Props = {- history: History;-};--export const HistoryProvider = ({- history,- children,-}: PropsWithChildren<Props>) => {- return (- <HistoryContext.Provider value={{ history }}>- {children}- </HistoryContext.Provider>- );-};diff --git a/frontend/src/metabase/history/index.ts b/frontend/src/metabase/history/index.tsdeleted file mode 100644index ea91d1e7664..00000000000--- a/frontend/src/metabase/history/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./HistoryProvider";-export * from "./useHistory";diff --git a/frontend/src/metabase/history/useHistory.ts b/frontend/src/metabase/history/useHistory.tsdeleted file mode 100644index 9b271ea76dc..00000000000--- a/frontend/src/metabase/history/useHistory.ts+++ /dev/null@@ -1,11 +0,0 @@-import { useContext } from "react";--import { HistoryContext } from "./HistoryProvider";--export const useHistory = () => {- const history = useContext(HistoryContext);- if (!history) {- throw new Error("useHistory must be used inside <HistoryProvider>");- }- return history;-};diff --git a/frontend/src/metabase/redux/routing-contract.unit.spec.ts b/frontend/src/metabase/redux/routing-contract.unit.spec.tsdeleted file mode 100644index f754e66d5fc..00000000000--- a/frontend/src/metabase/redux/routing-contract.unit.spec.ts+++ /dev/null@@ -1,135 +0,0 @@-import { configureStore } from "@reduxjs/toolkit";-import { createMemoryHistory } from "history";--import {- goBack,- push,- replace,- routerMiddleware,- routing,- syncHistoryWithStore,-} from "metabase/router";-import { getLocation } from "metabase/selectors/routing";--// Keystone characterization test for the navigation TRANSPORT seam.-//-// `metabase/router` owns the `push`/`replace`/`goBack`-// action creators + `routerMiddleware` + `routing` reducer +-// `syncHistoryWithStore`. This test pins the observable contract that the-// replacement preserves byte-for-byte:-//-// dispatch(push/replace/goBack) -> state.routing + @@router/LOCATION_CHANGE-//-// It wires up the SAME transport `store.js` / `app.js` use (the router-// middleware + the routing reducer + a memory history + syncHistoryWithStore),-// isolated from the rest of the app graph.--const LOCATION_CHANGE = "@@router/LOCATION_CHANGE";--const setup = () => {- const actions: Array<{ type: string; payload?: any }> = [];- const recorder = () => (next: any) => (action: any) => {- actions.push(action);- return next(action);- };-- const history = createMemoryHistory();- const store = configureStore({- reducer: { routing },- middleware: (getDefaultMiddleware) =>- getDefaultMiddleware({- serializableCheck: false,- immutableCheck: false,- }).concat(routerMiddleware(history), recorder),- });- const syncedHistory = syncHistoryWithStore(history, store);-- const locationChanges = () =>- actions.filter((a) => a.type === LOCATION_CHANGE);- // Unjustified type cast. FIXME- const location = () => getLocation(store.getState() as any);-- return { store, history: syncedHistory, location, locationChanges };-};--describe("routing transport contract", () => {- it("mirrors the initial location into state.routing on sync", () => {- const { location } = setup();- expect(location().pathname).toBe("/");- });-- it("push(string) updates pathname, search and hash", () => {- const { store, location } = setup();-- store.dispatch(push("/question/42?x=1#hash"));-- expect(location().pathname).toBe("/question/42");- expect(location().search).toBe("?x=1");- expect(location().hash).toBe("#hash");- });-- it("push(descriptor) round-trips location.state (the QB card-state case)", () => {- // query_builder/actions/url.ts dispatches push() with the serialized card on- // `state`; the migration's history proxy must forward state across engines.- const { store, location } = setup();- const cardState = {- card: { id: 7, name: "Q" },- cardId: 7,- objectId: undefined,- };-- store.dispatch(- push({- pathname: "/question",- search: "?y=2",- hash: "#abc",- state: cardState,- }),- );-- expect(location().pathname).toBe("/question");- expect(location().state).toEqual(cardState);- });-- it("preserves the preserveNavbarState flag on location.state", () => {- const { store, location } = setup();-- store.dispatch(- push({ pathname: "/question/1", state: { preserveNavbarState: true } }),- );-- expect(location().state).toEqual({ preserveNavbarState: true });- });-- it("distinguishes push from replace via location.action", () => {- const { store, location } = setup();-- store.dispatch(push("/a"));- expect(location().action).toBe("PUSH");-- store.dispatch(replace("/b"));- expect(location().pathname).toBe("/b");- expect(location().action).toBe("REPLACE");- });-- it("goBack returns to the previous entry", () => {- const { store, location } = setup();-- store.dispatch(push("/first"));- store.dispatch(push("/second"));- expect(location().pathname).toBe("/second");-- store.dispatch(goBack());- expect(location().pathname).toBe("/first");- });-- it("emits @@router/LOCATION_CHANGE with the location payload on every navigation", () => {- const { store, locationChanges } = setup();-- store.dispatch(push("/one"));- store.dispatch(push("/two"));-- const paths = locationChanges().map((a) => a.payload.pathname);- expect(paths).toEqual(expect.arrayContaining(["/one", "/two"]));- });-});diff --git a/frontend/src/metabase/redux/routing-contract.unit.spec.tsx b/frontend/src/metabase/redux/routing-contract.unit.spec.tsxnew file mode 100644index 00000000000..e6281c50843--- /dev/null+++ b/frontend/src/metabase/redux/routing-contract.unit.spec.tsx@@ -0,0 +1,123 @@+import { act, renderWithProviders, waitFor } from "__support__/ui";+import { Route, goBack, push, replace } from "metabase/router";+import { getLocation } from "metabase/selectors/routing";++// Keystone characterization test for the navigation TRANSPORT seam.+//+// `metabase/router` owns the `push`/`replace`/`goBack` action creators, the+// `routerMiddleware`, the `routing` reducer, and the redux bridge that mirrors+// the router's location back into the store. This test pins the observable+// contract:+//+// dispatch(push/replace/goBack) -> state.routing+//+// It wires up the same transport `app.js` uses, isolated from the rest of the+// app graph.++const setup = () => {+ const { store } = renderWithProviders(<Route path="*" element={null} />, {+ withRouter: true,+ initialRoute: "/",+ });++ // Unjustified type cast. FIXME+ const location = () => getLocation(store.getState() as any);++ const navigate = async (action: unknown) => {+ await act(async () => {+ // Unjustified type cast. FIXME+ store.dispatch(action as any);+ });+ };++ return { store, location, navigate };+};++describe("routing transport contract", () => {+ it("mirrors the initial location into state.routing on mount", async () => {+ const { location } = setup();+ await waitFor(() => expect(location().pathname).toBe("/"));+ });++ it("push(string) updates pathname, search and hash", async () => {+ const { location, navigate } = setup();++ await navigate(push("/question/42?x=1#hash"));++ expect(location().pathname).toBe("/question/42");+ expect(location().search).toBe("?x=1");+ expect(location().hash).toBe("#hash");+ });++ it("push(descriptor) round-trips location.state (the QB card-state case)", async () => {+ // query_builder/actions/url.ts dispatches push() with the serialized card on+ // `state`, so the transport must forward it.+ const { location, navigate } = setup();+ const cardState = {+ card: { id: 7, name: "Q" },+ cardId: 7,+ objectId: undefined,+ };++ await navigate(+ push({+ pathname: "/question",+ search: "?y=2",+ hash: "#abc",+ state: cardState,+ }),+ );++ expect(location().pathname).toBe("/question");+ expect(location().state).toEqual(cardState);+ });++ it("preserves the preserveNavbarState flag on location.state", async () => {+ const { location, navigate } = setup();++ await navigate(+ push({ pathname: "/question/1", state: { preserveNavbarState: true } }),+ );++ expect(location().state).toEqual({ preserveNavbarState: true });+ });++ it("distinguishes push from replace via location.action", 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");+ });++ it("goBack returns to the previous entry", async () => {+ const { location, navigate } = setup();++ await navigate(push("/first"));+ await navigate(push("/second"));+ expect(location().pathname).toBe("/second");++ await navigate(goBack());+ expect(location().pathname).toBe("/first");+ });++ it("mirrors every navigation into state.routing", async () => {+ const { store, location, navigate } = setup();++ const seen: string[] = [];+ store.subscribe(() => {+ const { pathname } = location();+ if (seen.at(-1) !== pathname) {+ seen.push(pathname);+ }+ });++ await navigate(push("/one"));+ await navigate(push("/two"));++ expect(seen).toEqual(expect.arrayContaining(["/one", "/two"]));+ });+});diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsxindex 03a54af24b5..24575c0ea0a 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SmartLink/SmartLinkNode.unit.spec.tsx@@ -1,5 +1,4 @@import type { NodeViewProps } from "@tiptap/react";-import { createMemoryHistory } from "history";import {setupCardEndpoints,@@ -10,7 +9,8 @@ import {setupTableEndpoints,} from "__support__/server-mocks";import { renderWithProviders, screen, waitFor } from "__support__/ui";-import { Route, Router, useRouterHistory } from "metabase/router";+import { Route } from "metabase/router";+import { RouterProviderV7Memory } from "metabase/router/v7/RouterProviderV7";import {createMockCard,createMockCollection,@@ -50,7 +50,7 @@ function setup({updateAttributes?: NodeViewProps["updateAttributes"];}) {const props = createProps(model, entity, label, updateAttributes);- renderWithProviders(<SmartLinkComponent {...props} />);+ renderWithProviders(<SmartLinkComponent {...props} />, { withRouter: true });}describe("SmartLink", () => {@@ -204,16 +204,11 @@ describe("SmartLink", () => {setupDashboardEndpoints(dashboard);- const historyWithBasename = useRouterHistory(createMemoryHistory)({- basename: "/subpath",- entries: ["/"],- });-const props = createProps("dashboard", dashboard);renderWithProviders(- <Router history={historyWithBasename}>+ <RouterProviderV7Memory initialRoute="/subpath" basename="/subpath"><Route path="*" element={<SmartLinkComponent {...props} />} />- </Router>,+ </RouterProviderV7Memory>,);await waitFor(() => {@@ -235,15 +230,11 @@ describe("SmartLink", () => {setupDashboardEndpoints(dashboard);- const historyNoBasename = useRouterHistory(createMemoryHistory)({- entries: ["/"],- });-const props = createProps("dashboard", dashboard);renderWithProviders(- <Router history={historyNoBasename}>+ <RouterProviderV7Memory initialRoute="/"><Route path="*" element={<SmartLinkComponent {...props} />} />- </Router>,+ </RouterProviderV7Memory>,);await waitFor(() => {diff --git a/frontend/src/metabase/router/Outlet.tsx b/frontend/src/metabase/router/Outlet.tsxindex d99655ac979..e0b3e2ee18d 100644--- a/frontend/src/metabase/router/Outlet.tsx+++ b/frontend/src/metabase/router/Outlet.tsx@@ -1,4 +1,4 @@-import type { ComponentType, ReactNode } from "react";+import type { ReactNode } from "react";import { createContext, useContext } from "react";import type { Route } from "./route";@@ -8,11 +8,8 @@ export const OutletContext = createContext<ReactNode>(null);export const RouteContext = createContext<Route | null>(null);/**- * The route matched for the nearest `element`-based route ancestor. On v3 the- * matched route is injected as a `route` prop; this exposes it to `element`- * routes, which are not passed props. Replaces threading the v3 `route` prop- * through pages (e.g. for `setRouteLeaveHook`). Native `useMatch`/route context- * takes over at the engine swap.+ * The route matched for the nearest `element`-based route ancestor, published by+ * `RouterBridge`. Consumers hand it back to `setRouteLeaveHook`.*/export function useRoute(): Route | null {return useContext(RouteContext);@@ -20,8 +17,7 @@ export function useRoute(): Route | null {/*** react-router v7's `<Outlet>`: renders the matched child route (or nothing when- * there is none). On v3 the child is injected as `props.children`, which the- * `element` bridge exposes through context.+ * there is none).** @see https://reactrouter.com/7.18.1/api/components/Outlet*/@@ -29,68 +25,3 @@ export function Outlet(): JSX.Element {const child = useContext(OutletContext);return <>{child}</>;}--type RouteWithElement = Route & { element?: ReactNode };--type RouteElementComponent = ComponentType<{- children?: ReactNode;- route?: RouteWithElement;-}>;--// The generated route `component` is keyed by the element's component *type*, not-// by element identity, and it renders the element off the v3-injected `route`.-// Two sibling routes that render the same component (`element={<X/>}` at-// `foo/:a` and `foo/:a/:b`) therefore share one `component`, so React reconciles-// `X` across a navigation between them instead of remounting it — matching v3's-// `component={X}` behaviour and preserving `X`'s state. It also keeps the-// component stable across v3's config rebuilds, so a `redirect()` element does-// not remount and re-fire its navigation in a loop.-const componentByType = new WeakMap<object, RouteElementComponent>();--/**- * Turns a v7-style `element` into a react-router v3 route `component`. The child- * route that v3 injects as `props.children` is exposed through context, letting- * the element render it with `<Outlet/>`. This is how `<Route element={<X/>}>`- * runs on v3.- */-export function routeElementToComponent(- element: ReactNode,-): RouteElementComponent {- const type = elementType(element);- if (type != null) {- let cached = componentByType.get(type);- if (!cached) {- cached = makeRouteElementComponent();- componentByType.set(type, cached);- }- return cached;- }- return makeRouteElementComponent();-}--// The component type of an element, usable as a WeakMap key (a component function-// or a `React.memo`/`forwardRef` object). Host tags (strings) and fragments-// (symbols) aren't keyable, so those fall back to a fresh, unmemoized component.-function elementType(element: ReactNode): object | null {- if (element != null && typeof element === "object" && "type" in element) {- // Narrowed to an object with a `type` key just above; read it as `unknown`- // to classify the element's component type without assuming a React shape.- const type = (element as { type: unknown }).type;- if (typeof type === "function" || (typeof type === "object" && type)) {- return type;- }- }- return null;-}--function makeRouteElementComponent(): RouteElementComponent {- return function RouteElement({ children, route }) {- return (- <RouteContext.Provider value={route ?? null}>- <OutletContext.Provider value={children}>- {route?.element}- </OutletContext.Provider>- </RouteContext.Provider>- );- };-}diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsxindex 0aa426c65c1..92a635c8c1b 100644--- a/frontend/src/metabase/router/RouterProvider.tsx+++ b/frontend/src/metabase/router/RouterProvider.tsx@@ -1,92 +1,18 @@-import { type PropsWithChildren, createContext, useMemo } from "react";+import { type PropsWithChildren, createContext } from "react";-import { useHistory } from "metabase/history";--import { type RouterEngine, getRouterEngine } from "./engine";-import {- ReactRouterRoute,- Router,- type WithRouterProps,- reactRouterWithRouter,-} from "./react-router";-import type { History } from "./types";+import type { WithRouterProps } from "./types";import { RouterProviderV7 } from "./v7/RouterProviderV7";type RouterContextType = WithRouterProps;-export const RouterContext = createContext<RouterContextType | null>(null);--const RouterContextProviderBase = ({- router,- location,- params,- routes,- children,-}: PropsWithChildren<RouterContextType>) => {- // Memoize on the injected parts so a re-render that leaves them unchanged does- // not hand consumers a fresh object. Under the `element` bridge, navigation- // commits twice (the facade context update, then v3's own route re-render), and- // an unmemoized value would re-propagate on that second, location-unchanged- // render. That extra render breaks pages that derive transient state from- // `usePrevious(location.key)` (e.g. the document /new -> /new leave prompt),- // which `component`-based v3 routes never saw because v3 re-renders them once.- const value = useMemo(- () => ({ router, location, params, routes }),- [router, location, params, routes],- );- return (- <RouterContext.Provider value={value}>{children}</RouterContext.Provider>- );-};--const RouterContextProvider = reactRouterWithRouter(RouterContextProviderBase);--type RouterProviderProps = {- history?: History | undefined;-};-/**- * This provider encapsulates react-router initiation and puts router and routes references to the context- * This is v3's only solution to provide a router and routes.- * Without extra Route component it doesn't work.- * Additionally, it provides the history reference- *- * Uses the raw v3 `Route` here (not the facade's `element`-based one): this is the- * component that establishes the router context, so it cannot itself consume that- * context through `<Outlet/>`.+ * The router state the facade hooks read, published per route by `RouterBridge`.*/-const RouterProviderV3 = ({- children,-}: PropsWithChildren<RouterProviderProps>) => {- const { history } = useHistory();- return (- <Router history={history}>- <ReactRouterRoute component={RouterContextProvider}>- {children}- </ReactRouterRoute>- </Router>- );-};--type RouterProviderPropsWithEngine = RouterProviderProps & {- /**- * Which engine hosts the app. Defaults to the `use-v7-router` flag; tests pass- * it explicitly to exercise both engines. Goes away with the v3 engine.- */- engine?: RouterEngine;-};+export const RouterContext = createContext<RouterContextType | null>(null);/**- * Hosts the app on either engine. On v7 the facade hooks read the same- * `RouterContext`, filled per route by the `RouterBridge` instead of v3's- * `withRouter`, so nothing downstream changes.+ * Hosts the app on react-router v7.*/-export const RouterProvider = ({- children,- engine = getRouterEngine(),-}: PropsWithChildren<RouterProviderPropsWithEngine>) => {- if (engine === "v7") {- return <RouterProviderV7>{children}</RouterProviderV7>;- }- return <RouterProviderV3>{children}</RouterProviderV3>;-};+export const RouterProvider = ({ children }: PropsWithChildren) => (+ <RouterProviderV7>{children}</RouterProviderV7>+);diff --git a/frontend/src/metabase/router/conformance/Navigate.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/Navigate.conformance.unit.spec.tsxdeleted file mode 100644index 14bc346fe5c..00000000000--- a/frontend/src/metabase/router/conformance/Navigate.conformance.unit.spec.tsx+++ /dev/null@@ -1,105 +0,0 @@-import userEvent from "@testing-library/user-event";-import { useState } from "react";--import { screen } from "__support__/ui";--import type { Probe, RouterApi } from "./test-utils";-import { runBoth } from "./test-utils";--// Because the facade churns its `navigate` identity like v7, a mounted-// <Navigate> re-fires whenever the pathname changes and snaps forward to its-// target again. So on both engines, going back re-asserts the destination.-function makeLandingProbe(to: string, replace: boolean): Probe {- return function LandingProbe({ api }: { api: RouterApi }) {- const { Navigate } = api;- const navigate = api.useNavigate();- const location = api.useLocation();- return (- <div>- <span data-testid="rr-pathname">{location.pathname}</span>- <Navigate to={to} replace={replace} />- <button onClick={() => navigate(-1)}>back</button>- </div>- );- };-}--function RenavigateProbe({ api }: { api: RouterApi }) {- const { Navigate } = api;- const location = api.useLocation();- const [to, setTo] = useState("/first");- return (- <div>- <span data-testid="rr-pathname">{location.pathname}</span>- <Navigate to={to} />- <button onClick={() => setTo("/second")}>change</button>- </div>- );-}--const RICH_STATE = { when: new Date(0), n: NaN };--function StateProbe({ api }: { api: RouterApi }) {- const { Navigate } = api;- const location = api.useLocation();- // Unjustified type cast. FIXME- const state = location.state as typeof RICH_STATE | null;- return (- <div>- <span data-testid="rr-pathname">{location.pathname}</span>- <span data-testid="rr-when-is-date">- {String(state?.when instanceof Date)}- </span>- <span data-testid="rr-n-is-nan">{String(Number.isNaN(state?.n))}</span>- <Navigate to="/dest" state={RICH_STATE} />- </div>- );-}--describe("router/Navigate conformance", () => {- it("matches v7 when landing on the destination on mount (push)", async () => {- const { facade, v7 } = await runBoth(makeLandingProbe("/dest", false), {- initialRoute: "/home",- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/dest");- });-- it("matches v7 when landing on the destination on mount (replace)", async () => {- const { facade, v7 } = await runBoth(makeLandingProbe("/dest", true), {- initialRoute: "/home",- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/dest");- });-- it("matches v7 when re-asserting the pushed target on back", async () => {- const { facade, v7 } = await runBoth(makeLandingProbe("/dest", false), {- initialRoute: "/home",- interact: () =>- userEvent.click(screen.getByRole("button", { name: "back" })),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/dest");- });-- it("matches v7 when re-navigating after the target prop changes", async () => {- const { facade, v7 } = await runBoth(RenavigateProbe, {- initialRoute: "/home",- interact: () =>- userEvent.click(screen.getByRole("button", { name: "change" })),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/second");- });-- it("matches v7 when passing rich state through by reference", async () => {- const { facade, v7 } = await runBoth(StateProbe, {- initialRoute: "/home",- });- expect(facade).toEqual(v7);- // Serializing would turn the Date into a string and NaN into null.- expect(facade["rr-when-is-date"]).toBe("true");- expect(facade["rr-n-is-nan"]).toBe("true");- });-});diff --git a/frontend/src/metabase/router/conformance/dynamic-routes.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/dynamic-routes.conformance.unit.spec.tsxdeleted file mode 100644index 5c9edb96c42..00000000000--- a/frontend/src/metabase/router/conformance/dynamic-routes.conformance.unit.spec.tsx+++ /dev/null@@ -1,48 +0,0 @@-import { runDynamicBoth } from "./test-utils";--describe("router/dynamic routes conformance", () => {- it("matches v7 when an enabled feature route is reachable", async () => {- const { facade, v7 } = await runDynamicBoth(- { featureEnabled: true, pluginLoaded: true },- "/feature",- );- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("feature");- });-- it("matches v7 by rendering the upsell when the feature is disabled", async () => {- const { facade, v7 } = await runDynamicBoth(- { featureEnabled: false, pluginLoaded: true },- "/feature",- );- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("upsell");- });-- it("matches v7 by reaching an array-interpolated plugin route", async () => {- const { facade, v7 } = await runDynamicBoth(- { featureEnabled: true, pluginLoaded: true },- "/ee/reports",- );- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("ee-reports");- });-- it("matches v7 by falling through to the catch-all when the EE bundle is absent", async () => {- const { facade, v7 } = await runDynamicBoth(- { featureEnabled: true, pluginLoaded: false },- "/ee/reports",- );- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("not-found");- });-- it("matches v7 when deep-linking straight to a disabled-feature route", async () => {- const { facade, v7 } = await runDynamicBoth(- { featureEnabled: false, pluginLoaded: false },- "/feature",- );- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("upsell");- });-});diff --git a/frontend/src/metabase/router/conformance/relative-navigate.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/relative-navigate.conformance.unit.spec.tsxdeleted file mode 100644index 4b97aadbf68..00000000000--- a/frontend/src/metabase/router/conformance/relative-navigate.conformance.unit.spec.tsx+++ /dev/null@@ -1,116 +0,0 @@-import userEvent from "@testing-library/user-event";--import { screen } from "__support__/ui";--import type { RouterApi } from "./test-utils";-import { runBoth } from "./test-utils";--/**- * Mounted in a child route, so `relative: "route"` resolves against the child.- * The readouts come from the parent route, which stays mounted after the probe- * navigates away.- */-function RelativeNavigateProbe({ api }: { api: RouterApi }) {- const navigate = api.useNavigate();- return (- <div>- <button onClick={() => navigate("..", { relative: "route" })}>- up-route- </button>- <button onClick={() => navigate("..", { relative: "path" })}>- up-path- </button>- <button onClick={() => navigate("..")}>up-default</button>- <button onClick={() => navigate("../sibling")}>sibling</button>- <button onClick={() => navigate("..", { replace: true })}>- up-replace- </button>- <button onClick={() => navigate("?x=1")}>query-only</button>- </div>- );-}--const click = (name: string) =>- userEvent.click(screen.getByRole("button", { name }));--const collectionRoute = {- initialRoute: "/collection/5/move",- facadePath: "collection/:slug",- v7Path: "collection/:slug",- childPath: "move",-};--// A modal route whose path spans several URL segments, e.g. the account-// notification routes' `pulse/:pulseId/archive`.-const multiSegmentRoute = {- initialRoute: "/account/notifications/pulse/7/archive",- facadePath: "account/notifications",- v7Path: "account/notifications",- childPath: "pulse/:pulseId/archive",-};--describe("router/useNavigate relative conformance", () => {- it('matches v7 when ".." climbs one route', async () => {- const { facade, v7 } = await runBoth(RelativeNavigateProbe, {- ...collectionRoute,- interact: () => click("up-route"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/collection/5");- });-- it('matches v7 when ".." defaults to route-relative', async () => {- const { facade, v7 } = await runBoth(RelativeNavigateProbe, {- ...collectionRoute,- interact: () => click("up-default"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/collection/5");- });-- it('matches v7 when ".." climbs a route spanning several segments', async () => {- const { facade, v7 } = await runBoth(RelativeNavigateProbe, {- ...multiSegmentRoute,- interact: () => click("up-route"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/account/notifications");- });-- it('matches v7 when ".." climbs a single segment with relative: "path"', async () => {- const { facade, v7 } = await runBoth(RelativeNavigateProbe, {- ...multiSegmentRoute,- interact: () => click("up-path"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/account/notifications/pulse/7");- });-- it("matches v7 when navigating to a sibling route", async () => {- const { facade, v7 } = await runBoth(RelativeNavigateProbe, {- ...collectionRoute,- interact: () => click("sibling"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/collection/5/sibling");- });-- it('matches v7 when ".." replaces the current entry', async () => {- const { facade, v7 } = await runBoth(RelativeNavigateProbe, {- ...collectionRoute,- interact: () => click("up-replace"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/collection/5");- });-- it("matches v7 when a destination carries only a query", async () => {- const { facade, v7 } = await runBoth(RelativeNavigateProbe, {- ...collectionRoute,- interact: () => click("query-only"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/collection/5/move");- expect(facade["rr-search"]).toBe("?x=1");- });-});diff --git a/frontend/src/metabase/router/conformance/test-utils.tsx b/frontend/src/metabase/router/conformance/test-utils.tsxdeleted file mode 100644index a527d08f90e..00000000000--- a/frontend/src/metabase/router/conformance/test-utils.tsx+++ /dev/null@@ -1,311 +0,0 @@-import type {- ComponentType,- PropsWithChildren,- ReactElement,- ReactNode,-} from "react";-import { Route } from "react-router";-import {- MemoryRouter,- Navigate as V7Navigate,- Outlet as V7Outlet,- Route as V7Route,- Routes as V7Routes,- useLocation as v7UseLocation,- useNavigate as v7UseNavigate,- useParams as v7UseParams,- useSearchParams as v7UseSearchParams,-} from "react-router-v7";--import { act, cleanup, renderWithProviders } from "__support__/ui";-import {- Navigate,- useLocation,- useNavigate,- useParams,- useSearchParams,-} from "metabase/router";--/**- * The slice of the router API that both the `metabase/router` facade (running on- * react-router v3) and real react-router v7 expose with the same names and- * signatures. A `Probe` receives one of these and cannot tell which engine it is- * rendered against, which is what lets a single probe drive both adapters.- */-export type RouterApi = {- useNavigate: typeof useNavigate;- useLocation: typeof useLocation;- useSearchParams: typeof useSearchParams;- useParams: typeof useParams;- // Probes only ever pass string destinations, which both engines accept.- Navigate: ComponentType<{ to: string; replace?: boolean; state?: unknown }>;-};--export const facadeApi: RouterApi = {- useNavigate,- useLocation,- useSearchParams,- useParams,- Navigate,-};--/**- * Real react-router v7's hooks and components share the facade's shapes but not- * its exact types (v7 adds options like `relative`), so the object is asserted- * to the shared `RouterApi` rather than structurally assignable.- */-export const v7Api = {- useNavigate: v7UseNavigate,- useLocation: v7UseLocation,- useSearchParams: v7UseSearchParams,- useParams: v7UseParams,- Navigate: V7Navigate,-} as unknown as RouterApi;--/**- * A probe renders readouts from the router API it is handed. Every readout it- * emits must be a `data-testid` starting with `rr-` so the harness can collect- * and compare exactly those, ignoring provider chrome.- */-export type Probe = ComponentType<{ api: RouterApi }>;--const READOUT_PREFIX = "rr-";--export type RenderOptions = {- initialRoute: string;- facadePath?: string;- v7Path?: string;- /**- * Mount the probe in a child route of `facadePath`/`v7Path` instead of in the- * route itself. The parent route emits the readouts, so they survive a probe- * that navigates itself out of the tree.- */- childPath?: string;-};--function ParentReadouts({- location,-}: {- location: { pathname: string; search: string };-}) {- return (- <>- <span data-testid="rr-pathname">{location.pathname}</span>- <span data-testid="rr-search">{location.search}</span>- </>- );-}--function FacadeParent({ children }: { children?: ReactNode }) {- return (- <div>- <ParentReadouts location={useLocation()} />- {children}- </div>- );-}--function V7Parent() {- return (- <div>- <ParentReadouts location={v7UseLocation()} />- <V7Outlet />- </div>- );-}--// Keeps the parent route matched wherever a probe navigates below it, so both-// engines are compared on the destination rather than on an unmatched URL.-const Nothing = () => null;--function renderFacade(- Probe: Probe,- { initialRoute, facadePath = "*", childPath }: RenderOptions,-) {- const Mounted = () => <Probe api={facadeApi} />;- const tree = childPath ? (- <Route path={facadePath} component={FacadeParent}>- <Route path={childPath} component={Mounted} />- <Route path="*" component={Nothing} />- </Route>- ) : (- <Route path={facadePath} component={Mounted} />- );-- // These suites exist to prove the facade *on v3* behaves like real v7, and the- // tree above is raw v3 route config, so pin the engine rather than following- // the harness default (now v7). Retired with the v3 engine.- renderWithProviders(tree, {- withRouter: true,- initialRoute,- routerEngine: "v3",- });-}--function renderV7(- Probe: Probe,- { initialRoute, v7Path = "*", childPath }: RenderOptions,-) {- const probe = <Probe api={v7Api} />;- const tree = childPath ? (- <V7Route path={v7Path} element={<V7Parent />}>- <V7Route path={childPath} element={probe} />- <V7Route path="*" element={<Nothing />} />- </V7Route>- ) : (- <V7Route path={v7Path} element={probe} />- );-- renderWithProviders(- <MemoryRouter initialEntries={[initialRoute]}>- <V7Routes>{tree}</V7Routes>- </MemoryRouter>,- );-}--function collectReadouts(): Record<string, string | null> {- const nodes = document.querySelectorAll(`[data-testid^="${READOUT_PREFIX}"]`);- const readouts: Record<string, string | null> = {};- nodes.forEach((node) => {- const id = node.getAttribute("data-testid");- if (id) {- readouts[id] = node.textContent;- }- });- return readouts;-}--async function settle() {- // Flush mount effects (e.g. <Navigate>) and the re-render they trigger.- await act(async () => {});-}--async function renderAndCollect(- render: () => void,- interact?: () => Promise<void>,-): Promise<Record<string, string | null>> {- render();- // Always unmount, even if a step throws, so one render's `rr-` nodes can never- // leak into the next.- try {- await settle();- await interact?.();- return collectReadouts();- } finally {- cleanup();- }-}--/**- * Render the same probe against the facade and against real v7, running the- * optional interaction against each, and return the `rr-` readouts from both so- * a spec can assert they are identical.- */-export async function runBoth(- Probe: Probe,- options: RenderOptions & { interact?: () => Promise<void> },-): Promise<{- facade: Record<string, string | null>;- v7: Record<string, string | null>;-}> {- const { interact, ...renderOptions } = options;-- const facade = await renderAndCollect(- () => renderFacade(Probe, renderOptions),- interact,- );- const v7 = await renderAndCollect(- () => renderV7(Probe, renderOptions),- interact,- );-- return { facade, v7 };-}--/**- * The three moving parts of a dynamic/plugin route setup. `featureEnabled`- * drives the `isEnabled ? real : upsell` conditional; `pluginLoaded` drives the- * `{PLUGIN_*_ROUTES}` array interpolation (false models an OSS build where the- * enterprise bundle contributes nothing).- */-export type DynamicRouteScenario = {- featureEnabled: boolean;- pluginLoaded: boolean;-};--/**- * Constructs one leaf route for a given engine. The facade builds a v3- * `component=` route, real v7 builds an `element=` route; both render a `Page`- * emitting the same `rr-page` readout so the harness can compare outcomes.- */-type LeafRoute = (key: string, path: string, page: string) => ReactElement;--const Passthrough = ({ children }: PropsWithChildren) => <>{children}</>;--const Page = ({ name }: { name: string }) => (- <span data-testid="rr-page">{name}</span>-);--/**- * Assembles the sibling routes for a scenario from whichever engine's leaf- * constructor is supplied, so both engines route the exact same declarative- * shape: a feature-gated route, an array-interpolated plugin route, and a- * trailing catch-all.- */-function dynamicSiblings(route: LeafRoute, scenario: DynamicRouteScenario) {- const gated = scenario.featureEnabled- ? route("feature", "feature", "feature")- : route("feature", "feature", "upsell");- const pluginRoutes = scenario.pluginLoaded- ? [route("ee", "ee/reports", "ee-reports")]- : [];- const catchAll = route("catch-all", "*", "not-found");- return [gated, ...pluginRoutes, catchAll];-}--function renderDynamicFacade(- scenario: DynamicRouteScenario,- initialRoute: string,-) {- const leaf: LeafRoute = (key, path, page) => (- <Route key={key} path={path} component={() => <Page name={page} />} />- );- renderWithProviders(- <Route component={Passthrough}>{dynamicSiblings(leaf, scenario)}</Route>,- // Raw v3 route config, same as `renderFacade`: pin the engine.- { withRouter: true, initialRoute, routerEngine: "v3" },- );-}--function renderDynamicV7(scenario: DynamicRouteScenario, initialRoute: string) {- const leaf: LeafRoute = (key, path, page) => (- <V7Route key={key} path={path} element={<Page name={page} />} />- );- renderWithProviders(- <MemoryRouter initialEntries={[initialRoute]}>- <V7Routes>{dynamicSiblings(leaf, scenario)}</V7Routes>- </MemoryRouter>,- );-}--/**- * Render the same dynamic/plugin route scenario against the facade and against- * real v7, deep-linking each to `initialRoute`, and return the `rr-` readouts- * from both so a spec can assert the mechanism resolves identically.- */-export async function runDynamicBoth(- scenario: DynamicRouteScenario,- initialRoute: string,-): Promise<{- facade: Record<string, string | null>;- v7: Record<string, string | null>;-}> {- const facade = await renderAndCollect(() =>- renderDynamicFacade(scenario, initialRoute),- );- const v7 = await renderAndCollect(() =>- renderDynamicV7(scenario, initialRoute),- );-- return { facade, v7 };-}diff --git a/frontend/src/metabase/router/conformance/types.conformance.unit.spec.ts b/frontend/src/metabase/router/conformance/types.conformance.unit.spec.tsdeleted file mode 100644index 26cdf7c05c3..00000000000--- a/frontend/src/metabase/router/conformance/types.conformance.unit.spec.ts+++ /dev/null@@ -1,137 +0,0 @@-import type { ComponentProps } from "react";-import type {- Location as V7Location,- NavigateFunction as V7NavigateFunction,- NavigateOptions as V7NavigateOptions,- NavigateProps as V7NavigateProps,- OutletProps as V7OutletProps,- Params as V7Params,- Path as V7Path,- SetURLSearchParams as V7SetURLSearchParams,- To as V7To,- URLSearchParamsInit as V7URLSearchParamsInit,- useNavigate as v7UseNavigate,- useParams as v7UseParams,- useSearchParams as v7UseSearchParams,-} from "react-router-v7";--import type {- Navigate,- NavigateFunction,- NavigateOptions,- Outlet,- Params,- Path,- SetURLSearchParams,- To,- URLSearchParamsInit,- useLocation,- useNavigate,- useParams,- useSearchParams,-} from "metabase/router";--/*- * Compile-time conformance: these assertions fail `tsc` (not jest) if the- * facade's public types drift from react-router v7's. Runtime behavior lives in- * the sibling *.conformance specs; this file guards the type contract, the layer- * a behavioral test cannot see (the missing `defaultInit` argument slipped- * through exactly here).- */--type Extends<A, B> = [A] extends [B] ? true : false;-type Equal<A, B> =- Extends<A, B> extends true- ? Extends<B, A> extends true- ? true- : false- : false;-type Expect<T extends true> = T;--// The pure data types must be identical to v7's.-type _To = Expect<Equal<To, V7To>>;-type _Path = Expect<Equal<Path, V7Path>>;-type _Params = Expect<Equal<Params, V7Params>>;-type _Init = Expect<Equal<URLSearchParamsInit, V7URLSearchParamsInit>>;--// Hook signatures must match v7's, arguments included. This is the assertion-// that would have caught the missing `useSearchParams(defaultInit)` argument.-type _UseSearchParamsArgs = Expect<- Equal<- Parameters<typeof useSearchParams>,- Parameters<typeof v7UseSearchParams>- >->;-type _UseNavigateArgs = Expect<- Equal<Parameters<typeof useNavigate>, Parameters<typeof v7UseNavigate>>->;-type _UseParamsReturn = Expect<- Equal<ReturnType<typeof useParams>, ReturnType<typeof v7UseParams>>->;--// The facade's location shape must match v7's. `state` is excluded on purpose:-// v7 types it `any`, the facade uses the safer `unknown` (the codebase bans-// `any`). Both are mutually assignable, so the swap is unaffected.-type _Location = Expect<- Equal<- Omit<ReturnType<typeof useLocation>, "state">,- Omit<V7Location, "state">- >->;--// Where the facade omits v7 options it must be a strict subset (assignable to-// v7), so facade-typed code keeps compiling after the swap. The omitted options-// themselves are enumerated as known gaps below.-type _NavigateOptionsSubset = Expect<- Extends<NavigateOptions, V7NavigateOptions>->;-type _NavigateFnSubset = Expect<Extends<NavigateFunction, V7NavigateFunction>>;-type _SetSearchParamsSubset = Expect<- Extends<SetURLSearchParams, V7SetURLSearchParams>->;-type _NavigatePropsSubset = Expect<- Extends<ComponentProps<typeof Navigate>, V7NavigateProps>->;--/*- * Coverage: every option/prop v7 exposes must be either implemented by the- * facade or listed here as a deliberate gap. When a v7 upgrade adds a key, the- * matching `Unaccounted` type stops being `never` and this file fails to- * compile, forcing a conscious decision instead of a silent divergence.- */--// Need the engine swap (relative resolution, scroll/transition control, URL-// masking, data-router revalidation), so intentionally unsupported on v3.-type KnownGapNavigateOptions =- | "mask"- | "preventScrollReset"- | "relative"- | "viewTransition"- | "flushSync"- | "defaultShouldRevalidate";-type UnaccountedNavigateOptions = Exclude<- keyof V7NavigateOptions,- keyof NavigateOptions | KnownGapNavigateOptions->;-type _NavigateOptionsCovered = Expect<Equal<UnaccountedNavigateOptions, never>>;--type KnownGapNavigateProps = "relative";-type UnaccountedNavigateProps = Exclude<- keyof V7NavigateProps,- keyof ComponentProps<typeof Navigate> | KnownGapNavigateProps->;-type _NavigatePropsCovered = Expect<Equal<UnaccountedNavigateProps, never>>;--// The facade's <Outlet> does not pass context down (no useOutletContext yet).-type KnownGapOutletProps = "context";-type UnaccountedOutletProps = Exclude<- keyof V7OutletProps,- keyof ComponentProps<typeof Outlet> | KnownGapOutletProps->;-type _OutletPropsCovered = Expect<Equal<UnaccountedOutletProps, never>>;--describe("router type conformance", () => {- it("is enforced by tsc, not at runtime", () => {- expect(true).toBe(true);- });-});diff --git a/frontend/src/metabase/router/conformance/use-location.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-location.conformance.unit.spec.tsxdeleted file mode 100644index c4ace9839fe..00000000000--- a/frontend/src/metabase/router/conformance/use-location.conformance.unit.spec.tsx+++ /dev/null@@ -1,38 +0,0 @@-import type { RouterApi } from "./test-utils";-import { runBoth } from "./test-utils";--// v7's runtime `Location` carries an extra, undocumented `mask` field, so the-// differential compares the documented field values rather than the raw key set.-// The exact 5-field shape is locked down in use-location.unit.spec.tsx.-function LocationProbe({ api }: { api: RouterApi }) {- const location = api.useLocation();- return (- <div>- <span data-testid="rr-pathname">{location.pathname}</span>- <span data-testid="rr-search">{location.search}</span>- <span data-testid="rr-hash">{location.hash}</span>- <span data-testid="rr-state">{JSON.stringify(location.state)}</span>- </div>- );-}--describe("router/useLocation conformance", () => {- it("matches v7 for a url with search and hash", async () => {- const { facade, v7 } = await runBoth(LocationProbe, {- initialRoute: "/foo/bar?x=1&y=2#section",- facadePath: "foo/bar",- v7Path: "foo/bar",- });- expect(facade).toEqual(v7);- });-- it("matches v7's Location field set and null state default", async () => {- const { facade, v7 } = await runBoth(LocationProbe, {- initialRoute: "/foo/bar",- facadePath: "foo/bar",- v7Path: "foo/bar",- });- expect(facade).toEqual(v7);- expect(facade["rr-state"]).toBe("null");- });-});diff --git a/frontend/src/metabase/router/conformance/use-navigate.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-navigate.conformance.unit.spec.tsxdeleted file mode 100644index a0c30196332..00000000000--- a/frontend/src/metabase/router/conformance/use-navigate.conformance.unit.spec.tsx+++ /dev/null@@ -1,134 +0,0 @@-import userEvent from "@testing-library/user-event";-import { useEffect, useState } from "react";--import { screen } from "__support__/ui";--import type { RouterApi } from "./test-utils";-import { runBoth } from "./test-utils";--function NavigateProbe({ api }: { api: RouterApi }) {- const navigate = api.useNavigate();- const location = api.useLocation();- return (- <div>- <span data-testid="rr-pathname">{location.pathname}</span>- <span data-testid="rr-search">{location.search}</span>- <span data-testid="rr-hash">{location.hash}</span>- <span data-testid="rr-state">{JSON.stringify(location.state)}</span>- <button onClick={() => navigate("/foo")}>push</button>- <button onClick={() => navigate("/bar", { state: { from: "here" } })}>- push-state- </button>- <button onClick={() => navigate({ pathname: "/obj", search: "?x=1" })}>- push-object- </button>- <button onClick={() => navigate("/bar?x=1", { state: { from: "here" } })}>- push-string-query-state- </button>- <button onClick={() => navigate("/baz", { replace: true })}>- replace- </button>- <button onClick={() => navigate(-1)}>back</button>- </div>- );-}--// v7's `useNavigate` lists the current pathname in its callback dependencies, so-// the returned `navigate` gets a new identity on every navigation and anything-// depending on it (an effect, or `<Navigate>`) re-runs per navigation. The-// facade matches this, so a `[navigate]` effect runs the same number of times.-function EffectCountProbe({ api }: { api: RouterApi }) {- const navigate = api.useNavigate();- const location = api.useLocation();- const [runs, setRuns] = useState(0);- useEffect(() => {- setRuns((count) => count + 1);- }, [navigate]);- return (- <div>- <span data-testid="rr-effect-runs">{runs}</span>- <span data-testid="rr-pathname">{location.pathname}</span>- <button onClick={() => navigate("/next")}>go</button>- </div>- );-}--const click = (name: string) =>- userEvent.click(screen.getByRole("button", { name }));--describe("router/useNavigate conformance", () => {- it("matches v7 when pushing a string destination", async () => {- const { facade, v7 } = await runBoth(NavigateProbe, {- initialRoute: "/start",- interact: () => click("push"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/foo");- });-- it("matches v7 when attaching state to a string destination", async () => {- const { facade, v7 } = await runBoth(NavigateProbe, {- initialRoute: "/start",- interact: () => click("push-state"),- });- expect(facade).toEqual(v7);- expect(facade["rr-state"]).toBe(JSON.stringify({ from: "here" }));- });-- it("matches v7 when navigating to an object destination", async () => {- const { facade, v7 } = await runBoth(NavigateProbe, {- initialRoute: "/start",- interact: () => click("push-object"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/obj");- expect(facade["rr-search"]).toBe("?x=1");- });-- it("matches v7 when a string destination carries both a query and state", async () => {- const { facade, v7 } = await runBoth(NavigateProbe, {- initialRoute: "/start",- interact: () => click("push-string-query-state"),- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/bar");- expect(facade["rr-search"]).toBe("?x=1");- expect(facade["rr-state"]).toBe(JSON.stringify({ from: "here" }));- });-- it("matches v7 when replacing then going back", async () => {- const { facade, v7 } = await runBoth(NavigateProbe, {- initialRoute: "/start",- interact: async () => {- await click("push"); // /foo- await click("replace"); // replaces /foo with /baz- await click("back"); // back past the replaced entry- },- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/start");- });-- it("matches v7 when moving through history with a numeric delta", async () => {- const { facade, v7 } = await runBoth(NavigateProbe, {- initialRoute: "/start",- interact: async () => {- await click("push"); // /foo- await click("back"); // navigate(-1)- },- });- expect(facade).toEqual(v7);- expect(facade["rr-pathname"]).toBe("/start");- });-- it("matches v7's navigate identity churn across a navigation", async () => {- const { facade, v7 } = await runBoth(EffectCountProbe, {- initialRoute: "/start",- interact: () => click("go"),- });- expect(facade).toEqual(v7);- // A `[navigate]` effect re-runs on the navigation because the identity- // changed, on both engines.- expect(Number(facade["rr-effect-runs"])).toBeGreaterThan(1);- });-});diff --git a/frontend/src/metabase/router/conformance/use-params.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-params.conformance.unit.spec.tsxdeleted file mode 100644index 2bd1d555574..00000000000--- a/frontend/src/metabase/router/conformance/use-params.conformance.unit.spec.tsx+++ /dev/null@@ -1,50 +0,0 @@-import type { RouterApi } from "./test-utils";-import { runBoth } from "./test-utils";--function ParamsProbe({ api }: { api: RouterApi }) {- const params = api.useParams();- return (- <div>- <span data-testid="rr-segmentId">{params.segmentId}</span>- <span data-testid="rr-fieldId">{params.fieldId}</span>- <span data-testid="rr-id">{params.id}</span>- <span data-testid="rr-splat">{params["*"]}</span>- <span data-testid="rr-has-splat-key">{String("splat" in params)}</span>- </div>- );-}--describe("router/useParams conformance", () => {- it("matches v7 for params matched by the route", async () => {- const path = "reference/segments/:segmentId/fields/:fieldId";- const { facade, v7 } = await runBoth(ParamsProbe, {- initialRoute: "/reference/segments/42/fields/7",- facadePath: path,- v7Path: path,- });- expect(facade).toEqual(v7);- expect(facade["rr-segmentId"]).toBe("42");- expect(facade["rr-fieldId"]).toBe("7");- });-- it("matches v7 when decoding a URI-encoded segment", async () => {- const { facade, v7 } = await runBoth(ParamsProbe, {- initialRoute: "/x/a%20b",- facadePath: "x/:id",- v7Path: "x/:id",- });- expect(facade).toEqual(v7);- expect(facade["rr-id"]).toBe("a b");- });-- it("matches v7 by exposing the splat under the `*` key", async () => {- const { facade, v7 } = await runBoth(ParamsProbe, {- initialRoute: "/files/a/b",- facadePath: "files/**",- v7Path: "files/*",- });- expect(facade).toEqual(v7);- expect(facade["rr-splat"]).toBe("a/b");- expect(facade["rr-has-splat-key"]).toBe("false");- });-});diff --git a/frontend/src/metabase/router/conformance/use-search-params.conformance.unit.spec.tsx b/frontend/src/metabase/router/conformance/use-search-params.conformance.unit.spec.tsxdeleted file mode 100644index 8f89558be7a..00000000000--- a/frontend/src/metabase/router/conformance/use-search-params.conformance.unit.spec.tsx+++ /dev/null@@ -1,143 +0,0 @@-import userEvent from "@testing-library/user-event";--import { screen } from "__support__/ui";--import type { RouterApi } from "./test-utils";-import { runBoth } from "./test-utils";--function SearchParamsProbe({ api }: { api: RouterApi }) {- const [searchParams, setSearchParams] = api.useSearchParams();- const location = api.useLocation();- return (- <div>- <span data-testid="rr-x">{searchParams.get("x")}</span>- <span data-testid="rr-y">{searchParams.get("y")}</span>- <span data-testid="rr-brand">- {searchParams.getAll("brand").join(",")}- </span>- <span data-testid="rr-pathname">{location.pathname}</span>- <span data-testid="rr-search">{location.search}</span>- <span data-testid="rr-hash">{location.hash}</span>- <button onClick={() => setSearchParams({ x: "2", y: "9" })}>set</button>- <button onClick={() => setSearchParams({ brand: ["nike", "reebok"] })}>- set-array- </button>- <button onClick={() => setSearchParams()}>clear</button>- <button- onClick={() =>- setSearchParams((prev) => {- prev.set("x", "3");- return prev;- })- }- >- update- </button>- </div>- );-}--function DefaultInitProbe({ api }: { api: RouterApi }) {- const [searchParams, setSearchParams] = api.useSearchParams({ page: "1" });- return (- <div>- <span data-testid="rr-page">{searchParams.get("page")}</span>- <span data-testid="rr-q">{searchParams.get("q")}</span>- <button onClick={() => setSearchParams({ q: "x" })}>set-other</button>- </div>- );-}--const click = (name: string) =>- userEvent.click(screen.getByRole("button", { name }));--const AT_FOO = { facadePath: "foo", v7Path: "foo" };--describe("router/useSearchParams conformance", () => {- it("matches v7 when reading the current query string", async () => {- const { facade, v7 } = await runBoth(SearchParamsProbe, {- ...AT_FOO,- initialRoute: "/foo?x=1",- });- expect(facade).toEqual(v7);- expect(facade["rr-x"]).toBe("1");- });-- it("matches v7 when setting new params", async () => {- const { facade, v7 } = await runBoth(SearchParamsProbe, {- ...AT_FOO,- initialRoute: "/foo?x=1",- interact: () => click("set"),- });- expect(facade).toEqual(v7);- expect(facade["rr-search"]).toBe("?x=2&y=9");- });-- it("matches v7 when expanding array values into repeated params", async () => {- const { facade, v7 } = await runBoth(SearchParamsProbe, {- ...AT_FOO,- initialRoute: "/foo",- interact: () => click("set-array"),- });- expect(facade).toEqual(v7);- expect(facade["rr-brand"]).toBe("nike,reebok");- });-- it("matches v7 for a functional updater over the previous params", async () => {- const { facade, v7 } = await runBoth(SearchParamsProbe, {- ...AT_FOO,- initialRoute: "/foo?x=1",- interact: () => click("update"),- });- expect(facade).toEqual(v7);- expect(facade["rr-x"]).toBe("3");- });-- it("matches v7 when clearing the query", async () => {- const { facade, v7 } = await runBoth(SearchParamsProbe, {- ...AT_FOO,- initialRoute: "/foo?x=1",- interact: () => click("clear"),- });- expect(facade).toEqual(v7);- expect(facade["rr-search"]).toBe("");- });-- it("matches v7's handling of the existing hash when setting params", async () => {- const { facade, v7 } = await runBoth(SearchParamsProbe, {- ...AT_FOO,- initialRoute: "/foo?x=1#section",- interact: () => click("set"),- });- expect(facade).toEqual(v7);- });-- it("matches v7 when filling in a default the URL is missing", async () => {- const { facade, v7 } = await runBoth(DefaultInitProbe, {- ...AT_FOO,- initialRoute: "/foo",- });- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("1");- });-- it("matches v7 when the URL value wins over the default", async () => {- const { facade, v7 } = await runBoth(DefaultInitProbe, {- ...AT_FOO,- initialRoute: "/foo?page=5",- });- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("5");- });-- it("matches v7 when a default stops being merged after a set", async () => {- const { facade, v7 } = await runBoth(DefaultInitProbe, {- ...AT_FOO,- initialRoute: "/foo",- interact: () => click("set-other"),- });- expect(facade).toEqual(v7);- expect(facade["rr-page"]).toBe("");- expect(facade["rr-q"]).toBe("x");- });-});diff --git a/frontend/src/metabase/router/engine.ts b/frontend/src/metabase/router/engine.tsdeleted file mode 100644index 9db972707cc..00000000000--- a/frontend/src/metabase/router/engine.ts+++ /dev/null@@ -1,14 +0,0 @@-export type RouterEngine = "v3" | "v7";--/**- * Which router engine to run: the legacy react-router v3 engine, or the v7- * engine behind the `use-v7-router` flag.- *- * Read straight from `window.MetabaseBootstrap` rather than the redux settings- * slice so it is available at mount, before the store exists (the router is- * wired at the very top of `app.js`). Toggling the setting off is the instant- * rollback path.- */-export function getRouterEngine(): RouterEngine {- return window.MetabaseBootstrap?.["use-v7-router"] === true ? "v7" : "v3";-}diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.tsindex 648babc1c3f..83b547e2b00 100644--- a/frontend/src/metabase/router/index.ts+++ b/frontend/src/metabase/router/index.ts@@ -1,15 +1,12 @@-export * from "./engine";export * from "./Link";export * from "./middleware";export * from "./navigation";export * from "./Navigate";-export * from "./react-router";export * from "./redirect";export * from "./router-link";export * from "./route";export * from "./Outlet";export * from "./routing-reducer";-export * from "./sync";export * from "./RouterProvider";export * from "./types";export * from "./use-location";@@ -18,3 +15,4 @@ export * from "./use-params";export * from "./use-router";export * from "./use-search-params";export * from "./with-route-props";+export { getRawBrowserHistory } from "./v7/blocking-history";diff --git a/frontend/src/metabase/router/react-router.ts b/frontend/src/metabase/router/react-router.tsdeleted file mode 100644index 4385c492ff3..00000000000--- a/frontend/src/metabase/router/react-router.ts+++ /dev/null@@ -1,53 +0,0 @@-// The single module that imports the `react-router` package directly. The rest-// of the app reaches these symbols through `metabase/router`, so later phases can-// swap the engine behind this seam without touching call sites.-//-// The v7-shaped API (useNavigate, useLocation, Link, Navigate, Outlet, Route, ...)-// lives in the sibling facade modules. This file only re-exports the raw v3 symbols-// that have not been given a v7 shape yet (withRouter, history helpers, the route-// builders the `Route`/`redirect` shims are built on) plus the raw Link/LinkProps-// under `Router`-prefixed names for the few call sites that need the unstyled-// primitive.-import type { RouteProps as BaseRouteProps } from "react-router";--export {- // The raw v3 `<Link>`. The public `RouterLink` (router-link.tsx) is engine-aware- // and renders v7's `<Link>` on the v7 engine, so v3's is exported under a private- // name for that wrapper to fall back to on the v3 engine.- Link as V3RouterLink,- // The raw v3 `<Route>`, used by the `Route` shim to run v3's route builder over- // a `<Route index>` element without recursing back into the shim's own builder.- Route as ReactRouterRoute,- Router,- browserHistory,- createMemoryHistory,- createRoutes,- formatPattern,- useRouterHistory,- // The public facade no longer exposes `withRouter`; only `RouterProvider`'s v3- // bootstrap still needs the raw HOC to seed the router context.- withRouter as reactRouterWithRouter,-} from "react-router";--// v3's own path matcher, used to work out how much of the URL each matched route-// accounts for. Its pattern syntax has corners a hand-rolled parser gets wrong-// (optional groups like `database(/:databaseId)`, splats), so the engine's-// matcher is the only safe reader of it. Goes away with the engine swap.-export { matchPattern } from "react-router/lib/PatternUtils";--export type {- InjectedRouter,- LinkProps as RouterLinkProps,- PlainRoute,- RouteComponent,- WithRouterProps,-} from "react-router";--/**- * v3's route lifecycle hooks. They have no v7 equivalent, and the app now does- * this work in components and effects instead, so they are dropped from the route- * props to keep them from coming back.- */-type LifecycleHook = "onEnter" | "onChange" | "onLeave";--export type RouteProps = Omit<BaseRouteProps, LifecycleHook>;diff --git a/frontend/src/metabase/router/redirect.tsx b/frontend/src/metabase/router/redirect.tsxindex 56c1301ba61..b8d7cde8cbf 100644--- a/frontend/src/metabase/router/redirect.tsx+++ b/frontend/src/metabase/router/redirect.tsx@@ -1,11 +1,26 @@import { useState } from "react";import { Navigate } from "./Navigate";-import { type PlainRoute, formatPattern } from "./react-router";+import type { PlainRoute } from "./types";import { useRouter } from "./use-router";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.splat ?? "");+}+function RedirectRoute({ to }: { to: string }): JSX.Element {const { routes, params, location } = useRouter();diff --git a/frontend/src/metabase/router/resolve-to.ts b/frontend/src/metabase/router/resolve-to.tsindex d0153319b36..08f04d04bd1 100644--- a/frontend/src/metabase/router/resolve-to.ts+++ b/frontend/src/metabase/router/resolve-to.ts@@ -1,54 +1,18 @@-import { type PlainRoute, matchPattern } from "./react-router";-import type { Path, To } from "./types";+import type { Path, PlainRoute, To } from "./types";import { parsePath } from "./utils";/**- * The URL prefix each matched route accounts for, mirroring react-router v7's- * `match.pathnameBase`. Resolving `".."` walks this list rather than the URL,- * so a route whose path spans several segments (`pulse/:pulseId/archive`) is- * left in a single step, and a pathless route is left in no steps at all.+ * The URL prefix each matched route accounts for. v7 computes this per matched+ * route as `match.pathname`, which `RouterBridge` stashes on each stub as+ * `pathnameBase`, so read it directly rather than re-matching patterns.*- * How much of the URL a route accounts for is measured with v3's own- * `matchPattern` rather than by counting `/`. A v3 pattern segment does not map- * to one URL segment: `database(/:databaseId)(/schema/:schemaName)` matches- * anything from `database` to `database/1/schema/public`.- *- * A splat (`*`, `:entity_id(**)`) swallows the rest of the URL, so that route's- * own entry covers the splat where v7's `pathnameBase` would stop before it.- * `".."` reads the parent's entry rather than the route's own, so it still- * climbs correctly out of a splat route.+ * Resolving `".."` walks this list rather than the URL, so a route whose path+ * spans several segments (`pulse/:pulseId/archive`) is left in a single step, a+ * pathless route is left in no steps at all (v7 gives it its parent's pathname),+ * and a splat route's entry covers the splat (v7's `match.pathname` includes it).*/-export function getRoutePathnames(- routes: PlainRoute[],- locationPathname: string,-): string[] {- let matched = "";- let remaining = locationPathname;-- return routes.map((route) => {- const path = route.path;- if (path) {- // v3 matches an absolute child path against the whole pathname rather- // than against what its parents left over.- if (path.startsWith("/")) {- matched = "";- remaining = locationPathname;- }-- const match = matchPattern(path, remaining);- if (match) {- // `matchPattern` hands back the separator at the head of the remainder,- // so what it consumed is the rest of the string.- const consumed = remaining.slice(- 0,- remaining.length - match.remainingPathname.length,- );- matched += consumed;- remaining = match.remainingPathname;- }- }- return withoutTrailingSlash(matched);- });+export function getRoutePathnames(routes: PlainRoute[]): string[] {+ return routes.map((route) => withoutTrailingSlash(route.pathnameBase ?? ""));}function withoutTrailingSlash(pathname: string): string {diff --git a/frontend/src/metabase/router/resolve-to.unit.spec.ts b/frontend/src/metabase/router/resolve-to.unit.spec.tsindex ca2417ae9b6..416734d1298 100644--- a/frontend/src/metabase/router/resolve-to.unit.spec.ts+++ b/frontend/src/metabase/router/resolve-to.unit.spec.ts@@ -1,31 +1,32 @@-import type { PlainRoute } from "./react-router";import { getRoutePathnames, resolveTo } from "./resolve-to";+import type { PlainRoute } from "./types";-// getRoutePathnames only reads `path`; the rest of PlainRoute is irrelevant here.-const route = (path?: string) => ({ path }) as PlainRoute;+// A matched route as `RouterBridge` builds it: `pathnameBase` is the URL prefix+// v7 matched for that route (`match.pathname`). getRoutePathnames only reads it.+const route = (pathnameBase?: string) => ({ pathnameBase }) as PlainRoute;// The pathname `".."` resolves to, from the deepest of `routes`.const parentOf = (routes: PlainRoute[], pathname: string) =>- resolveTo("..", getRoutePathnames(routes, pathname), pathname, false)- .pathname;+ resolveTo("..", getRoutePathnames(routes), pathname, false).pathname;describe("getRoutePathnames", () => {- it("gives a route with no path the pathname of its parent", () => {+ it("reads each route's matched pathname, without a trailing slash", () => {expect(- getRoutePathnames(- [route(), route("collection/:slug"), route(), route("archive")],- "/collection/5/archive",- ),+ getRoutePathnames([+ route("/"),+ route("/collection/5"),+ route("/collection/5/"),+ route("/collection/5/archive"),+ ]),).toEqual(["/", "/collection/5", "/collection/5", "/collection/5/archive"]);});- it("matches an absolute child path against the whole pathname", () => {+ it("gives a pathless route the empty base v7 reports as its parent's", () => {+ // v7 gives a pathless (layout) route its parent's `match.pathname`, so its+ // entry equals the neighbour rather than adding a step.expect(- getRoutePathnames(- [route("/model/:slug/detail"), route("actions"), route("new")],- "/model/5-orders/detail/actions/new",- )[1],- ).toBe("/model/5-orders/detail/actions");+ getRoutePathnames([route("/collection/5"), route("/collection/5")]),+ ).toEqual(["/collection/5", "/collection/5"]);});});@@ -33,7 +34,7 @@ describe("resolveTo", () => {it('climbs one route for ".."', () => {expect(parentOf(- [route("collection/:slug"), route("archive")],+ [route("/collection/5"), route("/collection/5/archive")],"/collection/5/archive",),).toBe("/collection/5");@@ -42,61 +43,45 @@ describe("resolveTo", () => {it("climbs a route whose path spans several segments", () => {expect(parentOf(- [route("account/notifications"), route("pulse/:pulseId/archive")],+ [+ route("/account/notifications"),+ route("/account/notifications/pulse/7/archive"),+ ],"/account/notifications/pulse/7/archive",),).toBe("/account/notifications");});- // v3 optional groups match a variable number of URL segments, so the number of- // `/` in the pattern says nothing about how much of the URL it accounts for.- describe("v3 optional groups", () => {- const databaseRoutes = (child: string) => [- route("data"),- route("database(/:databaseId)(/schema/:schemaName)(/table/:tableId)"),- route(child),- ];-- it("climbs past an optional group that matched nothing", () => {- expect(- parentOf(- databaseRoutes("impersonated/group/:groupId"),- "/data/database/1/impersonated/group/2",- ),- ).toBe("/data/database/1");- });-- it("climbs past optional groups that all matched", () => {- expect(- parentOf(- databaseRoutes("segmented/group/:groupId"),- "/data/database/1/schema/public/table/3/segmented/group/5",- ),- ).toBe("/data/database/1/schema/public/table/3");- });+ it("climbs out of a route whose match includes a splat", () => {+ // A splat route's `match.pathname` covers the swallowed tail, so `".."`+ // reads the parent's entry and lands above the whole splat route.+ expect(+ parentOf(+ [route("/collection"), route("/collection/entity/abc/def")],+ "/collection/entity/abc/def",+ ),+ ).toBe("/collection");+ });- it("climbs out of a route whose path ends in a splat", () => {- expect(- parentOf(- [route("collection"), route("entity/:entity_id(**)")],- "/collection/entity/abc/def",- ),- ).toBe("/collection");- });+ it('resolves a named relative target ("child") against the deepest match', () => {+ expect(+ resolveTo(+ "sibling",+ getRoutePathnames([route("/data/5"), route("/data/5/edit")]),+ "/data/5/edit",+ false,+ ).pathname,+ ).toBe("/data/5/edit/sibling");+ });- it("climbs past a group route with a partially matched optional tail", () => {- expect(- parentOf(- [- route("data"),- route(- "group(/:groupId)(/database/:databaseId)(/schema/:schemaName)",- ),- route("segmented/group/:groupId"),- ],- "/data/group/2/database/1/segmented/group/5",- ),- ).toBe("/data/group/2/database/1");- });+ it("passes an absolute target through untouched", () => {+ expect(+ resolveTo(+ "/browse/databases",+ getRoutePathnames([route("/data/5")]),+ "/data/5",+ false,+ ).pathname,+ ).toBe("/browse/databases");});});diff --git a/frontend/src/metabase/router/route.tsx b/frontend/src/metabase/router/route.tsxindex 6f04206adea..ea8ed25653b 100644--- a/frontend/src/metabase/router/route.tsx+++ b/frontend/src/metabase/router/route.tsx@@ -1,103 +1,31 @@-import {- type ComponentClass,- type ReactElement,- type ReactNode,- createElement,-} from "react";+import type { ComponentClass, ReactNode } from "react";-import { routeElementToComponent } from "./Outlet";-import {- type PlainRoute,- ReactRouterRoute,- type RouteProps,- createRoutes,-} from "./react-router";-import { translatePatternToV3 } from "./translate-pattern";+import type { RouteProps } from "./types";/**- * Props accepted by the `<Route>` element. Adds react-router v7's `index` and- * `element` on top of v3's route props. `index` registers the route as its- * parent's index route (what v3's `<IndexRoute>` did) and works with either- * `component` or `element`. `element` is bridged to a v3 `component` that renders- * it and exposes the matched child through `<Outlet/>`.+ * Props accepted by the `<Route>` element: react-router v7's `index` and+ * `element` on top of the shared route props. `index` registers the route as its+ * parent's index route.*/-// `component` is intentionally omitted: routes must use `element={<X/>}`. The-// bridge still sets a `component` on the built v3 route config internally, and-// the raw v3 `Route` (ReactRouterRoute) remains for the facade's own bootstrap.export type RouteElementProps = Omit<RouteProps, "component"> & {index?: boolean;element?: ReactNode;};-interface RouteConfigElement {- (props: RouteElementProps): null;- createRouteFromReactElement(- element: ReactElement<RouteElementProps>,- parentRoute?: PlainRoute,- ): PlainRoute | undefined;-}-/**- * The route object type, preserved for the call sites that annotate v3's injected+ * The route object type, preserved for the call sites that annotate the injected* `route` prop with `Route`.*/export type Route = ComponentClass<RouteProps>;/**- * react-router v7's `<Route>` shape running on the v3 engine. Like v3's `Route` it- * is route configuration and never renders. It adds support for the v7 `index`- * prop by registering the element as its parent's index route (what v3's- * `<IndexRoute>` did); every other prop behaves exactly as v3's `<Route>`.+ * react-router v7's `<Route>`. Like v3's it is route configuration and never+ * renders: `mapToV7` reads its props and rebuilds the tree as real v7 routes.** @see https://reactrouter.com/7.18.1/api/components/Route*/-export const Route: RouteConfigElement = Object.assign(- function Route(_props: RouteElementProps): null {- throw new Error(- "<Route> configures the route tree and is never rendered directly",- );- },- {- createRouteFromReactElement(- element: ReactElement<RouteElementProps>,- parentRoute?: PlainRoute,- ): PlainRoute | undefined {- // 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, 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 the- // route config so the bridge component can render it off the injected- // `route` prop, letting sibling routes that share a component reconcile- // instead of remounting. Goes away at the engine swap.- //- // The guard is `!== undefined`, not `!= null`, to match v7: an explicit- // `element={null}` renders nothing (bridged to a component that renders- // null), while an omitted `element` falls through to v3's render-children- // default, which is v7's implicit `<Outlet/>`.- if (route != null && route.element !== undefined) {- route.component = routeElementToComponent(route.element);- }-- if (index) {- if (parentRoute && route) {- parentRoute.indexRoute = route;- }- return undefined;- }- return route;- },- },-);+export function Route(_props: RouteElementProps): null {+ throw new Error(+ "<Route> configures the route tree and is never rendered directly",+ );+}diff --git a/frontend/src/metabase/router/router-link.tsx b/frontend/src/metabase/router/router-link.tsxindex 52dc8f77fe5..54182ad0702 100644--- a/frontend/src/metabase/router/router-link.tsx+++ b/frontend/src/metabase/router/router-link.tsx@@ -4,22 +4,17 @@ import {type LinkProps as V7LinkProps,NavLink as V7NavLink,useInRouterContext,-} from "react-router-v7";+} from "react-router";-import { type RouterLinkProps, V3RouterLink } from "./react-router";+import type { RouterLinkProps } from "./types";import { queryToSearch } from "./v7/location";-/**- * The app's `<Link>`, engine-aware.- *- * v3's `<Link>` reads v3's legacy React context, which only a v3 `<Router>`- * provides and which does not cross portals. On the v7 engine there is no v3- * router, so a v3 `<Link>` throws "rendered outside of a router context" the- * moment it is clicked (worst inside portaled modals). v7's `<Link>` uses modern- * context, provided by the engine's `<BrowserRouter>` and propagated through- * portals, so it works everywhere. Both collapse to v7's `<Link>` when the v3- * engine is deleted in Phase 4.- */+function hrefFor(target: V7LinkProps["to"]): string {+ if (typeof target === "string") {+ return target;+ }+ return `${target.pathname ?? ""}${target.search ?? ""}${target.hash ?? ""}`;+}type V3To = RouterLinkProps["to"];@@ -78,73 +73,63 @@ interface Props extends Omit<RouterLinkProps, "to"> {export const RouterLink = forwardRef<HTMLAnchorElement, Props>(function RouterLink({ to, innerRef, ...props }, ref) {const linkRef = ref ?? innerRef;- // Detect the engine from the mounted router rather than the flag, so the link- // matches whichever provider actually wraps it (the flag and the provider- // agree in the app; tests mount a provider directly).- const isV7Engine = useInRouterContext();+ const inRouter = useInRouterContext();- if (isV7Engine) {- // v3-only props v7's `<Link>` does not accept.- const { activeClassName, activeStyle, onlyActiveOnIndex, ...rest } =- props;+ // v3-only props v7's `<Link>` does not accept.+ const { activeClassName, activeStyle, onlyActiveOnIndex, ...rest } = props;- // A `<Link>` with no destination (`to` null or `""`) is used as a button: it- // navigates through its `onClick`. v7's `<Link>` would additionally navigate- // on click (an empty `to` resolves to the current route, or `/` from a- // top-level portal like a toast), clobbering any push the handler performs,- // so render a plain anchor instead. On v3 this matches `router.push("")` /- // `router.push(undefined)`, which are no-ops, so only the handler runs.- if (to == null || to === "") {- return <a {...rest} ref={linkRef} />;- }+ // A `<Link>` with no destination (`to` null or `""`) is used as a button: it+ // navigates through its `onClick`. v7's `<Link>` would additionally navigate+ // on click (an empty `to` resolves to the current route, or `/` from a+ // top-level portal like a toast), clobbering any push the handler performs,+ // so render a plain anchor instead. On v3 this matched `router.push("")` /+ // `router.push(undefined)`, which are no-ops, so only the handler runs.+ if (to == null || to === "") {+ return <a {...rest} ref={linkRef} />;+ }- const { to: v7To, state } = toV7Target(to);+ const { to: v7To, state } = toV7Target(to);- // v3's `<Link>` highlights itself when its route is active via- // `activeClassName`/`activeStyle` (and `onlyActiveOnIndex` for an exact- // match). v7 moved that to `<NavLink>`, so route it there when a call site- // asks for active styling; a plain `<Link>` would silently drop it.- if (activeClassName != null || activeStyle != null) {- const { className, style, ...navRest } = rest;- return (- <V7NavLink- {...navRest}- to={v7To}- state={state}- replace={false}- ref={linkRef}- end={onlyActiveOnIndex}- className={({ isActive }) =>- [className, isActive ? activeClassName : null]- .filter(Boolean)- .join(" ")- }- style={({ isActive }) =>- isActive ? { ...style, ...activeStyle } : style- }- />- );- }+ // v7's `<Link>` reads router context and throws without one. A component+ // rendered in isolation (common in unit tests) has no router, so fall back to+ // a plain anchor with the resolved href. The real app always mounts a router,+ // so this path never runs there.+ if (!inRouter) {+ return <a {...rest} href={hrefFor(v7To)} ref={linkRef} />;+ }- // 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.+ // v3's `<Link>` highlighted itself when its route was active via+ // `activeClassName`/`activeStyle` (and `onlyActiveOnIndex` for an exact+ // match). v7 moved that to `<NavLink>`, so route it there when a call site+ // asks for active styling; a plain `<Link>` would silently drop it.+ if (activeClassName != null || activeStyle != null) {+ const { className, style, ...navRest } = rest;return (- <V7Link- {...rest}+ <V7NavLink+ {...navRest}to={v7To}state={state}replace={false}ref={linkRef}+ end={onlyActiveOnIndex}+ className={({ isActive }) =>+ [className, isActive ? activeClassName : null]+ .filter(Boolean)+ .join(" ")+ }+ style={({ isActive }) =>+ isActive ? { ...style, ...activeStyle } : style+ }/>);}+ // 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 (- // `innerRef` is a valid v3 `<Link>` prop but is missing from its types.- // @ts-expect-error see https://github.com/remix-run/react-router/blob/v3.2.6/docs/API.md#innerref- <V3RouterLink {...props} to={to} innerRef={linkRef} />+ <V7Link {...rest} to={v7To} state={state} replace={false} ref={linkRef} />);},);diff --git a/frontend/src/metabase/router/router-link.unit.spec.tsx b/frontend/src/metabase/router/router-link.unit.spec.tsxindex 1f64534417d..4c7f81efcef 100644--- a/frontend/src/metabase/router/router-link.unit.spec.tsx+++ b/frontend/src/metabase/router/router-link.unit.spec.tsx@@ -4,8 +4,6 @@ import { renderWithProviders, screen } from "__support__/ui";import { useDispatch } from "metabase/redux";import { Link, Outlet, Route, push, useLocation } from "metabase/router";-import type { RouterEngine } from "./engine";-function Home() {const { pathname, key } = useLocation();const dispatch = useDispatch();@@ -41,124 +39,110 @@ const tree = (</Route>);-// A v3 `<Link>` reads v3's legacy router context, which the v7 engine does not-// provide, so it threw "rendered outside of a router context" on click. The-// engine-aware `RouterLink` renders v7's `<Link>` on v7, so clicking navigates on-// both engines.-describe.each<RouterEngine>(["v3", "v7"])(- "RouterLink on the %s engine",- (routerEngine) => {- it("navigates on click without throwing", async () => {- renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/",- });-- await userEvent.click(screen.getByRole("link", { name: "go" }));-- expect(await screen.findByTestId("other")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/other");+describe("RouterLink", () => {+ it("navigates on click without throwing", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/",+ });++ await userEvent.click(screen.getByRole("link", { name: "go" }));++ expect(await screen.findByTestId("other")).toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent("/other");+ });++ // Only the destination is asserted: v3's memory history leaves the bare path+ // literal in tests, though a real browser resolves it against the root the way+ // v7 now does.+ it("resolves a bare relative path against the root", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/",});- // Only the destination is asserted: v3's memory history leaves the bare path- // literal in tests, though a real browser resolves it against the root the way- // v7 now does.- it("resolves a bare relative path against the root", async () => {- renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/",- });+ await userEvent.click(screen.getByRole("link", { name: "bare" }));- await userEvent.click(screen.getByRole("link", { name: "bare" }));+ expect(await screen.findByTestId("other")).toBeInTheDocument();+ });- expect(await screen.findByTestId("other")).toBeInTheDocument();+ // Anchoring bare paths must not touch absolute URLs, or a docs link becomes+ // `/https:/www.metabase.com/...`.+ it("leaves absolute urls untouched", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/",});- // Anchoring bare paths must not touch absolute URLs, or a docs link becomes- // `/https:/www.metabase.com/...`.- it("leaves absolute urls untouched", async () => {- renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/",- });-- expect(screen.getByRole("link", { name: "external" })).toHaveAttribute(- "href",- "https://www.metabase.com/docs",- );- expect(screen.getByRole("link", { name: "mail" })).toHaveAttribute(- "href",- "mailto:[email protected]",- );+ expect(screen.getByRole("link", { name: "external" })).toHaveAttribute(+ "href",+ "https://www.metabase.com/docs",+ );+ expect(screen.getByRole("link", { name: "mail" })).toHaveAttribute(+ "href",+ "mailto:[email protected]",+ );+ });++ // 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, {+ withRouter: true,+ initialRoute: "/other",});- // 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, {- withRouter: true,- routerEngine,- initialRoute: "/other",- });+ await screen.findByTestId("other");+ const keyBefore = screen.getByTestId("location-key").textContent;- await screen.findByTestId("other");- const keyBefore = screen.getByTestId("location-key").textContent;+ await userEvent.click(screen.getByRole("link", { name: "go" }));- await userEvent.click(screen.getByRole("link", { name: "go" }));+ expect(screen.getByTestId("location-key")).not.toHaveTextContent(+ String(keyBefore),+ );+ });- expect(screen.getByTestId("location-key")).not.toHaveTextContent(- String(keyBefore),- );+ it("applies activeClassName to the link that matches the route", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/other",});- it("applies activeClassName to the link that matches the route", async () => {- renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/other",- });+ await screen.findByTestId("other");- await screen.findByTestId("other");+ // The exact-match home link is not active on /other; the section link is.+ expect(screen.getByText("home")).not.toHaveClass("is-active");+ expect(screen.getByText("section")).toHaveClass("is-active");+ });- // The exact-match home link is not active on /other; the section link is.- expect(screen.getByText("home")).not.toHaveClass("is-active");- expect(screen.getByText("section")).toHaveClass("is-active");+ it("does not navigate on its own when used as a button (no `to`)", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/",});- it("does not navigate on its own when used as a button (no `to`)", async () => {- renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/",- });+ // The click handler dispatches the navigation; the link itself must not+ // navigate, or on v7 it would clobber the push and never reach /other.+ await userEvent.click(screen.getByText("act"));- // The click handler dispatches the navigation; the link itself must not- // navigate, or on v7 it would clobber the push and never reach /other.- await userEvent.click(screen.getByText("act"));+ expect(await screen.findByTestId("other")).toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent("/other");+ });- expect(await screen.findByTestId("other")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/other");+ it("does not navigate when a button-like `to=''` link is clicked", async () => {+ renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/other",});- it("does not navigate when a button-like `to=''` link is clicked", async () => {- renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/other",- });-- await screen.findByTestId("other");+ await screen.findByTestId("other");- // On v7 an empty `to` resolved to "/" and navigated home, unmounting the- // current view. It must stay put so only the onClick handler runs.- await userEvent.click(screen.getByText("noop"));+ // On v7 an empty `to` resolved to "/" and navigated home, unmounting the+ // current view. It must stay put so only the onClick handler runs.+ await userEvent.click(screen.getByText("noop"));- expect(screen.getByTestId("other")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/other");- });- },-);+ expect(screen.getByTestId("other")).toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent("/other");+ });+});diff --git a/frontend/src/metabase/router/sync.ts b/frontend/src/metabase/router/sync.tsdeleted file mode 100644index 5fe95bf06f4..00000000000--- a/frontend/src/metabase/router/sync.ts+++ /dev/null@@ -1,53 +0,0 @@-import { LOCATION_CHANGE, type RouterState } from "./routing-reducer";-import type { History } from "./types";--// Only the slice of the redux store `sync` actually touches. Declared-// structurally rather than as `Store<State>` so this leaf does not instantiate-// RTK's store generic against the whole app state.-type RoutingStore = {- getState: () => { routing: RouterState };- dispatch: (action: { type: string; payload: unknown }) => unknown;- subscribe: (listener: () => void) => () => void;-};--/**- * Re-owned equivalent of react-router-redux's `syncHistoryWithStore`.- *- * Location flows history -> store: every history transition dispatches- * LOCATION_CHANGE so `state.routing.locationBeforeTransitions` tracks it. The- * returned history is enhanced so its `listen` is driven by the store, which is- * what the v3 <Router> subscribes to, keeping the rendered route in sync with- * redux.- */-export function syncHistoryWithStore(- history: History,- store: RoutingStore,-): History {- const getLocationInStore = () =>- store.getState().routing.locationBeforeTransitions;-- history.listen((location) => {- store.dispatch({ type: LOCATION_CHANGE, payload: location });- });-- // history@3 does not call listeners synchronously on subscribe, so mirror the- // initial location into the store ourselves.- store.dispatch({- type: LOCATION_CHANGE,- payload: history.getCurrentLocation(),- });-- return {- ...history,- listen(listener) {- let lastLocation = getLocationInStore();- return store.subscribe(() => {- const location = getLocationInStore();- if (location && location !== lastLocation) {- lastLocation = location;- listener(location);- }- });- },- };-}diff --git a/frontend/src/metabase/router/translate-pattern.conformance.unit.spec.ts b/frontend/src/metabase/router/translate-pattern.conformance.unit.spec.tsdeleted file mode 100644index 039dc1da0c9..00000000000--- a/frontend/src/metabase/router/translate-pattern.conformance.unit.spec.ts+++ /dev/null@@ -1,137 +0,0 @@-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.tsdeleted file mode 100644index a7a522d9aeb..00000000000--- a/frontend/src/metabase/router/translate-pattern.ts+++ /dev/null@@ -1,28 +0,0 @@-/**- * 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/router/types.ts b/frontend/src/metabase/router/types.tsindex 8b3cb6d5b4b..36deab3b11f 100644--- a/frontend/src/metabase/router/types.ts+++ b/frontend/src/metabase/router/types.ts@@ -1,3 +1,11 @@+import type {+ CSSProperties,+ ComponentClass,+ FunctionComponent,+ HTMLProps,+ ReactNode,+} from "react";+/*** The pathname, search, and hash values of a URL.*@@ -178,3 +186,90 @@ export type SetURLSearchParams = (| ((prev: URLSearchParams) => URLSearchParamsInit),navigateOptions?: NavigateOptions,) => void;++/**+ * A route's component. v3 accepted a class or function component; kept for the+ * call sites that annotate the injected `route` / `routes` props.+ */+export type RouteComponent = ComponentClass<any> | FunctionComponent<any>;++/**+ * The `<Route>` configuration props, re-homed from v3's `RouteProps`. The+ * lifecycle hooks (`onEnter` / `onChange` / `onLeave`) are intentionally absent:+ * they have no v7 equivalent and the app does that work in components now.+ */+export interface RouteProps<Props = any> {+ children?: ReactNode;+ path?: string;+ component?: RouteComponent;+ props?: Props;+}++/**+ * A route object as v3 exposed it on the injected `routes` branch. The v7+ * `RouterBridge` republishes the matched branch in this shape, adding+ * `pathnameBase`, the URL prefix the route accounts for (v7's `match.pathname`).+ */+export interface PlainRoute<Props = any> extends RouteProps<Props> {+ childRoutes?: PlainRoute[];+ indexRoute?: PlainRoute;+ pathnameBase?: string;+}++/**+ * A route-leave hook, v3's `setRouteLeaveHook` callback: it receives the+ * attempted destination and returns `false` to cancel the navigation.+ */+export type RouteHook = (nextLocation?: Location) => unknown;++/**+ * v3's imperative router, the `router` prop the facade injects. The v7+ * `RouterBridge` implements this shape over v7's `navigate`.+ */+export interface InjectedRouter {+ push(location: LocationDescriptor): void;+ replace(location: LocationDescriptor): void;+ go(n: number): void;+ goBack(): void;+ goForward(): void;+ // `route` is the route to scope the hook to. v3 typed it `any` (callers pass a+ // route stub, a `<Route>`, or nothing); the shim reads its `pathnameBase`.+ setRouteLeaveHook(route: any, hook: RouteHook): () => void;+ createPath(location: LocationDescriptor): string;+ createHref(location: LocationDescriptor): string;+ isActive(location: LocationDescriptor, indexOnly?: boolean): boolean;+}++/**+ * The router-injected props v3 passed to route components (`router`, `location`,+ * `params`, `routes`). The `RouterBridge` republishes them from the v7 match;+ * `withRouteProps` feeds them to legacy components.+ *+ * `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).+ */+export interface WithRouterProps<P = Record<string, string>, Q = any> {+ location: Location<Q>;+ params: P;+ router: InjectedRouter;+ routes: PlainRoute[];+}++/**+ * v3's function form of a `<Link to>`, kept because `RouterLink` still handles it.+ */+type ToLocationFunction = (location: Location) => LocationDescriptor;++/**+ * Props of the app's `<Link>`, re-homed from v3's `LinkProps`. `RouterLink` reads+ * `to` (and the active-styling props) and forwards the rest to the anchor.+ */+export interface RouterLinkProps extends HTMLProps<any> {+ to: LocationDescriptor | ToLocationFunction;+ activeClassName?: string;+ activeStyle?: CSSProperties;+ onlyActiveOnIndex?: boolean;+}diff --git a/frontend/src/metabase/router/use-navigate.ts b/frontend/src/metabase/router/use-navigate.tsindex 21e1d2d9f74..08bee8dde52 100644--- a/frontend/src/metabase/router/use-navigate.ts+++ b/frontend/src/metabase/router/use-navigate.ts@@ -46,7 +46,7 @@ export function useNavigate(): NavigateFunction {const path = resolveTo(to,- getRoutePathnames(routesRef.current, location.pathname),+ getRoutePathnames(routesRef.current),location.pathname,options.relative === "path",);diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsxindex 1afcf38cd21..be07da883f6 100644--- a/frontend/src/metabase/router/v7/RouterBridge.tsx+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx@@ -9,17 +9,18 @@ import {useLocation as useV7Location,useNavigate as useV7Navigate,useParams as useV7Params,-} from "react-router-v7";+} from "react-router";import { OutletContext, RouteContext } from "../Outlet";import { RouterContext } from "../RouterProvider";+import type { Route } from "../route";import type {+ Location as HistoryLocation,InjectedRouter,+ LocationDescriptor,PlainRoute,WithRouterProps,-} from "../react-router";-import type { Route } from "../route";-import type { Location as HistoryLocation, LocationDescriptor } from "../types";+} from "../types";import { registerLeaveHook } from "./blocking-history";import { toV3Location } from "./location";@@ -68,24 +69,24 @@ export function RouterBridge({// `route` changes, which closed it mid-interaction. Key on the matched branch.const matchesKey = matches.map((match) => {- // `handle` is typed `unknown`; we only ever put `{ v3Path }` on it.- const handle = match.route.handle as { v3Path?: string } | undefined;- return `${match.pathname}|${handle?.v3Path ?? ""}`;+ // `handle` is typed `unknown`; we only ever put `{ path, props }` on it.+ const handle = match.route.handle as { path?: string } | undefined;+ return `${match.pathname}|${handle?.path ?? ""}`;}).join(">");const routes = useMemo<RouteStub[]>(() =>matches.map((match) => {- // `handle` is typed `unknown`; we only ever put `{ v3Path, props }` on it.+ // `handle` is typed `unknown`; we only ever put `{ path, props }` on it.const handle = match.route.handle as- | { v3Path?: string; props?: PlainRoute["props"] }+ | { path?: string; props?: PlainRoute["props"] }| undefined;// The facade hooks read `route.path`; `pathnameBase` is the route's matched// pathname, which `setRouteLeaveHook` uses to scope its hook to this route.// `props` carries the arbitrary route props v3 exposed (the command palette// reads `route.props.disableCommandPalette`).return {- path: handle?.v3Path,+ path: handle?.path,props: handle?.props,pathnameBase: match.pathname,};diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsxindex 829c1aa7d07..92f7379f440 100644--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx@@ -5,7 +5,7 @@ import {Routes,UNSAFE_createBrowserHistory as createBrowserHistory,UNSAFE_createMemoryHistory as createMemoryHistory,-} from "react-router-v7";+} from "react-router";import { useDispatch } from "metabase/redux";import { getBasename } from "metabase/utils/basename";@@ -60,10 +60,9 @@ function useLocationMirror() {}/**- * react-router v7 hosting the app, declarative mode (Phase 3.1). Replaces the v3- * `<Router>` + `useRouterHistory` + `syncHistoryWithStore` stack behind the- * `use-v7-router` flag. Hosted on a blocking history so `setRouteLeaveHook`- * cancels navigation the way it does on v3.+ * react-router v7 hosting the app, declarative mode. Replaces the v3 `<Router>` ++ * `useRouterHistory` + `syncHistoryWithStore` stack. Hosted on a blocking history+ * so `setRouteLeaveHook` cancels navigation the way it did on v3.*/export function RouterProviderV7({ children }: PropsWithChildren): JSX.Element {// `v5Compat` makes the history notify its listeners on push/replace, which is@@ -110,9 +109,11 @@ export type MemoryTestHistory = ReturnType<typeof createMemoryTestHistory>;export function RouterProviderV7Memory({children,initialRoute,+ basename,history: providedHistory,}: PropsWithChildren<{initialRoute: string;+ basename?: string;history?: MemoryTestHistory;}>): JSX.Element {const [history] = useState(@@ -120,7 +121,11 @@ export function RouterProviderV7Memory({);const onLocationChange = useLocationMirror();return (- <SyncHistoryRouter history={history} onLocationChange={onLocationChange}>+ <SyncHistoryRouter+ history={history}+ basename={basename}+ onLocationChange={onLocationChange}+ ><V7RouterTree history={history}>{children}</V7RouterTree></SyncHistoryRouter>);diff --git a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsxindex b233ae7ee56..dee202d554f 100644--- a/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx+++ b/frontend/src/metabase/router/v7/SyncHistoryRouter.tsx@@ -5,7 +5,7 @@ import {type NavigationType,Router,type Location as V7Location,-} from "react-router-v7";+} from "react-router";type History = HistoryRouterProps["history"];diff --git a/frontend/src/metabase/router/v7/V7ReduxBridge.tsx b/frontend/src/metabase/router/v7/V7ReduxBridge.tsxindex acd4c59a6c0..a63c599414f 100644--- a/frontend/src/metabase/router/v7/V7ReduxBridge.tsx+++ b/frontend/src/metabase/router/v7/V7ReduxBridge.tsx@@ -4,7 +4,7 @@ import {useNavigationType,useLocation as useV7Location,useNavigate as useV7Navigate,-} from "react-router-v7";+} from "react-router";import { useDispatch } from "metabase/redux";diff --git a/frontend/src/metabase/router/v7/blocking-history.ts b/frontend/src/metabase/router/v7/blocking-history.tsindex 1d28b2b032b..9227876dddf 100644--- a/frontend/src/metabase/router/v7/blocking-history.ts+++ b/frontend/src/metabase/router/v7/blocking-history.ts@@ -2,8 +2,9 @@ import {type HistoryRouterProps,type To,type Location as V7Location,+ UNSAFE_createBrowserHistory as createBrowserHistory,parsePath,-} from "react-router-v7";+} from "react-router";import type { Location as HistoryLocation } from "../types";@@ -30,6 +31,20 @@ interface Registration {const registrations = new Set<Registration>();+let rawBrowserHistory: History | null = null;++/**+ * A plain browser history for imperative navigation outside the app's router+ * tree, replacing v3's global `browserHistory` singleton. The SDK data-app bundle+ * mounts no router, so it drives its iframe URL through this instead. Created+ * lazily on first use, so it never exists in the main app, where a second history+ * would fight the mounted router over `popstate`.+ */+export function getRawBrowserHistory(): History {+ rawBrowserHistory ??= createBrowserHistory({ v5Compat: true });+ return rawBrowserHistory;+}+/*** Register a leave hook. The v7 `setRouteLeaveHook` shim calls this, so the* leave-confirm modals block navigation on v7 the same way they do on v3.diff --git a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts b/frontend/src/metabase/router/v7/blocking-history.unit.spec.tsindex a14f70e02b0..a2045c5dcfe 100644--- a/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts+++ b/frontend/src/metabase/router/v7/blocking-history.unit.spec.ts@@ -1,4 +1,4 @@-import { UNSAFE_createMemoryHistory as createMemoryHistory } from "react-router-v7";+import { UNSAFE_createMemoryHistory as createMemoryHistory } from "react-router";import type { Location as HistoryLocation } from "../types";diff --git a/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx b/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsxdeleted file mode 100644index 40dd513fb64..00000000000--- a/frontend/src/metabase/router/v7/dual-engine.unit.spec.tsx+++ /dev/null@@ -1,160 +0,0 @@-import { useEffect } from "react";--import { renderWithProviders, screen, waitFor } from "__support__/ui";-import {- Outlet,- Route,- push,- useLocation,- useParams,- useRouter,-} from "metabase/router";-import { getLocation } from "metabase/selectors/routing";--import type { RouterEngine } from "../engine";--function Home() {- const { pathname } = useLocation();- return (- <div>- <span data-testid="location">{pathname}</span>- <Outlet />- </div>- );-}--function Page() {- const { id } = useParams();- return <span data-testid="page-id">{id}</span>;-}--// Registers a route-leave hook the way the leave-confirm modals do, cancelling-// the navigation when `block` is set.-function LeaveGuard({ block }: { block: boolean }) {- const { router, routes } = useRouter();- const route = routes.at(-1);- useEffect(- () => router.setRouteLeaveHook(route, () => (block ? false : undefined)),- [router, route, block],- );- return null;-}--const tree = (- <Route path="/" element={<Home />}>- <Route path="page/:id" element={<Page />} />- <Route path="other" element={<span data-testid="other">other</span>} />- </Route>-);--function setup(routerEngine: RouterEngine, initialRoute: string) {- return renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute,- });-}--describe.each<RouterEngine>(["v3", "v7"])(- "route tree on the %s engine",- (routerEngine) => {- it("matches a deep link and reads its params", async () => {- setup(routerEngine, "/page/7");- expect(await screen.findByTestId("page-id")).toHaveTextContent("7");- expect(screen.getByTestId("location")).toHaveTextContent("/page/7");- });-- it("navigates via dispatch(push())", async () => {- const { store } = setup(routerEngine, "/page/7");- expect(await screen.findByTestId("page-id")).toBeInTheDocument();-- store.dispatch(push("/other"));-- expect(await screen.findByTestId("other")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/other");- });- },-);--// setRouteLeaveHook must cancel navigation on both engines so the flag stays a-// reliable two-way switch: v3 blocks natively, v7 through the blocking history.-describe.each<RouterEngine>(["v3", "v7"])(- "route-leave blocking on the %s engine",- (routerEngine) => {- const blockingTree = (- <Route path="/" element={<Home />}>- <Route- path="page/:id"- element={- <>- <Page />- <LeaveGuard block />- </>- }- />- <Route path="other" element={<span data-testid="other">other</span>} />- </Route>- );-- const openTree = (- <Route path="/" element={<Home />}>- <Route- path="page/:id"- element={- <>- <Page />- <LeaveGuard block={false} />- </>- }- />- <Route path="other" element={<span data-testid="other">other</span>} />- </Route>- );-- it("cancels navigation while the hook returns false", async () => {- const { store } = renderWithProviders(blockingTree, {- withRouter: true,- routerEngine,- initialRoute: "/page/7",- });- expect(await screen.findByTestId("page-id")).toBeInTheDocument();-- store.dispatch(push("/other"));-- await new Promise((resolve) => setTimeout(resolve, 30));- expect(screen.queryByTestId("other")).not.toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/page/7");- });-- it("allows navigation when the hook does not block", async () => {- const { store } = renderWithProviders(openTree, {- withRouter: true,- routerEngine,- initialRoute: "/page/7",- });- expect(await screen.findByTestId("page-id")).toBeInTheDocument();-- store.dispatch(push("/other"));-- expect(await screen.findByTestId("other")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/other");- });- },-);--// v3 tests never wired `syncHistoryWithStore`, so `state.routing` only tracks the-// location on v7, through the redux bridge. This pins that the bridge feeds it.-describe("v7 redux bridge", () => {- it("mirrors the location into state.routing", async () => {- const { store } = setup("v7", "/page/7");- await waitFor(() => {- expect(getLocation(store.getState())?.pathname).toBe("/page/7");- });-- store.dispatch(push("/other"));-- await waitFor(() => {- expect(getLocation(store.getState())?.pathname).toBe("/other");- });- });-});diff --git a/frontend/src/metabase/router/v7/location.ts b/frontend/src/metabase/router/v7/location.tsindex ec164ad9432..04e20a5ce3c 100644--- a/frontend/src/metabase/router/v7/location.ts+++ b/frontend/src/metabase/router/v7/location.ts@@ -1,4 +1,4 @@-import type { Location as V7Location } from "react-router-v7";+import type { Location as V7Location } from "react-router";import type { Location as HistoryLocation } from "../types";diff --git a/frontend/src/metabase/router/v7/map-to-v7.tsx b/frontend/src/metabase/router/v7/map-to-v7.tsxindex 618592f71b1..608fc5c2b77 100644--- a/frontend/src/metabase/router/v7/map-to-v7.tsx+++ b/frontend/src/metabase/router/v7/map-to-v7.tsx@@ -5,11 +5,10 @@ import {type ReactNode,isValidElement,} from "react";-import { Route as V7Route } from "react-router-v7";+import { Route as V7Route } from "react-router";import type { RouteElementProps } from "../route";import { Route } from "../route";-import { translatePatternToV3 } from "../translate-pattern";import { RouterBridge } from "./RouterBridge";@@ -54,12 +53,11 @@ function toV7Route(element: ReactElement<RouteElementProps>): ReactElement {<RouterBridge v3Element={routeElement} />) : undefined;- // Keep the v3 path and the arbitrary route `props` on `handle`: v3 exposed both- // on the matched-route branch, and consumers still read them (the command- // palette reads `route.props.disableCommandPalette`).- const v3Path = path != null ? translatePatternToV3(path) : undefined;- const handle =- v3Path != null || props != null ? { v3Path, props } : undefined;+ // Keep the route `path` and the arbitrary route `props` on `handle`: the+ // matched-route branch the facade republishes exposes both, and consumers read+ // them (`redirect` reads `route.path`, the command palette reads+ // `route.props.disableCommandPalette`).+ const handle = path != null || props != null ? { path, props } : undefined;if (index) {return <V7Route index element={bridged} handle={handle} />;diff --git a/frontend/src/metabase/router/v7/navigator.ts b/frontend/src/metabase/router/v7/navigator.tsindex a869d651690..07ccfb491d0 100644--- a/frontend/src/metabase/router/v7/navigator.ts+++ b/frontend/src/metabase/router/v7/navigator.ts@@ -1,4 +1,4 @@-import type { NavigateFunction, NavigateOptions, To } from "react-router-v7";+import type { NavigateFunction, NavigateOptions, To } from "react-router";import type { RouterNavigator } from "../middleware";import type { Location as HistoryLocation, LocationDescriptor } from "../types";diff --git a/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx b/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsxindex c3287a95618..adafd315abb 100644--- a/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx+++ b/frontend/src/metabase/router/v7/route-leave-scope.unit.spec.tsx@@ -10,8 +10,6 @@ import {useRouter,} from "metabase/router";-import type { RouterEngine } from "../engine";-// Registers an always-blocking leave hook scoped to the route it is rendered on,// exactly as the leave-confirm modals do (guard on a parent layout route).function Guard() {@@ -48,36 +46,31 @@ const tree = (// v3's `setRouteLeaveHook` is scoped to the guarded route: it fires only when a// navigation leaves that route's subtree. So moving between sibling child routes// under the guarded layout is allowed, and only leaving the layout is blocked.-describe.each<RouterEngine>(["v3", "v7"])(- "route-scoped leave hook on the %s engine",- (routerEngine) => {- it("allows navigation that stays within the guarded route", async () => {- const { store } = renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/section/a",- });- expect(await screen.findByTestId("a")).toBeInTheDocument();-- store.dispatch(push("/section/b"));-- expect(await screen.findByTestId("b")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/section/b");+describe("route-scoped leave hook", () => {+ it("allows navigation that stays within the guarded route", async () => {+ const { store } = renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/section/a",});+ expect(await screen.findByTestId("a")).toBeInTheDocument();- it("blocks navigation that leaves the guarded route", async () => {- const { store } = renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/section/a",- });- expect(await screen.findByTestId("a")).toBeInTheDocument();+ store.dispatch(push("/section/b"));- store.dispatch(push("/other"));+ expect(await screen.findByTestId("b")).toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent("/section/b");+ });- await new Promise((resolve) => setTimeout(resolve, 30));- expect(screen.queryByTestId("other")).not.toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent("/section/a");+ it("blocks navigation that leaves the guarded route", async () => {+ const { store } = renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/section/a",});- },-);+ expect(await screen.findByTestId("a")).toBeInTheDocument();++ store.dispatch(push("/other"));++ await new Promise((resolve) => setTimeout(resolve, 30));+ expect(screen.queryByTestId("other")).not.toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent("/section/a");+ });+});diff --git a/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx b/frontend/src/metabase/router/v7/router-listen.unit.spec.tsxindex db6b7e4f21a..649b40541ea 100644--- a/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx+++ b/frontend/src/metabase/router/v7/router-listen.unit.spec.tsx@@ -3,7 +3,6 @@ import { useEffect, useState } from "react";import { renderWithProviders, screen } from "__support__/ui";import { Outlet, Route, push, useRouter } from "metabase/router";-import type { RouterEngine } from "../engine";import type { Location as HistoryLocation } from "../types";// Both engines expose `listen` at runtime; v3's `InjectedRouter` type omits it.@@ -38,22 +37,18 @@ const tree = (</Route>);-describe.each<RouterEngine>(["v3", "v7"])(- "router.listen on the %s engine",- (routerEngine) => {- it("fires the callback on navigation and stops after unsubscribe", async () => {- const { store } = renderWithProviders(tree, {- withRouter: true,- routerEngine,- initialRoute: "/",- });+describe("router.listen", () => {+ it("fires the callback on navigation and stops after unsubscribe", async () => {+ const { store } = renderWithProviders(tree, {+ withRouter: true,+ initialRoute: "/",+ });- await screen.findByTestId("seen");+ await screen.findByTestId("seen");- store.dispatch(push("/other"));+ store.dispatch(push("/other"));- await screen.findByText("other");- expect(screen.getByTestId("seen")).toHaveTextContent("/other");- });- },-);+ await screen.findByText("other");+ expect(screen.getByTestId("seen")).toHaveTextContent("/other");+ });+});diff --git a/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsxindex 3c475ecc1fe..0bdf96b9968 100644--- a/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx+++ b/frontend/src/metabase/router/v7/v7-engine.unit.spec.tsx@@ -1,5 +1,5 @@import userEvent from "@testing-library/user-event";-import { MemoryRouter } from "react-router-v7";+import { MemoryRouter } from "react-router";import { renderWithProviders, screen } from "__support__/ui";import {diff --git a/frontend/src/metabase/router/with-route-props.tsx b/frontend/src/metabase/router/with-route-props.tsxindex f666dbcfc36..cf9bb79634a 100644--- a/frontend/src/metabase/router/with-route-props.tsx+++ b/frontend/src/metabase/router/with-route-props.tsx@@ -1,9 +1,8 @@import type { ComponentType } from "react";import { useRoute } from "./Outlet";-import type { InjectedRouter, PlainRoute } from "./react-router";import type { Route } from "./route";-import type { Location, Params } from "./types";+import type { InjectedRouter, Location, Params, PlainRoute } from "./types";import { useRouter } from "./use-router";/**diff --git a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsx b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsxindex 3f18761e0b7..88cfac2c882 100644--- a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsx+++ b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/TransformGraphRunListPage.tsx@@ -1,6 +1,5 @@import { useDisclosure, useElementSize } from "@mantine/hooks";import cx from "classnames";-import type { Location } from "history";import { useCallback, useEffect, useMemo, useState } from "react";import { t } from "ttag";@@ -13,6 +12,7 @@ import { PaginationControls } from "metabase/common/components/PaginationControlimport { DataStudioBreadcrumbs } from "metabase/common/data-studio/components/DataStudioBreadcrumbs";import { PaneHeader } from "metabase/common/data-studio/components/PaneHeader";import { useDispatch } from "metabase/redux";+import type { Location } from "metabase/router";import { replace } from "metabase/router";import { DetailedViewSwitch } from "metabase/transforms/components/DetailedViewSwitch";import { POLLING_INTERVAL } from "metabase/transforms/constants";diff --git a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.ts b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.tsindex 70de18c9d42..4edb6e43184 100644--- a/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.ts+++ b/frontend/src/metabase/transforms/pages/TransformGraphRunListPage/utils.ts@@ -1,5 +1,4 @@-import type { Location } from "history";-+import type { Location } from "metabase/router";import * as Urls from "metabase/urls";import {SORT_DIRECTIONS,diff --git a/frontend/src/metabase/visualizations/components/legend/LegendLabel.unit.spec.tsx b/frontend/src/metabase/visualizations/components/legend/LegendLabel.unit.spec.tsxindex d4391a36e32..ee14e39a63c 100644--- a/frontend/src/metabase/visualizations/components/legend/LegendLabel.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/legend/LegendLabel.unit.spec.tsx@@ -1,8 +1,8 @@-import { fireEvent, render } from "@testing-library/react";+import { fireEvent } from "@testing-library/react";import type { ComponentProps } from "react";-import { screen } from "__support__/ui";-import { Route, Router, createMemoryHistory } from "metabase/router";+import { renderWithProviders, screen } from "__support__/ui";+import { Route } from "metabase/router";import { LegendLabel } from "./LegendLabel";@@ -12,25 +12,22 @@ describe("LegendLabel", () => {const onFocus = jest.fn();const onMouseEnter = jest.fn();- const history = createMemoryHistory();-- render(- <Router history={history}>- <Route- path="/"- element={- <LegendLabel- href="#hello"- onClick={onClick}- onFocus={onFocus}- onMouseEnter={onMouseEnter}- {...props}- >- Test- </LegendLabel>- }- />- </Router>,+ const { history } = renderWithProviders(+ <Route+ path="/"+ element={+ <LegendLabel+ href="#hello"+ onClick={onClick}+ onFocus={onFocus}+ onMouseEnter={onMouseEnter}+ {...props}+ >+ Test+ </LegendLabel>+ }+ />,+ { withRouter: true, initialRoute: "/" },);return { history, onClick, onFocus, onMouseEnter };@@ -39,7 +36,8 @@ describe("LegendLabel", () => {it("should be a link when onClick is defined", () => {const { onClick } = setup();- expect(screen.getByText("Test")).toHaveAttribute("href", "#hello");+ // A hash-only target resolves against the current pathname.+ expect(screen.getByText("Test")).toHaveAttribute("href", "/#hello");fireEvent.click(screen.getByText("Test"));expect(onClick).toHaveBeenCalled();@@ -50,7 +48,7 @@ describe("LegendLabel", () => {expect(screen.getByText("Test")).not.toHaveAttribute("href");fireEvent.click(screen.getByText("Test"));- expect(history.getCurrentLocation().pathname).toBe("/");- expect(history.getCurrentLocation().hash).toBe("");+ expect(history?.getCurrentLocation().pathname).toBe("/");+ expect(history?.getCurrentLocation().hash).toBe("");});});diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsxindex 0b3f5c41d05..b6000ced7f9 100644--- a/frontend/test/__support__/ui.tsx+++ b/frontend/test/__support__/ui.tsx@@ -8,8 +8,6 @@ import {render as testingLibraryRender,waitFor,} from "@testing-library/react";-import type { History } from "history";-import { createMemoryHistory } from "history";import {Children,Fragment,@@ -29,7 +27,6 @@ import { Api } from "metabase/api";import { useUpdateSettingMutation } from "metabase/api/settings";import { UndoListing } from "metabase/common/components/UndoListing";import { baseStyle } from "metabase/css/core/base.styled";-import { HistoryProvider } from "metabase/history";import { makeMainReducers } from "metabase/reducers-main";import { publicReducers } from "metabase/reducers-public";import { MetabaseReduxProvider } from "metabase/redux";@@ -37,13 +34,11 @@ import type { State } from "metabase/redux/store";import { createMockState } from "metabase/redux/store/mocks";import {type Action,+ type History,type LocationDescriptor,Route,- type RouterEngine,- RouterProvider,routerMiddleware,routing as routingReducer,- useRouterHistory,} from "metabase/router";import {type MemoryTestHistory,@@ -78,8 +73,6 @@ export interface RenderWithProvidersOptions {initialRoute?: string;storeInitialState?: Partial<State>;withRouter?: boolean;- /** Which router engine hosts the tree when `withRouter` is set. Defaults to v7. */- routerEngine?: RouterEngine;/** Renders children wrapped with kbar provider */withKBar?: boolean;withDND?: boolean;@@ -100,7 +93,6 @@ export function renderWithProviders(initialRoute = "/",storeInitialState = {},withRouter = false,- routerEngine = "v7",withKBar = false,withDND = false,withUndos = false,@@ -114,7 +106,6 @@ export function renderWithProviders(initialRoute,storeInitialState,withRouter,- routerEngine,withKBar,withDND,withUndos,@@ -141,7 +132,6 @@ export function renderHookWithProviders<TProps, TResult>(initialRoute = "/",storeInitialState = {},withRouter = false,- routerEngine = "v7",withKBar = false,withDND = false,withUndos = false,@@ -159,7 +149,6 @@ export function renderHookWithProviders<TProps, TResult>(initialRoute,storeInitialState,withRouter,- routerEngine,withKBar,withDND,withUndos,@@ -190,14 +179,12 @@ export function getTestStoreAndWrapper({initialRoute,storeInitialState,withRouter,- routerEngine = "v7",withKBar,withDND,withUndos,customReducers,theme,}: GetTestStoreAndWrapperOptions) {- const isV7Router = withRouter && routerEngine === "v7";let { routing, ...initialState }: Partial<State> =createMockState(storeInitialState);@@ -206,22 +193,12 @@ export function getTestStoreAndWrapper({initialState = _.pick(initialState, ...publicReducerNames);}- // We need to call `useRouterHistory` to ensure the history has a `query` object,- // since some components and hooks rely on it to read/write query params.- // eslint-disable-next-line react-hooks/rules-of-hooks- const browserHistory = useRouterHistory(createMemoryHistory)({- entries: [initialRoute],- });- // On v7 the harness owns the memory history (rather than the provider creating- // it internally) so specs still get a handle to drive and assert against.- const v7History = isV7Router+ // The harness owns the memory history (rather than the provider creating it+ // internally) so specs still get a handle to drive and assert against.+ const v7History = withRouter? createMemoryTestHistory(initialRoute): undefined;- const history = !withRouter- ? undefined- : v7History- ? createV3HistoryAdapter(v7History)- : browserHistory;+ const history = v7History ? createV3HistoryAdapter(v7History) : undefined;let reducers;@@ -239,12 +216,7 @@ export function getTestStoreAndWrapper({reducers = { ...reducers, ...customReducers };}- // Drive navigation through v3 history or the v7 navigator, matching the engine.- const routerNavigator = isV7Router- ? createV7Navigator()- : history- ? history- : undefined;+ const routerNavigator = withRouter ? createV7Navigator() : undefined;const storeMiddleware = _.compact([Api.middleware,routerNavigator && routerMiddleware(routerNavigator),@@ -263,10 +235,8 @@ export function getTestStoreAndWrapper({<TestWrapper{...props}store={store}- history={history}v7History={v7History}withRouter={withRouter}- routerEngine={routerEngine}initialRoute={initialRoute}withDND={withDND}withUndos={withUndos}@@ -317,10 +287,8 @@ const TestColorSchemeProvider = ({ children }: React.PropsWithChildren) => {export function TestWrapper({children,store,- history,v7History,withRouter,- routerEngine = "v7",initialRoute = "/",withKBar,withDND,@@ -331,10 +299,8 @@ export function TestWrapper({}: {children: React.ReactElement;store: any;- history?: History;v7History?: MemoryTestHistory;withRouter: boolean;- routerEngine?: RouterEngine;initialRoute?: string;withKBar: boolean;withDND: boolean;@@ -370,8 +336,6 @@ export function TestWrapper({<MaybeKBar hasKBar={withKBar}><MaybeRouterhasRouter={withRouter}- routerEngine={routerEngine}- history={history}v7History={v7History}initialRoute={initialRoute}>@@ -452,43 +416,29 @@ function childrenAreRouteTree(children: React.ReactNode): boolean {function MaybeRouter({children,hasRouter,- routerEngine,- history,v7History,initialRoute,}: {children: React.ReactElement;hasRouter: boolean;- routerEngine: RouterEngine;- history?: History;v7History?: MemoryTestHistory;initialRoute: string;}): JSX.Element {if (!hasRouter) {return children;}- if (routerEngine === "v7") {- // Tests pass either a `<Route>` tree (rendered as-is) or a bare component.- // v7's `<Routes>` only renders `<Route>` children, so wrap a bare component in- // a catch-all route, matching how the v3 harness rendered it directly.- const content = childrenAreRouteTree(children) ? (- children- ) : (- <Route path="*" element={children} />- );- return (- <RouterProviderV7Memory initialRoute={initialRoute} history={v7History}>- {content}- </RouterProviderV7Memory>- );- }- if (!history) {- return children;- }+ // Tests pass either a `<Route>` tree (rendered as-is) or a bare component.+ // `<Routes>` only renders `<Route>` children, so wrap a bare component in a+ // catch-all route.+ const content = childrenAreRouteTree(children) ? (+ children+ ) : (+ <Route path="*" element={children} />+ );return (- <HistoryProvider history={history}>- <RouterProvider>{children}</RouterProvider>- </HistoryProvider>+ <RouterProviderV7Memory initialRoute={initialRoute} history={v7History}>+ {content}+ </RouterProviderV7Memory>);}diff --git a/package.json b/package.jsonindex c7acbe5fc89..d0af58cc3f3 100644--- a/package.json+++ b/package.json@@ -76,7 +76,6 @@"@tiptap/starter-kit": "^3.2.0","@tiptap/suggestion": "^3.2.0","@types/js-yaml": "^4.0.9",- "@types/react-router": "3.0.27","@uiw/react-codemirror": "^4.23.6","@visx/axis": "^3.10.1","@visx/clip-path": "^3.3.0",@@ -111,7 +110,6 @@"formik": "^2.4.5","frimousse": "^0.3.0","fuse.js": "^7.1.0",- "history": "3","html2canvas-pro": "^2.0.2","icepick": "2.4.0","iframe-resizer": "~4.3.2",@@ -155,7 +153,6 @@"react-qr-code": "^2.0.15","react-redux": "^9.1.2","react-resizable": "^3.1.3",- "react-router": "3","react-transition-group": "^4.4.5","react-use": "^17.5.1","react-virtualized": "9.22.6",@@ -390,7 +387,7 @@"raf": "^3.4.0","react-docgen-typescript-plugin": "^1.0.6","react-refresh": "^0.14.2",- "react-router-v7": "npm:[email protected]",+ "react-router": "7.18.1","reg-cli": "^0.17.7","semver": "^7.6.3","shadow-cljs": "^3.3.5",diff --git a/src/metabase/appearance/settings.clj b/src/metabase/appearance/settings.cljindex 9ee2238aeda..f1c807f5cc6 100644--- a/src/metabase/appearance/settings.clj+++ b/src/metabase/appearance/settings.clj@@ -46,14 +46,6 @@:audit :getter:export? true)-(defsetting use-v7-router- (deferred-tru "Serve the app with the react-router v7 engine instead of the legacy v3 engine. Toggle off for an instant rollback.")- :type :boolean- :default true- :visibility :public- :export? false- :doc false)-(defn- coerce-to-relative-url"Get the path of a given URL if the URL contains an origin.Otherwise make the landing-page a relative path."