Skip to content

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

Author the app's routes as data routes (#79268)

Romeo Van Snick452f68975080
diff --git a/frontend/src/metabase/app.js b/frontend/src/metabase/app.js
index a470452eae6..304ea565bf7 100644
--- a/frontend/src/metabase/app.js
+++ b/frontend/src/metabase/app.js
@@ -105,9 +105,10 @@ function _init(reducers, getRoutes, callback) {
<GlobalStyles />
{createPortal(<PortalContainer />, document.body)}
<MetabotProvider>
- <RouterProvider onLocationChange={mirrorLocation}>
- {routes}
- </RouterProvider>
+ <RouterProvider
+ routes={routes}
+ onLocationChange={mirrorLocation}
+ />
</MetabotProvider>
</AppThemeProvider>
</OverlayStackProvider>
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.tsx
index 84317fdb2ec..de6e5a4e879 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
@@ -9,7 +9,7 @@ import {
setupTableEndpoints,
} from "__support__/server-mocks";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
-import { Route, RouterProviderMemory } from "metabase/router";
+import { RouterProviderMemory } from "metabase/router";
import {
createMockCard,
createMockCollection,
@@ -205,9 +205,11 @@ describe("SmartLink", () => {
const props = createProps("dashboard", dashboard);
renderWithProviders(
- <RouterProviderMemory initialRoute="/subpath" basename="/subpath">
- <Route path="*" element={<SmartLinkComponent {...props} />} />
- </RouterProviderMemory>,
+ <RouterProviderMemory
+ initialRoute="/subpath"
+ basename="/subpath"
+ routes={[{ path: "*", element: <SmartLinkComponent {...props} /> }]}
+ />,
);
await waitFor(() => {
@@ -231,9 +233,10 @@ describe("SmartLink", () => {
const props = createProps("dashboard", dashboard);
renderWithProviders(
- <RouterProviderMemory initialRoute="/">
- <Route path="*" element={<SmartLinkComponent {...props} />} />
- </RouterProviderMemory>,
+ <RouterProviderMemory
+ initialRoute="/"
+ routes={[{ path: "*", element: <SmartLinkComponent {...props} /> }]}
+ />,
);
await waitFor(() => {
diff --git a/frontend/src/metabase/router/RouterProvider.tsx b/frontend/src/metabase/router/RouterProvider.tsx
index 0d1d0e94f57..6b06c8c206f 100644
--- a/frontend/src/metabase/router/RouterProvider.tsx
+++ b/frontend/src/metabase/router/RouterProvider.tsx
@@ -1,8 +1,8 @@
-import type { PropsWithChildren } from "react";
import { useLayoutEffect, useState } from "react";
import {
type DataRouter,
RouterProvider as ReactRouterProvider,
+ type RouteObject,
} from "react-router";
import { getBasename } from "metabase/utils/basename";
@@ -71,11 +71,14 @@ function useLocationMirror(
* all react to the LOCATION_CHANGE it emits.
*/
export function RouterProvider({
- children,
+ routes,
onLocationChange,
-}: PropsWithChildren<{ onLocationChange?: LocationMirror }>): JSX.Element {
+}: {
+ routes: RouteObject[];
+ onLocationChange?: LocationMirror;
+}): JSX.Element {
const [router] = useState(() =>
- createAppRouter(children, getBasename() || undefined),
+ createAppRouter(routes, getBasename() || undefined),
);
useLocationMirror(router, onLocationChange);
@@ -89,19 +92,20 @@ export function RouterProvider({
* tree.
*/
export function RouterProviderMemory({
- children,
+ routes,
initialRoute,
basename,
routerHolder,
onLocationChange,
-}: PropsWithChildren<{
+}: {
+ routes: RouteObject[];
initialRoute: string;
basename?: string;
routerHolder?: MemoryTestRouterHolder;
onLocationChange?: LocationMirror;
-}>): JSX.Element {
+}): JSX.Element {
const [router] = useState(() => {
- const created = createMemoryAppRouter(children, initialRoute, basename);
+ const created = createMemoryAppRouter(routes, initialRoute, basename);
if (routerHolder) {
routerHolder.current = created;
}
diff --git a/frontend/src/metabase/router/create-router.tsx b/frontend/src/metabase/router/create-router.tsx
index 8bf08c06981..7efb17765e9 100644
--- a/frontend/src/metabase/router/create-router.tsx
+++ b/frontend/src/metabase/router/create-router.tsx
@@ -1,10 +1,8 @@
-import type { ReactNode } from "react";
import {
type DataRouter,
- Route,
+ type RouteObject,
createBrowserRouter,
createMemoryRouter,
- createRoutesFromElements,
} from "react-router";
import { AppShell } from "./AppShell";
@@ -18,32 +16,32 @@ export type MemoryTestRouter = DataRouter;
export type MemoryTestRouterHolder = { current: MemoryTestRouter | null };
/**
- * The app's route tree as data routes, under a pathless layout route.
+ * The app's routes under a pathless layout route.
*
* The layout route contributes no path, so it changes no matching. It exists so
* relative redux navigation resolves from the root (see `AppShell`) and as the
* seat for anything the app shell needs above the route tree.
*/
-function toDataRoutes(tree: ReactNode) {
- return createRoutesFromElements(<Route element={<AppShell />}>{tree}</Route>);
+function withAppShell(routes: RouteObject[]): RouteObject[] {
+ return [{ element: <AppShell />, children: routes }];
}
export function createAppRouter(
- tree: ReactNode,
+ routes: RouteObject[],
basename?: string,
): DataRouter {
- return createBrowserRouter(toDataRoutes(tree), { basename });
+ return createBrowserRouter(withAppShell(routes), { basename });
}
export function createMemoryAppRouter(
- tree: ReactNode,
+ routes: RouteObject[],
initialRoute: string,
basename?: string,
): DataRouter {
const entry = initialRoute.startsWith("/")
? initialRoute
: `/${initialRoute}`;
- return createMemoryRouter(toDataRoutes(tree), {
+ return createMemoryRouter(withAppShell(routes), {
basename,
initialEntries: [entry],
});
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 7e5634cce96..83f07d23c33 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -12,6 +12,7 @@ export * from "./navigation";
export * from "./Navigate";
export * from "./redirect";
export * from "./router-link";
+export * from "./to-route-objects";
export * from "./location-change";
export * from "./RouterProvider";
export * from "./types";
diff --git a/frontend/src/metabase/router/to-route-objects.ts b/frontend/src/metabase/router/to-route-objects.ts
new file mode 100644
index 00000000000..dd63a9c1e8c
--- /dev/null
+++ b/frontend/src/metabase/router/to-route-objects.ts
@@ -0,0 +1,33 @@
+import type { ReactNode } from "react";
+import { type RouteObject, createRoutesFromElements } from "react-router";
+
+/**
+ * A `<Route>` subtree as route objects, so it can be spread into the `children`
+ * of a route that is already authored as objects.
+ *
+ * Route trees are being converted top down, and there is no way back: a route
+ * object cannot be rendered as a `<Route>` element. So a parent that has
+ * converted uses this on every subtree that has not.
+ */
+export function toRouteObjects(tree: ReactNode): RouteObject[] {
+ return withDerivedIds(createRoutesFromElements(tree));
+}
+
+/**
+ * Drop the `id` that `createRoutesFromElements` derives from a route's position
+ * in the tree it was given. Those ids reach the router as explicit ones, and
+ * every call starts numbering at "0", so two converted subtrees under one router
+ * collide. Without them the router derives ids from the whole tree, as it does
+ * for a tree that was authored as objects throughout.
+ */
+function withDerivedIds(routes: RouteObject[]): RouteObject[] {
+ return routes.map((route) =>
+ route.index
+ ? { ...route, id: undefined }
+ : {
+ ...route,
+ id: undefined,
+ children: route.children && withDerivedIds(route.children),
+ },
+ );
+}
diff --git a/frontend/src/metabase/router/to-route-objects.unit.spec.tsx b/frontend/src/metabase/router/to-route-objects.unit.spec.tsx
new file mode 100644
index 00000000000..5d22a271165
--- /dev/null
+++ b/frontend/src/metabase/router/to-route-objects.unit.spec.tsx
@@ -0,0 +1,43 @@
+import { renderRoutes, screen } from "__support__/ui";
+import { Outlet, Route } from "metabase/router";
+
+import { toRouteObjects } from "./to-route-objects";
+
+const Parent = () => (
+ <div>
+ <span>parent chrome</span>
+ <Outlet />
+ </div>
+);
+
+describe("router/toRouteObjects", () => {
+ it("converts a `<Route>` subtree into route objects", () => {
+ expect(
+ toRouteObjects(
+ <Route path="parent" element={<Parent />}>
+ <Route path="child" element={<div />} />
+ </Route>,
+ ),
+ ).toMatchObject([{ path: "parent", children: [{ path: "child" }] }]);
+ });
+
+ it("leaves the route ids to the router, so converted subtrees can be siblings", async () => {
+ const routes = [
+ {
+ path: "/",
+ element: <Parent />,
+ children: [
+ ...toRouteObjects(<Route path="one" element={<div>page one</div>} />),
+ ...toRouteObjects(<Route path="two" element={<div>page two</div>} />),
+ ],
+ },
+ ];
+
+ // Both subtrees start numbering at "0", so keeping the ids they were given
+ // fails the router's global uniqueness check before anything renders.
+ renderRoutes(routes, { initialRoute: "/two" });
+
+ expect(await screen.findByText("page two")).toBeInTheDocument();
+ expect(screen.getByText("parent chrome")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 8fc58ab0bed..1ca58aef2a1 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -13,6 +13,7 @@ export type {
Params,
Path,
RelativeRoutingType,
+ RouteObject,
SetURLSearchParams,
To,
URLSearchParamsInit,
diff --git a/frontend/src/metabase/routes-embed.tsx b/frontend/src/metabase/routes-embed.tsx
index a2ff2429960..1b8cc38e56d 100644
--- a/frontend/src/metabase/routes-embed.tsx
+++ b/frontend/src/metabase/routes-embed.tsx
@@ -1,20 +1,26 @@
import { PublicNotFound } from "metabase/public/components/PublicNotFound";
import PublicApp from "metabase/public/containers/PublicApp";
import { PublicOrEmbeddedQuestion } from "metabase/public/containers/PublicOrEmbeddedQuestion";
-import { Route } from "metabase/router";
+import type { RouteObject } from "metabase/router";
import { PublicOrEmbeddedDashboardPage } from "./public/containers/PublicOrEmbeddedDashboard";
-export const getRoutes = () => (
- <Route>
- <Route path="embed" element={<PublicApp />}>
- <Route path="question/:token" element={<PublicOrEmbeddedQuestion />} />
- <Route
- path="dashboard/:token"
- element={<PublicOrEmbeddedDashboardPage />}
- />
- <Route path="*" element={<PublicNotFound />} />
- </Route>
- <Route path="*" element={<PublicNotFound />} />
- </Route>
-);
+export const getRoutes = (): RouteObject[] => [
+ {
+ children: [
+ {
+ path: "embed",
+ element: <PublicApp />,
+ children: [
+ { path: "question/:token", element: <PublicOrEmbeddedQuestion /> },
+ {
+ path: "dashboard/:token",
+ element: <PublicOrEmbeddedDashboardPage />,
+ },
+ { path: "*", element: <PublicNotFound /> },
+ ],
+ },
+ { path: "*", element: <PublicNotFound /> },
+ ],
+ },
+];
diff --git a/frontend/src/metabase/routes-public.tsx b/frontend/src/metabase/routes-public.tsx
index e9abb769744..7d6c3cf44ef 100644
--- a/frontend/src/metabase/routes-public.tsx
+++ b/frontend/src/metabase/routes-public.tsx
@@ -4,22 +4,26 @@ import PublicApp from "metabase/public/containers/PublicApp";
import { PublicDocument } from "metabase/public/containers/PublicDocument";
import { PublicOrEmbeddedDashboardPage } from "metabase/public/containers/PublicOrEmbeddedDashboard";
import { PublicOrEmbeddedQuestion } from "metabase/public/containers/PublicOrEmbeddedQuestion";
-import { Route } from "metabase/router";
+import type { RouteObject } from "metabase/router";
-export const getRoutes = () => {
- return (
- <Route>
- <Route path="public" element={<PublicApp />}>
- <Route path="action/:uuid" element={<PublicAction />} />
- <Route path="question/:uuid" element={<PublicOrEmbeddedQuestion />} />
- <Route
- path="dashboard/:uuid/:tabSlug?"
- element={<PublicOrEmbeddedDashboardPage />}
- />
- <Route path="document/:uuid" element={<PublicDocument />} />
- <Route path="*" element={<PublicNotFound />} />
- </Route>
- <Route path="*" element={<PublicNotFound />} />
- </Route>
- );
-};
+export const getRoutes = (): RouteObject[] => [
+ {
+ children: [
+ {
+ path: "public",
+ element: <PublicApp />,
+ children: [
+ { path: "action/:uuid", element: <PublicAction /> },
+ { path: "question/:uuid", element: <PublicOrEmbeddedQuestion /> },
+ {
+ path: "dashboard/:uuid/:tabSlug?",
+ element: <PublicOrEmbeddedDashboardPage />,
+ },
+ { path: "document/:uuid", element: <PublicDocument /> },
+ { path: "*", element: <PublicNotFound /> },
+ ],
+ },
+ { path: "*", element: <PublicNotFound /> },
+ ],
+ },
+];
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 963e6953ab3..05e4a8a422d 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -75,7 +75,13 @@ import {
IsAuthenticated,
IsNotAuthenticated,
} from "metabase/route-guards";
-import { Navigate, Route, redirect, useParams } from "metabase/router";
+import {
+ Navigate,
+ type RouteObject,
+ redirect,
+ toRouteObjects,
+ useParams,
+} from "metabase/router";
import { SearchApp } from "metabase/search/containers/SearchApp";
import { RedirectIfSetup } from "metabase/setup/components/RedirectIfSetup";
import { Setup } from "metabase/setup/components/Setup";
@@ -106,309 +112,377 @@ export function LegacyBrowseRedirect() {
return <Navigate to={`/browse/databases/${dbIdAndSlug}`} replace />;
}
-export const getRoutes = (store: AppStore) => {
- return (
- <Route element={<App />}>
- {/* SETUP */}
- <Route element={<RedirectIfSetup />}>
- <Route path="/setup" element={<Setup />} />
- </Route>
-
- {/* For compatibility: use the standard setup for embedding */}
- <Route path="/setup/embedding" element={redirect("/setup")} />
-
- {/* APP */}
- <Route element={<LoadCurrentUser />}>
- {/* AUTH */}
- <Route path="/auth">
- <Route index element={redirect("/auth/login")} />
- <Route element={<IsNotAuthenticated />}>
- <Route path="login" element={<Login />} />
- <Route path="login/:provider" element={<Login />} />
- </Route>
- <Route path="logout" element={<Logout />} />
- <Route path="forgot_password" element={<ForgotPassword />} />
- <Route path="reset_password/:token" element={<ResetPassword />} />
- {/* FE routes can sometimes be prioritized over BE
- reloading will correctly pick the SSO flow back up from the BE */}
- <Route path="sso" element={<SsoReload />} />
- <Route path="sso/:provider" element={<SsoReload />} />
- </Route>
-
- {/* MAIN */}
- <Route element={<IsAuthenticated />}>
- {getMetabotRoutes()}
-
- {PLUGIN_DATA_APPS.isEnabled && PLUGIN_DATA_APPS.getRoutes()}
-
- {/* The global all hands routes, things in here are for all the folks */}
- <Route path="/" element={<LandingPageRedirect />} />
-
- <Route path="getting-started" element={<CanAccessOnboarding />}>
- <Route index element={<Onboarding />} />
- </Route>
-
- <Route path="search" element={<SearchApp />} />
- {/* Send historical /archive route to trash - can remove in v52 */}
- <Route path="archive" element={redirect("trash")} />
- <Route path="trash" element={<TrashCollectionLanding />} />
-
- <Route path="document/:entityId" element={<DocumentPageOuter />}>
- {modalRoute("comments/:childTargetId", CommentsSidesheet, {
- noWrap: true,
- })}
- </Route>
-
- <Route
- path="collection/entity/:entity_id/*"
- element={createEntityIdRedirect({
- parametersToTranslate: [
- {
- name: "entity_id",
- resourceType: "collection",
- type: "param",
- },
- ],
- })}
- />
-
- <Route path="collection/users" element={<IsAdmin />}>
- <Route index element={<UserCollectionList />} />
- </Route>
-
- <Route
- path="collection/tenant-specific"
- element={<PLUGIN_TENANTS.CanAccessTenantSpecificRoute />}
- >
- <Route index element={<PLUGIN_TENANTS.TenantCollectionList />} />
- </Route>
-
- <Route path="collection/tenant-users" element={<IsAdmin />}>
- <Route index element={<PLUGIN_TENANTS.TenantUsersList />} />
- <Route
- path=":tenantId"
- element={<PLUGIN_TENANTS.TenantUsersPersonalCollectionList />}
- />
- </Route>
-
- <Route path="collection/:slug" element={<CollectionLanding />}>
- {modalRoute("move", MoveCollectionModal, { noWrap: true })}
- {modalRoute("archive", ArchiveCollectionModal, { noWrap: true })}
- {modalRoute("permissions", CollectionPermissionsModal)}
- {modalRoute(
- "move-questions-dashboard",
- MoveQuestionsIntoDashboardsModal,
- )}
- {PLUGIN_COLLECTIONS.cleanUpRoute}
- {getCollectionTimelineRoutes()}
- </Route>
-
- <Route
- path="dashboard/entity/:entity_id/*"
- element={createEntityIdRedirect({
- parametersToTranslate: [
- {
- name: "entity_id",
- resourceType: "dashboard",
- type: "param",
- },
- {
- name: "tab",
- resourceType: "dashboard-tab",
- type: "search",
- },
- ],
- })}
- />
-
- <Route path="dashboard/:slug" element={<DashboardApp />}>
- {modalRoute("move", DashboardMoveModalConnected, { noWrap: true })}
- {modalRoute("copy", DashboardCopyModalConnected, { noWrap: true })}
- {modalRoute("archive", ArchiveDashboardModalConnected, {
- noWrap: true,
- })}
- </Route>
-
- <Route path="/question">
- <Route
- path="/question/entity/:entity_id/*"
- element={createEntityIdRedirect({
- parametersToTranslate: [
+export const getRoutes = (store: AppStore): RouteObject[] => [
+ {
+ element: <App />,
+ children: [
+ // SETUP
+ {
+ element: <RedirectIfSetup />,
+ children: [{ path: "/setup", element: <Setup /> }],
+ },
+
+ // For compatibility: use the standard setup for embedding
+ { path: "/setup/embedding", element: redirect("/setup") },
+
+ // APP
+ {
+ element: <LoadCurrentUser />,
+ children: [
+ // AUTH
+ {
+ path: "/auth",
+ children: [
+ { index: true, element: redirect("/auth/login") },
+ {
+ element: <IsNotAuthenticated />,
+ children: [
+ { path: "login", element: <Login /> },
+ { path: "login/:provider", element: <Login /> },
+ ],
+ },
+ { path: "logout", element: <Logout /> },
+ { path: "forgot_password", element: <ForgotPassword /> },
+ { path: "reset_password/:token", element: <ResetPassword /> },
+ // FE routes can sometimes be prioritized over BE
+ // reloading will correctly pick the SSO flow back up from the BE
+ { path: "sso", element: <SsoReload /> },
+ { path: "sso/:provider", element: <SsoReload /> },
+ ],
+ },
+
+ // MAIN
+ {
+ element: <IsAuthenticated />,
+ children: [
+ ...toRouteObjects(getMetabotRoutes()),
+
+ ...(PLUGIN_DATA_APPS.isEnabled
+ ? toRouteObjects(PLUGIN_DATA_APPS.getRoutes())
+ : []),
+
+ // The global all hands routes, things in here are for all the folks
+ { path: "/", element: <LandingPageRedirect /> },
+
+ {
+ path: "getting-started",
+ element: <CanAccessOnboarding />,
+ children: [{ index: true, element: <Onboarding /> }],
+ },
+
+ { path: "search", element: <SearchApp /> },
+ // Send historical /archive route to trash - can remove in v52
+ { path: "archive", element: redirect("trash") },
+ { path: "trash", element: <TrashCollectionLanding /> },
+
+ {
+ path: "document/:entityId",
+ element: <DocumentPageOuter />,
+ children: toRouteObjects(
+ modalRoute("comments/:childTargetId", CommentsSidesheet, {
+ noWrap: true,
+ }),
+ ),
+ },
+
+ {
+ path: "collection/entity/:entity_id/*",
+ element: createEntityIdRedirect({
+ parametersToTranslate: [
+ {
+ name: "entity_id",
+ resourceType: "collection",
+ type: "param",
+ },
+ ],
+ }),
+ },
+
+ {
+ path: "collection/users",
+ element: <IsAdmin />,
+ children: [{ index: true, element: <UserCollectionList /> }],
+ },
+
+ {
+ path: "collection/tenant-specific",
+ element: <PLUGIN_TENANTS.CanAccessTenantSpecificRoute />,
+ children: [
{
- name: "entity_id",
- resourceType: "card",
- type: "param",
+ index: true,
+ element: <PLUGIN_TENANTS.TenantCollectionList />,
},
],
- })}
- />
- <Route index element={<QueryBuilder />} />
- <Route path="notebook" element={<QueryBuilder />} />
- <Route path="ask" element={<MetabotQueryBuilder />} />
- <Route path=":slug" element={<QueryBuilder />} />
- <Route path=":slug/notebook" element={<QueryBuilder />} />
- <Route path=":slug/metabot" element={<QueryBuilder />} />
- <Route path=":slug/:objectId" element={<QueryBuilder />} />
- </Route>
-
- {/* MODELS */}
- {getModelRoutes()}
-
- <Route path="/model">
- <Route index element={<QueryBuilder />} />
- <Route path="new" element={<NewModelOptions />} />
- <Route path=":slug" element={<QueryBuilder />} />
- <Route path=":slug/notebook" element={<QueryBuilder />} />
- <Route path=":slug/query" element={<QueryBuilder />} />
- <Route path=":slug/columns" element={<QueryBuilder />} />
- <Route path=":slug/metadata" element={<QueryBuilder />} />
- <Route path=":slug/metabot" element={<QueryBuilder />} />
- <Route path=":slug/:objectId" element={<QueryBuilder />} />
- <Route path="query" element={<QueryBuilder />} />
- <Route path="metabot" element={<QueryBuilder />} />
- </Route>
-
- {getMetricRoutes()}
-
- <Route path="browse">
- <Route index element={redirect("/browse/models")} />
- <Route path="metrics" element={<BrowseMetrics />} />
- <Route path="models" element={<BrowseModels />} />
- <Route path="databases" element={<BrowseDatabases />} />
- <Route path="databases/:slug" element={<BrowseSchemas />} />
- <Route
- path="databases/:dbId/schema/:schemaName"
- element={<BrowseTables />}
- />
- <Route
- path="databases/:dbName/schema/:schemaName/table/:tableName"
- element={<TablePermalinkRedirect />}
- />
- <Route
- path="databases/:dbName/table/:tableName"
- element={<TablePermalinkRedirect />}
- />
-
- {PLUGIN_TABLE_EDITING.getRoutes()}
-
- {/* These two Redirects support legacy paths in v48 and earlier */}
- <Route path=":dbIdAndSlug" element={<LegacyBrowseRedirect />} />
- <Route
- path=":dbId/schema/:schemaName"
- element={redirect("databases/:dbId/schema/:schemaName")}
- />
- </Route>
-
- <Route path="explore" element={<MetricsViewerPage />} />
-
- <Route path="table">
- <Route path=":slug" element={<QueryBuilder />} />
- <Route
- path=":tableId/detail/:rowId"
- element={<TableDetailPage />}
- />
- </Route>
-
- {/* INDIVIDUAL DASHBOARDS */}
-
- <Route path="/auto/dashboard/*" element={<AutomaticDashboardApp />} />
-
- {/* REFERENCE */}
- <Route path="/reference">
- <Route index element={redirect("/reference/databases")} />
- <Route path="segments" element={<SegmentListContainer />} />
- <Route
- path="segments/:segmentId"
- element={<SegmentDetailContainer />}
- />
- <Route
- path="segments/:segmentId/fields"
- element={<SegmentFieldListContainer />}
- />
- <Route
- path="segments/:segmentId/fields/:fieldId"
- element={<SegmentFieldDetailContainer />}
- />
- <Route
- path="segments/:segmentId/questions"
- element={<SegmentQuestionsContainer />}
- />
- <Route
- path="segments/:segmentId/revisions"
- element={<SegmentRevisionsContainer />}
- />
- <Route path="databases" element={<DatabaseListContainer />} />
- <Route
- path="databases/:databaseId"
- element={<DatabaseDetailContainer />}
- />
- <Route
- path="databases/:databaseId/tables"
- element={<TableListContainer />}
- />
- <Route
- path="databases/:databaseId/tables/:tableId"
- element={<TableDetailContainer />}
- />
- <Route
- path="databases/:databaseId/tables/:tableId/fields"
- element={<FieldListContainer />}
- />
- <Route
- path="databases/:databaseId/tables/:tableId/fields/:fieldId"
- element={<FieldDetailContainer />}
- />
- <Route
- path="databases/:databaseId/tables/:tableId/questions"
- element={<TableQuestionsContainer />}
- />
- <Route path="glossary" element={<GlossaryContainer />} />
- </Route>
-
- {/* ACCOUNT */}
- {getAccountRoutes(store, IsAuthenticated)}
-
- {/* ADMIN */}
- {getAdminRoutes(store, CanAccessSettings, IsAdmin)}
-
- {/* DATA STUDIO */}
- {getDataStudioRoutes(IsAdmin)}
-
- {/* MONITOR */}
- {getMonitorRoutes()}
- </Route>
- </Route>
-
- {/* DEPRECATED */}
- {/* NOTE: these custom routes are needed because <Redirect> doesn't preserve the hash */}
- <Route path="/q" element={<QuestionHashRedirect />} />
- <Route path="/card/:slug" element={<QuestionHashRedirect />} />
- <Route
- path="/dash/:dashboardId"
- element={redirect("/dashboard/:dashboardId")}
- />
- <Route
- path="/collections/permissions"
- element={redirect("/admin/permissions/collections")}
- />
-
- {/* Transforms moved from /admin to /data-studio */}
- <Route
- path="/admin/transforms"
- element={redirect("/data-studio/transforms")}
- />
- <Route
- path="/admin/transforms/*"
- element={redirect("/data-studio/transforms/*")}
- />
-
- {/* Dependency diagnostics moved from /data-studio to /monitor */}
- {getMonitorRedirects()}
-
- {/* MISC */}
- <Route path="/unsubscribe" element={<UnsubscribePage />} />
- <Route path="/unauthorized" element={<Unauthorized />} />
- <Route path="/*" element={<NotFoundFallbackPage />} />
- </Route>
- );
-};
+ },
+
+ {
+ path: "collection/tenant-users",
+ element: <IsAdmin />,
+ children: [
+ { index: true, element: <PLUGIN_TENANTS.TenantUsersList /> },
+ {
+ path: ":tenantId",
+ element: (
+ <PLUGIN_TENANTS.TenantUsersPersonalCollectionList />
+ ),
+ },
+ ],
+ },
+
+ {
+ path: "collection/:slug",
+ element: <CollectionLanding />,
+ children: toRouteObjects(
+ <>
+ {modalRoute("move", MoveCollectionModal, { noWrap: true })}
+ {modalRoute("archive", ArchiveCollectionModal, {
+ noWrap: true,
+ })}
+ {modalRoute("permissions", CollectionPermissionsModal)}
+ {modalRoute(
+ "move-questions-dashboard",
+ MoveQuestionsIntoDashboardsModal,
+ )}
+ {PLUGIN_COLLECTIONS.cleanUpRoute}
+ {getCollectionTimelineRoutes()}
+ </>,
+ ),
+ },
+
+ {
+ path: "dashboard/entity/:entity_id/*",
+ element: createEntityIdRedirect({
+ parametersToTranslate: [
+ {
+ name: "entity_id",
+ resourceType: "dashboard",
+ type: "param",
+ },
+ {
+ name: "tab",
+ resourceType: "dashboard-tab",
+ type: "search",
+ },
+ ],
+ }),
+ },
+
+ {
+ path: "dashboard/:slug",
+ element: <DashboardApp />,
+ children: toRouteObjects(
+ <>
+ {modalRoute("move", DashboardMoveModalConnected, {
+ noWrap: true,
+ })}
+ {modalRoute("copy", DashboardCopyModalConnected, {
+ noWrap: true,
+ })}
+ {modalRoute("archive", ArchiveDashboardModalConnected, {
+ noWrap: true,
+ })}
+ </>,
+ ),
+ },
+
+ {
+ path: "/question",
+ children: [
+ {
+ path: "/question/entity/:entity_id/*",
+ element: createEntityIdRedirect({
+ parametersToTranslate: [
+ {
+ name: "entity_id",
+ resourceType: "card",
+ type: "param",
+ },
+ ],
+ }),
+ },
+ { index: true, element: <QueryBuilder /> },
+ { path: "notebook", element: <QueryBuilder /> },
+ { path: "ask", element: <MetabotQueryBuilder /> },
+ { path: ":slug", element: <QueryBuilder /> },
+ { path: ":slug/notebook", element: <QueryBuilder /> },
+ { path: ":slug/metabot", element: <QueryBuilder /> },
+ { path: ":slug/:objectId", element: <QueryBuilder /> },
+ ],
+ },
+
+ // MODELS
+ ...toRouteObjects(getModelRoutes()),
+
+ {
+ path: "/model",
+ children: [
+ { index: true, element: <QueryBuilder /> },
+ { path: "new", element: <NewModelOptions /> },
+ { path: ":slug", element: <QueryBuilder /> },
+ { path: ":slug/notebook", element: <QueryBuilder /> },
+ { path: ":slug/query", element: <QueryBuilder /> },
+ { path: ":slug/columns", element: <QueryBuilder /> },
+ { path: ":slug/metadata", element: <QueryBuilder /> },
+ { path: ":slug/metabot", element: <QueryBuilder /> },
+ { path: ":slug/:objectId", element: <QueryBuilder /> },
+ { path: "query", element: <QueryBuilder /> },
+ { path: "metabot", element: <QueryBuilder /> },
+ ],
+ },
+
+ ...toRouteObjects(getMetricRoutes()),
+
+ {
+ path: "browse",
+ children: [
+ { index: true, element: redirect("/browse/models") },
+ { path: "metrics", element: <BrowseMetrics /> },
+ { path: "models", element: <BrowseModels /> },
+ { path: "databases", element: <BrowseDatabases /> },
+ { path: "databases/:slug", element: <BrowseSchemas /> },
+ {
+ path: "databases/:dbId/schema/:schemaName",
+ element: <BrowseTables />,
+ },
+ {
+ path: "databases/:dbName/schema/:schemaName/table/:tableName",
+ element: <TablePermalinkRedirect />,
+ },
+ {
+ path: "databases/:dbName/table/:tableName",
+ element: <TablePermalinkRedirect />,
+ },
+
+ ...toRouteObjects(PLUGIN_TABLE_EDITING.getRoutes()),
+
+ // These two redirects support legacy paths in v48 and earlier
+ { path: ":dbIdAndSlug", element: <LegacyBrowseRedirect /> },
+ {
+ path: ":dbId/schema/:schemaName",
+ element: redirect("databases/:dbId/schema/:schemaName"),
+ },
+ ],
+ },
+
+ { path: "explore", element: <MetricsViewerPage /> },
+
+ {
+ path: "table",
+ children: [
+ { path: ":slug", element: <QueryBuilder /> },
+ {
+ path: ":tableId/detail/:rowId",
+ element: <TableDetailPage />,
+ },
+ ],
+ },
+
+ // INDIVIDUAL DASHBOARDS
+ { path: "/auto/dashboard/*", element: <AutomaticDashboardApp /> },
+
+ // REFERENCE
+ {
+ path: "/reference",
+ children: [
+ { index: true, element: redirect("/reference/databases") },
+ { path: "segments", element: <SegmentListContainer /> },
+ {
+ path: "segments/:segmentId",
+ element: <SegmentDetailContainer />,
+ },
+ {
+ path: "segments/:segmentId/fields",
+ element: <SegmentFieldListContainer />,
+ },
+ {
+ path: "segments/:segmentId/fields/:fieldId",
+ element: <SegmentFieldDetailContainer />,
+ },
+ {
+ path: "segments/:segmentId/questions",
+ element: <SegmentQuestionsContainer />,
+ },
+ {
+ path: "segments/:segmentId/revisions",
+ element: <SegmentRevisionsContainer />,
+ },
+ { path: "databases", element: <DatabaseListContainer /> },
+ {
+ path: "databases/:databaseId",
+ element: <DatabaseDetailContainer />,
+ },
+ {
+ path: "databases/:databaseId/tables",
+ element: <TableListContainer />,
+ },
+ {
+ path: "databases/:databaseId/tables/:tableId",
+ element: <TableDetailContainer />,
+ },
+ {
+ path: "databases/:databaseId/tables/:tableId/fields",
+ element: <FieldListContainer />,
+ },
+ {
+ path: "databases/:databaseId/tables/:tableId/fields/:fieldId",
+ element: <FieldDetailContainer />,
+ },
+ {
+ path: "databases/:databaseId/tables/:tableId/questions",
+ element: <TableQuestionsContainer />,
+ },
+ { path: "glossary", element: <GlossaryContainer /> },
+ ],
+ },
+
+ // ACCOUNT
+ ...toRouteObjects(getAccountRoutes(store, IsAuthenticated)),
+
+ // ADMIN
+ ...toRouteObjects(
+ getAdminRoutes(store, CanAccessSettings, IsAdmin),
+ ),
+
+ // DATA STUDIO
+ ...toRouteObjects(getDataStudioRoutes(IsAdmin)),
+
+ // MONITOR
+ ...toRouteObjects(getMonitorRoutes()),
+ ],
+ },
+ ],
+ },
+
+ // DEPRECATED
+ // NOTE: these custom routes are needed because a redirect doesn't preserve the hash
+ { path: "/q", element: <QuestionHashRedirect /> },
+ { path: "/card/:slug", element: <QuestionHashRedirect /> },
+ {
+ path: "/dash/:dashboardId",
+ element: redirect("/dashboard/:dashboardId"),
+ },
+ {
+ path: "/collections/permissions",
+ element: redirect("/admin/permissions/collections"),
+ },
+
+ // Transforms moved from /admin to /data-studio
+ {
+ path: "/admin/transforms",
+ element: redirect("/data-studio/transforms"),
+ },
+ {
+ path: "/admin/transforms/*",
+ element: redirect("/data-studio/transforms/*"),
+ },
+
+ // Dependency diagnostics moved from /data-studio to /monitor
+ ...toRouteObjects(getMonitorRedirects()),
+
+ // MISC
+ { path: "/unsubscribe", element: <UnsubscribePage /> },
+ { path: "/unauthorized", element: <Unauthorized /> },
+ { path: "/*", element: <NotFoundFallbackPage /> },
+ ],
+ },
+];
diff --git a/frontend/src/metabase/routes.unit.spec.tsx b/frontend/src/metabase/routes.unit.spec.tsx
index 332e9ce17d7..031fece7ea4 100644
--- a/frontend/src/metabase/routes.unit.spec.tsx
+++ b/frontend/src/metabase/routes.unit.spec.tsx
@@ -1,11 +1,7 @@
-import { render, waitFor } from "@testing-library/react";
+import { waitFor } from "@testing-library/react";
import { setupCurrentUserEndpoint } from "__support__/server-mocks";
-import {
- getTestStoreAndWrapper,
- renderWithProviders,
- screen,
-} from "__support__/ui";
+import { renderRoutes, renderWithProviders, screen } from "__support__/ui";
import { PLUGIN_AUDIT, reinitialize } from "metabase/plugins";
import { Route } from "metabase/router";
import { createMockUser } from "metabase-types/api/mocks";
@@ -73,12 +69,10 @@ function setupAppRoutes({
initialRoute: string;
user?: ReturnType<typeof createMockUser>;
}) {
- const { wrapper, store, history } = getTestStoreAndWrapper({
- withRouter: true,
+ const { history } = renderRoutes(getRoutes, {
initialRoute,
storeInitialState: { currentUser: user },
});
- render(getRoutes(store), { wrapper });
return { history };
}
diff --git a/frontend/test/__support__/ui.tsx b/frontend/test/__support__/ui.tsx
index 5a95e23da3d..6238cd7d3a1 100644
--- a/frontend/test/__support__/ui.tsx
+++ b/frontend/test/__support__/ui.tsx
@@ -46,12 +46,14 @@ import {
type LocationDescriptor,
type MemoryTestRouterHolder,
Route,
+ type RouteObject,
RouterProviderMemory,
createLocationMirror,
createRouterNavigator,
routerMiddleware,
toFacadeLocation,
toNavigateArgs,
+ toRouteObjects,
} from "metabase/router";
import { getMetabaseCssVariables } from "metabase/styled-components/theme/css-variables";
import type { MantineThemeOverride } from "metabase/ui";
@@ -128,6 +130,27 @@ export function renderWithProviders(
};
}
+/**
+ * Renders route objects, for a spec that has them already, such as the app's own
+ * `getRoutes`. Pass a function to build them from the store the harness makes.
+ */
+export function renderRoutes(
+ routes: RouteObject[] | ((store: Store<State>) => RouteObject[]),
+ { initialRoute = "/", ...options }: RenderWithProvidersOptions = {},
+) {
+ const {
+ wrapper: Wrapper,
+ store,
+ history,
+ } = getTestStoreAndWrapper({ ...options, initialRoute, withRouter: true });
+
+ const utils = testingLibraryRender(
+ <Wrapper routes={typeof routes === "function" ? routes(store) : routes} />,
+ );
+
+ return { ...utils, store, history };
+}
+
export function renderHookWithProviders<TProps, TResult>(
hook: (props: TProps) => TResult,
{
@@ -288,6 +311,7 @@ const TestColorSchemeProvider = ({ children }: React.PropsWithChildren) => {
export function TestWrapper({
children,
+ routes,
store,
routerHolder,
withRouter,
@@ -299,7 +323,12 @@ export function TestWrapper({
displayTheme,
withCssVariables = false,
}: {
- children: React.ReactElement;
+ children?: React.ReactElement;
+ /**
+ * Routes to mount, for a spec that has them as objects already, such as the
+ * app's own `getRoutes`. Takes the place of rendering a `<Route>` tree.
+ */
+ routes?: RouteObject[];
store: any;
routerHolder?: MemoryTestRouterHolder;
withRouter: boolean;
@@ -338,6 +367,7 @@ export function TestWrapper({
<MaybeKBar hasKBar={withKBar}>
<MaybeRouter
hasRouter={withRouter}
+ routes={routes}
routerHolder={routerHolder}
initialRoute={initialRoute}
>
@@ -435,11 +465,13 @@ function childrenAreRouteTree(children: React.ReactNode): boolean {
function MaybeRouter({
children,
+ routes,
hasRouter,
routerHolder,
initialRoute,
}: {
- children: React.ReactElement;
+ children?: React.ReactElement;
+ routes?: RouteObject[];
hasRouter: boolean;
routerHolder?: MemoryTestRouterHolder;
initialRoute: string;
@@ -451,24 +483,33 @@ function MaybeRouter({
);
if (!hasRouter) {
- return children;
+ 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 (
<RouterProviderMemory
+ routes={routes ?? toRoutes(children)}
initialRoute={initialRoute}
routerHolder={routerHolder}
onLocationChange={onLocationChange}
- >
- {content}
- </RouterProviderMemory>
+ />
+ );
+}
+
+/**
+ * Tests render either a `<Route>` tree or a bare component. Only a bare
+ * component needs anything doing to it: it gets a catch-all route to sit in.
+ * A spec that has routes as objects passes them as `routes` instead.
+ */
+function toRoutes(children?: React.ReactElement): RouteObject[] {
+ if (!children) {
+ return [];
+ }
+ return toRouteObjects(
+ childrenAreRouteTree(children) ? (
+ children
+ ) : (
+ <Route path="*" element={children} />
+ ),
);
}