Skip to content

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

Flip the unit-test harness to the v7 router engine (#78306)

Romeo Van Snick5461b53d5506
diff --git a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.unit.spec.tsx
index 36f1912a3d5..4c944f0dead 100644
--- a/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/schema_viewer/components/SchemaViewer/components/SchemaPickerInput/SchemaPickerInput.unit.spec.tsx
@@ -74,8 +74,10 @@ function setup({ databaseId, schema }: SetupOpts) {
const onSchemaChange = jest.fn();
const { history } = renderWithProviders(
+ // Catch-all so the picker stays mounted after it navigates to select a
+ // schema; the test reopens it and checks the database list.
<Route
- path="/"
+ path="*"
element={
<SchemaPickerInput
databaseId={databaseId}
diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjs
index 0344fd06eff..45ed494e844 100644
--- a/frontend/lint/module-boundaries.mjs
+++ b/frontend/lint/module-boundaries.mjs
@@ -275,6 +275,7 @@ const elements = [
"frontend/src/metabase/reducers-common.ts",
"frontend/src/metabase/reducers-public.ts",
"frontend/src/metabase/routes.tsx",
+ "frontend/src/metabase/routes.unit.spec.tsx",
"frontend/src/metabase/routes-embed.tsx",
"frontend/src/metabase/LoadCurrentUser.tsx",
"frontend/src/metabase/LoadCurrentUser.unit.spec.tsx",
diff --git a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
index 1b5121e5839..f581f0a6bd9 100644
--- a/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useConfirmOnRouteLeave.unit.spec.tsx
@@ -25,10 +25,10 @@ describe("useConfirmOnRouteLeave", () => {
const PageA = () => <div>Page A</div>;
const { history, ...rest } = renderWithProviders(
- <div>
+ <>
<Route path="/a" element={<PageA />} />
<Route path="/b" element={<PageB />} />
- </div>,
+ </>,
{ withRouter: true, initialRoute: "/a" },
);
const guardedHistory = checkNotNull(history);
diff --git a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx
index e3ddeb9688a..4e549678648 100644
--- a/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/permissions/test/DatabasesPermissionsPage/DatabasesPermissionsPage.unit.spec.tsx
@@ -53,12 +53,25 @@ const setup = async () => {
path="/admin/permissions/data"
element={<RoutedDataPermissionsPage />}
>
- <Route
- path="database(/:databaseId)(/schema/:schemaName)(/table/:tableId)"
- element={<RoutedDatabasesPermissionsPage />}
- >
- {PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES}
- </Route>
+ {/*
+ * v7 cannot parse v3 optional groups, so the app spells each depth out as
+ * its own route (see DATABASES_PERMISSIONS_PATHS in permissions/routes.tsx).
+ * Mirror that here.
+ */}
+ {[
+ "database",
+ "database/:databaseId",
+ "database/:databaseId/schema/:schemaName",
+ "database/:databaseId/schema/:schemaName/table/:tableId",
+ ].map((path) => (
+ <Route
+ key={path}
+ path={path}
+ element={<RoutedDatabasesPermissionsPage />}
+ >
+ {PLUGIN_ADMIN_PERMISSIONS_TABLE_GROUP_ROUTES}
+ </Route>
+ ))}
</Route>,
{
withRouter: true,
diff --git a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx
index 0b7399489f3..fafa4fcedd0 100644
--- a/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/permissions/test/GroupsPermissionsPage/GroupsPermissionsPage.unit.spec.tsx
@@ -56,12 +56,21 @@ const setup = async ({
path="/admin/permissions/data"
element={<RoutedDataPermissionsPage />}
>
- <Route
- path="group(/:groupId)(/database/:databaseId)(/schema/:schemaName)"
- element={<RoutedGroupsPermissionsPage />}
- >
- {PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES}
- </Route>
+ {/*
+ * v7 cannot parse v3 optional groups, so the app spells each depth out as
+ * its own route (see GROUPS_PERMISSIONS_PATHS in permissions/routes.tsx).
+ * Mirror that here.
+ */}
+ {[
+ "group",
+ "group/:groupId",
+ "group/:groupId/database/:databaseId",
+ "group/:groupId/database/:databaseId/schema/:schemaName",
+ ].map((path) => (
+ <Route key={path} path={path} element={<RoutedGroupsPermissionsPage />}>
+ {PLUGIN_ADMIN_PERMISSIONS_TABLE_ROUTES}
+ </Route>
+ ))}
</Route>,
{
withRouter: true,
diff --git a/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx b/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx
index 5698b3a8d53..6bc5df5b232 100644
--- a/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/ModalRoute.unit.spec.tsx
@@ -81,14 +81,13 @@ describe("modalRoute", () => {
expect(pathname()).toBe("/account/notifications");
});
- // The admin permissions pages hang modal routes off a parent whose path uses
- // v3 optional groups, so the parent matches a variable number of segments.
- it("closes to the right parent under a route with optional groups", async () => {
+ // The admin permissions pages hang modal routes off a parent that matches a
+ // variable number of segments. v3 spelled that with optional groups
+ // (`database(/:databaseId)`); v7 cannot parse those, so the app expands each
+ // depth into its own route. Closing has to land on the depth that matched.
+ it("closes to the right parent under a variable-depth parent route", async () => {
const { pathname } = setup(
- <Route
- path="database(/:databaseId)(/schema/:schemaName)(/table/:tableId)"
- element={<CollectionPage />}
- >
+ <Route path="database/:databaseId" element={<CollectionPage />}>
{modalRoute("impersonated/group/:groupId", TestModal, { modalProps })}
</Route>,
"/database/1/impersonated/group/2",
diff --git a/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx
index 239947c715b..de5efa4c0ba 100644
--- a/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardTabs/DashboardTabs.unit.spec.tsx
@@ -102,7 +102,7 @@ function setup({
const { store } = renderWithProviders(
<>
- <Route path="dashboard/:slug(/:tabSlug)" element={<DashboardRoute />} />
+ <Route path="dashboard/:slug" element={<DashboardRoute />} />
<Route path="someotherpath" element={<OtherComponent />} />
</>,
{
diff --git a/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.unit.spec.tsx
index d2f65b2bf1d..c99a3caf799 100644
--- a/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.unit.spec.tsx
@@ -17,11 +17,12 @@ const setup = ({
slug?: string;
onClose?: () => void;
} = {}) => {
+ const modal = <ArchiveDashboardModalConnectedInner onClose={onClose} />;
renderWithProviders(
- <Route
- path="/dashboard(/:slug)"
- element={<ArchiveDashboardModalConnectedInner onClose={onClose} />}
- />,
+ <>
+ <Route path="/dashboard" element={modal} />
+ <Route path="/dashboard/:slug" element={modal} />
+ </>,
{
withRouter: true,
initialRoute: slug ? `/dashboard/${slug}` : "/dashboard",
diff --git a/frontend/src/metabase/data-studio/segments/pages/NewSegmentPage/NewSegmentPage.unit.spec.tsx b/frontend/src/metabase/data-studio/segments/pages/NewSegmentPage/NewSegmentPage.unit.spec.tsx
index 0517a901f90..737c04c88e1 100644
--- a/frontend/src/metabase/data-studio/segments/pages/NewSegmentPage/NewSegmentPage.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/segments/pages/NewSegmentPage/NewSegmentPage.unit.spec.tsx
@@ -61,8 +61,10 @@ function setup({ table = TEST_TABLE }: SetupOpts = {}) {
`${successUrl}/${segment.id}`;
const { history } = renderWithProviders(
+ // Catch-all so the page stays mounted after a successful save navigates to
+ // the deep success URL; the test asserts the form survived the save.
<Route
- path="/"
+ path="*"
element={
<NewSegmentPage
// Unjustified type cast. FIXME
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx
index cdcf43af480..d35131ade8e 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx
@@ -179,10 +179,16 @@ const setup = ({
);
return renderWithProviders(
- <Route
- path="/admin/tools/notifications(/:notificationId)"
- element={<RoutedNotificationsAdminPage />}
- />,
+ <>
+ <Route
+ path="/admin/tools/notifications"
+ element={<RoutedNotificationsAdminPage />}
+ />
+ <Route
+ path="/admin/tools/notifications/:notificationId"
+ element={<RoutedNotificationsAdminPage />}
+ />
+ </>,
{ withRouter: true, initialRoute },
);
};
diff --git a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.unit.spec.tsx b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.unit.spec.tsx
index 5e6ebfb64c7..40730017f6c 100644
--- a/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.unit.spec.tsx
+++ b/frontend/src/metabase/nav/components/search/SearchBar/SearchBar.unit.spec.tsx
@@ -92,7 +92,7 @@ describe("SearchBar", () => {
await userEvent.type(getSearchBar(), "BC{enter}");
const location = history.getCurrentLocation();
- expect(location.pathname).toEqual("search");
+ expect(location.pathname).toEqual("/search");
expect(location.search).toEqual("?q=BC");
});
@@ -190,7 +190,7 @@ describe("SearchBar", () => {
const location = history.getCurrentLocation();
- expect(location.pathname).toEqual("search");
+ expect(location.pathname).toEqual("/search");
expect(location.search).toEqual("?q=bar&type=card");
});
@@ -204,7 +204,7 @@ describe("SearchBar", () => {
const location = history.getCurrentLocation();
- expect(location.pathname).toEqual("search");
+ expect(location.pathname).toEqual("/search");
expect(location.search).toEqual("?q=bar");
});
});
diff --git a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
index d9094aff254..5f6adc08292 100644
--- a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
@@ -105,7 +105,7 @@ describe("Mouse/keyboard interactions", () => {
describe("The 'View and filter all N results' command palette item", () => {
const searchLocation = {
- pathname: "search",
+ pathname: "/search",
query: {
q: "hedgehogs",
},
diff --git a/frontend/src/metabase/public/containers/PublicApp/PublicApp.unit.spec.tsx b/frontend/src/metabase/public/containers/PublicApp/PublicApp.unit.spec.tsx
index defe63d0056..1d20f6a292d 100644
--- a/frontend/src/metabase/public/containers/PublicApp/PublicApp.unit.spec.tsx
+++ b/frontend/src/metabase/public/containers/PublicApp/PublicApp.unit.spec.tsx
@@ -2,10 +2,10 @@ import userEvent from "@testing-library/user-event";
import type { JSX } from "react";
import { mockSettings } from "__support__/settings";
-import { getIcon, renderWithProviders, screen } from "__support__/ui";
+import { act, getIcon, renderWithProviders, screen } from "__support__/ui";
import { SyncedEmbedFrame } from "metabase/public/components/EmbedFrame";
+import { setErrorPage } from "metabase/redux/app";
import type { AppErrorDescriptor } from "metabase/redux/store";
-import { createMockAppState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import PublicApp from "./PublicApp";
@@ -25,10 +25,9 @@ function setup({
hash = "",
...embedFrameProps
}: SetupOpts = {}) {
- const app = createMockAppState({ errorPage: error });
const settings = mockSettings({ "hide-embed-branding?": !hasEmbedBranding });
- renderWithProviders(
+ const { store } = renderWithProviders(
<Route path="/public/dashboard/:id" element={<PublicApp />}>
<Route
index
@@ -42,10 +41,19 @@ function setup({
{
mode: "public",
initialRoute: `/public/dashboard/UUID${hash}`,
- storeInitialState: { app, settings },
+ storeInitialState: { settings },
withRouter: true,
},
);
+
+ // `errorPage` is set at runtime by a failed request, after the mount
+ // `LOCATION_CHANGE` that resets it. Seeding it in the initial store would be
+ // cleared by that mount dispatch, so set it the way the app does: afterwards.
+ if (error) {
+ act(() => {
+ store.dispatch(setErrorPage(error));
+ });
+ }
}
describe("PublicApp", () => {
diff --git a/frontend/src/metabase/query_builder/containers/test-utils.tsx b/frontend/src/metabase/query_builder/containers/test-utils.tsx
index 2f2e8a61817..6b81ce8e978 100644
--- a/frontend/src/metabase/query_builder/containers/test-utils.tsx
+++ b/frontend/src/metabase/query_builder/containers/test-utils.tsx
@@ -287,7 +287,7 @@ export const setup = async ({
const mockEventListener = jest.spyOn(window, "addEventListener");
const { container, history, store } = renderWithProviders(
- <div>
+ <>
<Route>
<Route path="/" element={<TestHome />} />
<Route path="/model">
@@ -309,7 +309,7 @@ export const setup = async ({
</Route>
<Route path="/redirect" element={<TestRedirect />} />
</Route>
- </div>,
+ </>,
{
withRouter: true,
initialRoute,
diff --git a/frontend/src/metabase/router/conformance/test-utils.tsx b/frontend/src/metabase/router/conformance/test-utils.tsx
index 608d3319fdb..a527d08f90e 100644
--- a/frontend/src/metabase/router/conformance/test-utils.tsx
+++ b/frontend/src/metabase/router/conformance/test-utils.tsx
@@ -132,7 +132,14 @@ function renderFacade(
<Route path={facadePath} component={Mounted} />
);
- renderWithProviders(tree, { withRouter: true, initialRoute });
+ // 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(
@@ -265,7 +272,8 @@ function renderDynamicFacade(
);
renderWithProviders(
<Route component={Passthrough}>{dynamicSiblings(leaf, scenario)}</Route>,
- { withRouter: true, initialRoute },
+ // Raw v3 route config, same as `renderFacade`: pin the engine.
+ { withRouter: true, initialRoute, routerEngine: "v3" },
);
}
diff --git a/frontend/src/metabase/router/redirect.unit.spec.tsx b/frontend/src/metabase/router/redirect.unit.spec.tsx
index ca65f3eeb20..8ea025224f8 100644
--- a/frontend/src/metabase/router/redirect.unit.spec.tsx
+++ b/frontend/src/metabase/router/redirect.unit.spec.tsx
@@ -78,14 +78,14 @@ describe("router/redirect", () => {
it("interpolates params into a relative target", async () => {
const history = mountRoutes(
<Route path="browse" element={<Parent />}>
- <Route path=":dbId-:slug" element={redirect("databases/:dbId-:slug")} />
+ <Route path=":dbId/:slug" element={redirect("databases/:dbId/:slug")} />
</Route>,
- "/browse/5-orders",
+ "/browse/5/orders",
);
await waitFor(() =>
expect(history?.getCurrentLocation().pathname).toBe(
- "/browse/databases/5-orders",
+ "/browse/databases/5/orders",
),
);
});
diff --git a/frontend/src/metabase/router/use-params.unit.spec.tsx b/frontend/src/metabase/router/use-params.unit.spec.tsx
index 4d3a70a4e1e..7d9f9506e01 100644
--- a/frontend/src/metabase/router/use-params.unit.spec.tsx
+++ b/frontend/src/metabase/router/use-params.unit.spec.tsx
@@ -41,7 +41,7 @@ describe("router/useParams", () => {
});
it("exposes the splat under v7's `*` key, not v3's `splat`", () => {
- renderWithProviders(<Route path="files/**" element={<SplatProbe />} />, {
+ renderWithProviders(<Route path="files/*" element={<SplatProbe />} />, {
withRouter: true,
initialRoute: "/files/a/b",
});
diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsx
index fd37f8a3f0f..1afcf38cd21 100644
--- a/frontend/src/metabase/router/v7/RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx
@@ -76,11 +76,19 @@ export function RouterBridge({
const routes = useMemo<RouteStub[]>(
() =>
matches.map((match) => {
- // `handle` is typed `unknown`; we only ever put `{ v3Path }` on it.
- const handle = match.route.handle as { v3Path?: string } | undefined;
+ // `handle` is typed `unknown`; we only ever put `{ v3Path, props }` on it.
+ const handle = match.route.handle as
+ | { v3Path?: 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.
- return { path: handle?.v3Path, pathnameBase: match.pathname };
+ // `props` carries the arbitrary route props v3 exposed (the command palette
+ // reads `route.props.disableCommandPalette`).
+ return {
+ path: handle?.v3Path,
+ props: handle?.props,
+ pathnameBase: match.pathname,
+ };
}),
// Keyed on the matched branch, not the array identity, which changes each render.
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/frontend/src/metabase/router/v7/RouterProviderV7.tsx b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
index becb2015c2d..829c1aa7d07 100644
--- a/frontend/src/metabase/router/v7/RouterProviderV7.tsx
+++ b/frontend/src/metabase/router/v7/RouterProviderV7.tsx
@@ -83,19 +83,40 @@ export function RouterProviderV7({ children }: PropsWithChildren): JSX.Element {
);
}
+/**
+ * The in-memory blocking history the test engine runs on. Exposed so the test
+ * harness can own the instance and hand tests a handle on it, rather than it
+ * being created (and trapped) inside the provider.
+ */
+export function createMemoryTestHistory(initialRoute: string) {
+ // history@3 resolved a relative initial entry against the root; v7 keeps it
+ // relative, and a location without a leading slash then matches no route. Specs
+ // written against v3 pass both forms, so normalize.
+ const entry = initialRoute.startsWith("/")
+ ? initialRoute
+ : `/${initialRoute}`;
+ return withBlocking(
+ createMemoryHistory({ initialEntries: [entry], v5Compat: true }),
+ );
+}
+
+export type MemoryTestHistory = ReturnType<typeof createMemoryTestHistory>;
+
/**
* The v7 engine hosted on an in-memory history, for tests. Mirrors what
* `renderWithProviders({ routerEngine: "v7" })` mounts, including navigation
- * blocking.
+ * blocking. Pass `history` to drive and inspect it from outside the tree.
*/
export function RouterProviderV7Memory({
children,
initialRoute,
-}: PropsWithChildren<{ initialRoute: string }>): JSX.Element {
- const [history] = useState(() =>
- withBlocking(
- createMemoryHistory({ initialEntries: [initialRoute], v5Compat: true }),
- ),
+ history: providedHistory,
+}: PropsWithChildren<{
+ initialRoute: string;
+ history?: MemoryTestHistory;
+}>): JSX.Element {
+ const [history] = useState(
+ () => providedHistory ?? createMemoryTestHistory(initialRoute),
);
const onLocationChange = useLocationMirror();
return (
diff --git a/frontend/src/metabase/router/v7/map-to-v7.tsx b/frontend/src/metabase/router/v7/map-to-v7.tsx
index 51d1121c04f..618592f71b1 100644
--- a/frontend/src/metabase/router/v7/map-to-v7.tsx
+++ b/frontend/src/metabase/router/v7/map-to-v7.tsx
@@ -45,7 +45,7 @@ export function mapToV7(node: ReactNode): ReactNode {
}
function toV7Route(element: ReactElement<RouteElementProps>): ReactElement {
- const { path, index, element: routeElement, children } = element.props;
+ const { path, index, element: routeElement, children, props } = element.props;
// v7 defaults a route with no `element` to `<Outlet/>`; only wrap (and publish
// context) when the facade route actually renders something.
@@ -54,8 +54,12 @@ 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 =
- path != null ? { v3Path: translatePatternToV3(path) } : undefined;
+ v3Path != null || props != null ? { v3Path, 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.ts
index c3dbbf1e956..a869d651690 100644
--- a/frontend/src/metabase/router/v7/navigator.ts
+++ b/frontend/src/metabase/router/v7/navigator.ts
@@ -12,8 +12,30 @@ import { queryToSearch } from "./location";
*/
let currentNavigate: NavigateFunction | null = null;
+/**
+ * Navigations requested before the router registered its `navigate`. On v3 the
+ * history existed at store creation, so a `dispatch(replace(...))` from a mount
+ * `useLayoutEffect` (e.g. a guard redirect) took effect immediately. v7's
+ * `navigate` only registers in an effect, which runs after descendant layout
+ * effects, so buffer these and flush them once it does rather than dropping them.
+ */
+let pendingNavigations: Array<(navigate: NavigateFunction) => void> = [];
+
export function setV7Navigate(navigate: NavigateFunction | null): void {
currentNavigate = navigate;
+ if (!navigate) {
+ // The router unmounted. Anything still buffered was meant for it, not for
+ // whatever router mounts next, so drop it rather than replay it later.
+ pendingNavigations = [];
+ return;
+ }
+ if (pendingNavigations.length > 0) {
+ const flushing = pendingNavigations;
+ pendingNavigations = [];
+ for (const run of flushing) {
+ run(navigate);
+ }
+ }
}
/**
@@ -71,15 +93,17 @@ export function toNavigateArgs(
/**
* A `RouterNavigator` (the subset of `history` that `routerMiddleware` drives)
* backed by the live v7 `navigate`. Passed to the store on v7 so
- * `dispatch(push(...))` navigates the v7 router. Calls before the router mounts
- * are dropped, matching the pre-mount no-op window on v3.
+ * `dispatch(push(...))` navigates the v7 router. A call before the router mounts
+ * is buffered and flushed on registration, so a mount-time redirect is not lost.
*/
export function createV7Navigator(): RouterNavigator {
const navigate = (to: To | number, options?: NavigateOptions) => {
- if (typeof to === "number") {
- currentNavigate?.(to);
+ const run = (fn: NavigateFunction) =>
+ typeof to === "number" ? fn(to) : fn(to, options);
+ if (currentNavigate) {
+ run(currentNavigate);
} else {
- currentNavigate?.(to, options);
+ pendingNavigations.push(run);
}
};
diff --git a/frontend/src/metabase/router/v7/navigator.unit.spec.ts b/frontend/src/metabase/router/v7/navigator.unit.spec.ts
index da345cfff8c..68908380641 100644
--- a/frontend/src/metabase/router/v7/navigator.unit.spec.ts
+++ b/frontend/src/metabase/router/v7/navigator.unit.spec.ts
@@ -1,5 +1,5 @@
import { queryToSearch } from "./location";
-import { toNavigateArgs } from "./navigator";
+import { createV7Navigator, setV7Navigate, toNavigateArgs } from "./navigator";
// v3 location descriptors carry the query as an object. v7 only reads `search`,
// so the navigator has to serialize it; dropping it silently loses params (the
@@ -54,6 +54,48 @@ describe("toNavigateArgs", () => {
});
});
+// The redux navigator is built at store creation, before the router mounts and
+// registers its `navigate`. A navigation dispatched in that window (a guard
+// redirecting from a mount layout effect) must not be lost, but it also must not
+// leak into a later router once this one is gone.
+describe("createV7Navigator pre-mount buffering", () => {
+ afterEach(() => {
+ setV7Navigate(null);
+ });
+
+ it("buffers a navigation made before the router mounts and flushes it on register", () => {
+ const navigator = createV7Navigator();
+ navigator.replace("/target");
+
+ const navigate = jest.fn();
+ setV7Navigate(navigate);
+
+ expect(navigate).toHaveBeenCalledWith("/target", { replace: true });
+ });
+
+ it("navigates immediately once the router is registered", () => {
+ const navigate = jest.fn();
+ setV7Navigate(navigate);
+
+ createV7Navigator().push("/now");
+
+ expect(navigate).toHaveBeenCalledTimes(1);
+ });
+
+ it("drops a buffered navigation when the router unmounts before it flushes", () => {
+ const navigator = createV7Navigator();
+ navigator.replace("/stale");
+
+ // Router unmounts without ever registering; the next one must not inherit it.
+ setV7Navigate(null);
+
+ const navigate = jest.fn();
+ setV7Navigate(navigate);
+
+ expect(navigate).not.toHaveBeenCalled();
+ });
+});
+
describe("queryToSearch", () => {
it("repeats a key for array values", () => {
expect(queryToSearch({ id: ["1", "2"] })).toBe("?id=1&id=2");
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 9e1d0f55aa2..c2140e45f7d 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -67,7 +67,13 @@ import SegmentFieldListContainer from "metabase/reference/segments/SegmentFieldL
import SegmentListContainer from "metabase/reference/segments/SegmentListContainer";
import SegmentQuestionsContainer from "metabase/reference/segments/SegmentQuestionsContainer";
import SegmentRevisionsContainer from "metabase/reference/segments/SegmentRevisionsContainer";
-import { Route, redirect, withRouteProps } from "metabase/router";
+import {
+ Navigate,
+ Route,
+ redirect,
+ useParams,
+ withRouteProps,
+} from "metabase/router";
import {
CanAccessDataModel,
CanAccessDataStudio,
@@ -107,6 +113,24 @@ const RoutedMetricsViewerPage = withRouteProps(MetricsViewerPage);
const RoutedTableDetailPage = withRouteProps(TableDetailPage);
const RoutedUnsubscribePage = withRouteProps(UnsubscribePage);
+/**
+ * v48 and earlier linked databases as `/browse/<dbId>-<slug>`. That was a
+ * `:dbId-:slug` route, which react-router v7 cannot express: a dynamic segment
+ * has to span the whole path segment. Match the segment as a whole instead, and
+ * only redirect when it has the legacy hyphenated shape, so anything else still
+ * falls through to the not-found page rather than being sent to a database that
+ * cannot exist.
+ */
+export function LegacyBrowseRedirect() {
+ const { dbIdAndSlug } = useParams();
+
+ if (!dbIdAndSlug?.includes("-")) {
+ return <NotFoundFallbackPage />;
+ }
+
+ return <Navigate to={`/browse/databases/${dbIdAndSlug}`} replace />;
+}
+
export const getRoutes = (store: AppStore) => {
return (
<Route element={<RoutedApp />}>
@@ -300,10 +324,7 @@ export const getRoutes = (store: AppStore) => {
{PLUGIN_TABLE_EDITING.getRoutes()}
{/* These two Redirects support legacy paths in v48 and earlier */}
- <Route
- path=":dbId-:slug"
- element={redirect("databases/:dbId-:slug")}
- />
+ <Route path=":dbIdAndSlug" element={<LegacyBrowseRedirect />} />
<Route
path=":dbId/schema/:schemaName"
element={redirect("databases/:dbId/schema/:schemaName")}
diff --git a/frontend/src/metabase/routes.unit.spec.tsx b/frontend/src/metabase/routes.unit.spec.tsx
new file mode 100644
index 00000000000..a5490a0f270
--- /dev/null
+++ b/frontend/src/metabase/routes.unit.spec.tsx
@@ -0,0 +1,39 @@
+import { setupCurrentUserEndpoint } from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { Route } from "metabase/router";
+import { createMockUser } from "metabase-types/api/mocks";
+
+import { LegacyBrowseRedirect } from "./routes";
+
+function setup(initialRoute: string) {
+ setupCurrentUserEndpoint(createMockUser());
+
+ const { history } = renderWithProviders(
+ <Route path="browse">
+ <Route path="databases/:slug" element={<div>browse databases</div>} />
+ <Route path=":dbIdAndSlug" element={<LegacyBrowseRedirect />} />
+ </Route>,
+ { withRouter: true, initialRoute },
+ );
+
+ return history;
+}
+
+describe("LegacyBrowseRedirect", () => {
+ it("redirects a v48-era /browse/<dbId>-<slug> url onto /browse/databases", async () => {
+ const history = setup("/browse/5-orders");
+
+ await waitFor(() =>
+ expect(history?.getCurrentLocation().pathname).toBe(
+ "/browse/databases/5-orders",
+ ),
+ );
+ expect(screen.getByText("browse databases")).toBeInTheDocument();
+ });
+
+ it("does not redirect a segment without the legacy hyphenated shape", async () => {
+ const history = setup("/browse/orders");
+
+ expect(history?.getCurrentLocation().pathname).toBe("/browse/orders");
+ });
+});
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index df1af3cb4fd..0b3f5c41d05 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -10,7 +10,14 @@ import {
} from "@testing-library/react";
import type { History } from "history";
import { createMemoryHistory } from "history";
-import { useCallback, useMemo, useState } from "react";
+import {
+ Children,
+ Fragment,
+ isValidElement,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
import { DragDropContextProvider } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";
import { createPortal } from "react-dom";
@@ -29,15 +36,25 @@ import { MetabaseReduxProvider } from "metabase/redux";
import type { State } from "metabase/redux/store";
import { createMockState } from "metabase/redux/store/mocks";
import {
- ReactRouterRoute,
+ type Action,
+ type LocationDescriptor,
+ Route,
type RouterEngine,
RouterProvider,
routerMiddleware,
routing as routingReducer,
useRouterHistory,
} from "metabase/router";
-import { RouterProviderV7Memory } from "metabase/router/v7/RouterProviderV7";
-import { createV7Navigator } from "metabase/router/v7/navigator";
+import {
+ type MemoryTestHistory,
+ RouterProviderV7Memory,
+ createMemoryTestHistory,
+} from "metabase/router/v7/RouterProviderV7";
+import { toV3Location } from "metabase/router/v7/location";
+import {
+ createV7Navigator,
+ toNavigateArgs,
+} from "metabase/router/v7/navigator";
import { getMetabaseCssVariables } from "metabase/styled-components/theme/css-variables";
import type { MantineThemeOverride } from "metabase/ui";
import { PortalContainer, ThemeProvider, useMantineTheme } from "metabase/ui";
@@ -61,7 +78,7 @@ export interface RenderWithProvidersOptions {
initialRoute?: string;
storeInitialState?: Partial<State>;
withRouter?: boolean;
- /** Which router engine hosts the tree when `withRouter` is set. Defaults to v3. */
+ /** Which router engine hosts the tree when `withRouter` is set. Defaults to v7. */
routerEngine?: RouterEngine;
/** Renders children wrapped with kbar provider */
withKBar?: boolean;
@@ -83,7 +100,7 @@ export function renderWithProviders(
initialRoute = "/",
storeInitialState = {},
withRouter = false,
- routerEngine = "v3",
+ routerEngine = "v7",
withKBar = false,
withDND = false,
withUndos = false,
@@ -124,7 +141,7 @@ export function renderHookWithProviders<TProps, TResult>(
initialRoute = "/",
storeInitialState = {},
withRouter = false,
- routerEngine = "v3",
+ routerEngine = "v7",
withKBar = false,
withDND = false,
withUndos = false,
@@ -153,7 +170,7 @@ export function renderHookWithProviders<TProps, TResult>(
const WrapperWithRoute = ({ children, ...props }: any) => {
return (
<Wrapper {...props}>
- <ReactRouterRoute path="/" component={() => <>{children}</>} />
+ <Route path="*" element={<>{children}</>} />
</Wrapper>
);
};
@@ -173,7 +190,7 @@ export function getTestStoreAndWrapper({
initialRoute,
storeInitialState,
withRouter,
- routerEngine = "v3",
+ routerEngine = "v7",
withKBar,
withDND,
withUndos,
@@ -195,8 +212,16 @@ export function getTestStoreAndWrapper({
const browserHistory = useRouterHistory(createMemoryHistory)({
entries: [initialRoute],
});
- // v7 owns its own in-memory history; only the v3 engine uses this one.
- const history = withRouter && !isV7Router ? browserHistory : undefined;
+ // 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
+ ? createMemoryTestHistory(initialRoute)
+ : undefined;
+ const history = !withRouter
+ ? undefined
+ : v7History
+ ? createV3HistoryAdapter(v7History)
+ : browserHistory;
let reducers;
@@ -239,6 +264,7 @@ export function getTestStoreAndWrapper({
{...props}
store={store}
history={history}
+ v7History={v7History}
withRouter={withRouter}
routerEngine={routerEngine}
initialRoute={initialRoute}
@@ -292,8 +318,9 @@ export function TestWrapper({
children,
store,
history,
+ v7History,
withRouter,
- routerEngine = "v3",
+ routerEngine = "v7",
initialRoute = "/",
withKBar,
withDND,
@@ -305,6 +332,7 @@ export function TestWrapper({
children: React.ReactElement;
store: any;
history?: History;
+ v7History?: MemoryTestHistory;
withRouter: boolean;
routerEngine?: RouterEngine;
initialRoute?: string;
@@ -344,6 +372,7 @@ export function TestWrapper({
hasRouter={withRouter}
routerEngine={routerEngine}
history={history}
+ v7History={v7History}
initialRoute={initialRoute}
>
{children}
@@ -359,26 +388,97 @@ export function TestWrapper({
);
}
+/**
+ * The v3 `history` surface the specs drive and assert against
+ * (`getCurrentLocation()`, `push`, `goBack`, `listen`, ...), backed by the v7
+ * memory history. Lets specs written against the v3 engine keep working
+ * unchanged on v7. Cast to `History` so the handle specs already destructure
+ * keeps its type; it implements the subset they use.
+ */
+function createV3HistoryAdapter(history: MemoryTestHistory): History {
+ const getCurrentLocation = () =>
+ // v7 types `action` as its own `Action` enum; the values are the same
+ // "POP"/"PUSH"/"REPLACE" strings the facade's `Action` union uses.
+ toV3Location(history.location, history.action as Action);
+
+ const adapter = {
+ getCurrentLocation,
+ get location() {
+ return getCurrentLocation();
+ },
+ push: (location: LocationDescriptor) => {
+ const [to, options] = toNavigateArgs(location);
+ history.push(to, options.state);
+ },
+ replace: (location: LocationDescriptor) => {
+ const [to, options] = toNavigateArgs(location);
+ history.replace(to, options.state);
+ },
+ go: (n: number) => history.go(n),
+ goBack: () => history.go(-1),
+ goForward: () => history.go(1),
+ listen: (
+ listener: (location: ReturnType<typeof getCurrentLocation>) => void,
+ ) =>
+ history.listen(({ location, action }) =>
+ // Same enum-vs-union mismatch as in `getCurrentLocation` above.
+ listener(toV3Location(location, action as Action)),
+ ),
+ };
+
+ // The adapter implements the subset of v3's `History` the specs actually call,
+ // not the full interface, so widen through `unknown` to keep the `history`
+ // handle they destructure typed as before.
+ return adapter as unknown as History;
+}
+
+function childrenAreRouteTree(children: React.ReactNode): boolean {
+ return Children.toArray(children).some((child) => {
+ if (!isValidElement(child)) {
+ return false;
+ }
+ if (child.type === Route) {
+ return true;
+ }
+ // Routes are often grouped in a fragment (`<><Route/><Route/></>`); descend
+ // so the tree is still recognized, matching how `mapToV7` unwraps fragments.
+ if (child.type === Fragment) {
+ return childrenAreRouteTree(child.props.children);
+ }
+ return false;
+ });
+}
+
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}>
- {children}
+ <RouterProviderV7Memory initialRoute={initialRoute} history={v7History}>
+ {content}
</RouterProviderV7Memory>
);
}
diff --git a/src/metabase/appearance/settings.clj b/src/metabase/appearance/settings.clj
index 695e36918a8..9ee2238aeda 100644
--- a/src/metabase/appearance/settings.clj
+++ b/src/metabase/appearance/settings.clj
@@ -49,7 +49,7 @@
(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 false
+ :default true
:visibility :public
:export? false
:doc false)