Skip to content

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

Repoint the facade location hooks at react-router v7 and free Palette from route props (#78669)

Romeo Van Snicka3f725976367
diff --git a/frontend/src/metabase/palette/components/Palette.tsx b/frontend/src/metabase/palette/components/Palette.tsx
index aeccbe1b587..8bd43bd1842 100644
--- a/frontend/src/metabase/palette/components/Palette.tsx
+++ b/frontend/src/metabase/palette/components/Palette.tsx
@@ -3,7 +3,7 @@ import { useEffect, useRef } from "react";
import { useOnClickOutside } from "metabase/common/hooks/use-on-click-outside";
import { useSelector } from "metabase/redux";
-import { type PlainRoute, type Query, useRouter } from "metabase/router";
+import { type Query, useRouter } from "metabase/router";
import { getUser } from "metabase/selectors/user";
import { Box, Card, Center, Icon, Overlay, Stack, rem } from "metabase/ui";
import { isWithinIframe } from "metabase/utils/iframe";
@@ -15,26 +15,23 @@ import { HydratedKBarSearch } from "./HydratedKBarSearch";
import S from "./Palette.module.css";
import { PaletteResults } from "./PaletteResults";
-type CommandPaletteRouteProps = {
- disableCommandPalette?: boolean;
-};
+// The setup flow runs before there is an instance to search or act on.
+const PALETTE_DISABLED_PATHS = ["/setup"];
/** Command palette */
export const Palette = () => {
const routerProps = useRouter();
- const { routes, location } = routerProps;
+ const { location } = routerProps;
const isLoggedIn = useSelector((state) => !!getUser(state));
- const disableCommandPaletteForRoute = routes.some(
- (route: PlainRoute<CommandPaletteRouteProps>) =>
- route.props?.disableCommandPalette,
+ const isDisabledForPath = PALETTE_DISABLED_PATHS.some((path) =>
+ location.pathname.startsWith(path),
);
useCommandPaletteBasicActions({ ...routerProps, isLoggedIn });
const { query } = useKBar();
- const disabled =
- isWithinIframe() || !isLoggedIn || disableCommandPaletteForRoute;
+ const disabled = isWithinIframe() || !isLoggedIn || isDisabledForPath;
useEffect(() => {
query.disable(disabled);
}, [disabled, query]);
diff --git a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
index 34a10754caa..9c960dd86ba 100644
--- a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
@@ -20,12 +20,10 @@ import {
import { Palette } from "./Palette";
const setup = ({
- routeProps,
initialRoute,
searchResults = [],
searchResultsDelay,
}: {
- routeProps?: { disableCommandPalette?: boolean };
initialRoute?: string;
searchResults?: SearchResult[];
searchResultsDelay?: number;
@@ -37,11 +35,7 @@ const setup = ({
collections: [createMockCollection({ id: "root", can_write: true })],
});
renderWithProviders(
- <Route
- path={initialRoute ? "*" : "/"}
- element={<Palette />}
- props={routeProps}
- />,
+ <Route path={initialRoute ? "*" : "/"} element={<Palette />} />,
{
withKBar: true,
withRouter: true,
@@ -64,15 +58,15 @@ describe("command palette", () => {
expect(screen.getByTestId("command-palette")).toBeInTheDocument();
});
- it("should not render if the route has disabled the command palette", async () => {
- setup({ routeProps: { disableCommandPalette: true } });
+ it("should not render on a path that disables the command palette", async () => {
+ setup({ initialRoute: "/setup" });
await userEvent.keyboard("[ControlLeft>]k");
expect(screen.queryByTestId("command-palette")).not.toBeInTheDocument();
});
it("should not call recents API when palette is disabled", async () => {
- setup({ routeProps: { disableCommandPalette: true } });
+ setup({ initialRoute: "/setup" });
await userEvent.keyboard("[ControlLeft>]k");
diff --git a/frontend/src/metabase/router/Outlet.tsx b/frontend/src/metabase/router/Outlet.tsx
index e0b3e2ee18d..1cbe3d24b84 100644
--- a/frontend/src/metabase/router/Outlet.tsx
+++ b/frontend/src/metabase/router/Outlet.tsx
@@ -1,10 +1,7 @@
-import type { ReactNode } from "react";
import { createContext, useContext } from "react";
import type { Route } from "./route";
-export const OutletContext = createContext<ReactNode>(null);
-
export const RouteContext = createContext<Route | null>(null);
/**
@@ -21,7 +18,4 @@ export function useRoute(): Route | null {
*
* @see https://reactrouter.com/7.18.1/api/components/Outlet
*/
-export function Outlet(): JSX.Element {
- const child = useContext(OutletContext);
- return <>{child}</>;
-}
+export { Outlet } from "react-router";
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 36deab3b11f..5bd628e5455 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -198,11 +198,10 @@ export type RouteComponent = ComponentClass<any> | FunctionComponent<any>;
* 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> {
+export interface RouteProps {
children?: ReactNode;
path?: string;
component?: RouteComponent;
- props?: Props;
}
/**
@@ -210,7 +209,7 @@ export interface RouteProps<Props = any> {
* `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> {
+export interface PlainRoute extends RouteProps {
childRoutes?: PlainRoute[];
indexRoute?: PlainRoute;
pathnameBase?: string;
diff --git a/frontend/src/metabase/router/use-location.ts b/frontend/src/metabase/router/use-location.ts
index 367d81c7be3..f8f7c6997ae 100644
--- a/frontend/src/metabase/router/use-location.ts
+++ b/frontend/src/metabase/router/use-location.ts
@@ -1,34 +1,8 @@
-import { useMemo } from "react";
-
-import type { Location } from "./types";
-import { useRouter } from "./use-router";
-
/**
- * react-router v7's `useLocation`, implemented over the location injected into
- * the router context (mirrored into redux `state.routing`). Returns the pure v7
- * `Location` shape (no v3 `query`/`action` fields); the legacy compat `Location`
- * type carries those for the route-prop call sites.
+ * react-router v7's `useLocation`. Returns the pure v7 `Location` shape (no v3
+ * `query`/`action` fields); the legacy compat `Location` type carries those for
+ * the route-prop call sites.
*
* @see https://reactrouter.com/7.18.1/api/hooks/useLocation
*/
-export function useLocation(): Omit<Location, "query" | "action"> {
- const { location } = useRouter();
-
- return useMemo(
- () => ({
- pathname: location.pathname,
- search: location.search,
- hash: location.hash,
- // v3 leaves state `undefined` when absent, v7 uses `null`.
- state: location.state ?? null,
- key: location.key,
- }),
- [
- location.pathname,
- location.search,
- location.hash,
- location.state,
- location.key,
- ],
- );
-}
+export { useLocation } from "react-router";
diff --git a/frontend/src/metabase/router/use-location.unit.spec.tsx b/frontend/src/metabase/router/use-location.unit.spec.tsx
index 0d7347bf68a..2fe292901ae 100644
--- a/frontend/src/metabase/router/use-location.unit.spec.tsx
+++ b/frontend/src/metabase/router/use-location.unit.spec.tsx
@@ -1,3 +1,5 @@
+import { MemoryRouter } from "react-router";
+
import { renderWithProviders, screen } from "__support__/ui";
import { Route } from "./route";
@@ -28,16 +30,18 @@ describe("router/useLocation", () => {
expect(screen.getByTestId("hash")).toHaveTextContent("#section");
});
- it("returns exactly the v7 Location fields, without v3's `query`", () => {
+ it("does not carry v3's `query` and `action` fields", () => {
renderWithProviders(<Route path="foo/bar" element={<LocationProbe />} />, {
withRouter: true,
initialRoute: "/foo/bar?x=1",
});
- // v7's Location is exactly { pathname, search, hash, state, key }, no `query`.
- expect(screen.getByTestId("keys")).toHaveTextContent(
- /^hash,key,pathname,search,state$/,
+ const keys = screen.getByTestId("keys").textContent?.split(",");
+ expect(keys).toEqual(
+ expect.arrayContaining(["pathname", "search", "hash"]),
);
+ expect(keys).not.toContain("query");
+ expect(keys).not.toContain("action");
});
it("defaults state to null like v7 (not v3's undefined)", () => {
@@ -48,4 +52,15 @@ describe("router/useLocation", () => {
expect(screen.getByTestId("state")).toHaveTextContent(/^null$/);
});
+
+ it("works above the route tree, where the facade context is not published", () => {
+ renderWithProviders(
+ <MemoryRouter initialEntries={["/foo/bar?x=1"]}>
+ <LocationProbe />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTestId("pathname")).toHaveTextContent("/foo/bar");
+ expect(screen.getByTestId("search")).toHaveTextContent("?x=1");
+ });
});
diff --git a/frontend/src/metabase/router/use-params.ts b/frontend/src/metabase/router/use-params.ts
index 22a68ee69f7..390818d99a8 100644
--- a/frontend/src/metabase/router/use-params.ts
+++ b/frontend/src/metabase/router/use-params.ts
@@ -1,30 +1,7 @@
-import type { Params } from "./types";
-import { useRouter } from "./use-router";
-
/**
- * react-router v7's `useParams`, implemented over the params injected by
- * react-router v3 into the router context. Values are URI-decoded like v7, and
- * the v3 splat param (`splat`) is exposed under v7's `*` key.
+ * react-router v7's `useParams`. Values are URI-decoded and the wildcard match is
+ * exposed under v7's `*` key (v3 called it `splat`).
*
* @see https://reactrouter.com/7.18.1/api/hooks/useParams
*/
-export function useParams<
- ParamsOrKey extends string | Record<string, string | undefined> = string,
->(): Readonly<
- [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>
-> {
- type Result = Readonly<
- [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>
- >;
- const params = useRouter().params;
-
- if (!("splat" in params)) {
- // Unjustified type cast. FIXME
- return params as Result;
- }
-
- const { splat, ...rest } = params;
- const remapped: typeof params = { ...rest, "*": splat };
- // Unjustified type cast. FIXME
- return remapped as Result;
-}
+export { useParams } from "react-router";
diff --git a/frontend/src/metabase/router/use-params.unit.spec.tsx b/frontend/src/metabase/router/use-params.unit.spec.tsx
index 7d9f9506e01..53c38601406 100644
--- a/frontend/src/metabase/router/use-params.unit.spec.tsx
+++ b/frontend/src/metabase/router/use-params.unit.spec.tsx
@@ -1,3 +1,9 @@
+import {
+ MemoryRouter,
+ Route as V7Route,
+ Routes as V7Routes,
+} from "react-router";
+
import { renderWithProviders, screen } from "__support__/ui";
import { Route } from "./route";
@@ -49,4 +55,16 @@ describe("router/useParams", () => {
expect(screen.getByTestId("splat")).toHaveTextContent("a/b");
expect(screen.getByTestId("has-splat-key")).toHaveTextContent("false");
});
+
+ it("works outside the facade route tree, reading the host's own match", () => {
+ renderWithProviders(
+ <MemoryRouter initialEntries={["/files/a/b"]}>
+ <V7Routes>
+ <V7Route path="files/*" element={<SplatProbe />} />
+ </V7Routes>
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTestId("splat")).toHaveTextContent("a/b");
+ });
});
diff --git a/frontend/src/metabase/router/v7/RouterBridge.tsx b/frontend/src/metabase/router/v7/RouterBridge.tsx
index b87be1c711d..24c8ccdfc28 100644
--- a/frontend/src/metabase/router/v7/RouterBridge.tsx
+++ b/frontend/src/metabase/router/v7/RouterBridge.tsx
@@ -4,14 +4,13 @@ import {
type To,
UNSAFE_RouteContext,
type NavigateFunction as V7NavigateFunction,
- Outlet as V7Outlet,
useNavigationType,
useLocation as useV7Location,
useNavigate as useV7Navigate,
useParams as useV7Params,
} from "react-router";
-import { OutletContext, RouteContext } from "../Outlet";
+import { RouteContext } from "../Outlet";
import { RouterContext } from "../RouterProvider";
import type { Route } from "../route";
import type {
@@ -33,10 +32,10 @@ type RouteStub = PlainRoute & { pathnameBase?: string };
/**
* Runs as the `element` of every v7 route and republishes v7's location,
* params, matched-route branch, and an imperative-router shim into the shared
- * `RouterContext` (and the `Outlet`/`Route` contexts). The facade hooks
- * (`useLocation`, `useParams`, `useNavigate`, `useRouter`, `withRouteProps`)
- * read that context unchanged, so nothing downstream can tell which engine it
- * runs on. Deleted with the v3 engine in Phase 4.
+ * `RouterContext` (and the `Route` context). The facade hooks (`useNavigate`,
+ * `useRouter`, `withRouteProps`) read that context unchanged, so nothing
+ * downstream can tell which engine it runs on. Deleted with the v3 engine in
+ * Phase 4.
*/
export function RouterBridge({
v3Element,
@@ -69,7 +68,7 @@ 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 `{ path, props }` on it.
+ // `handle` is typed `unknown`; we only ever put `{ path }` on it.
const handle = match.route.handle as { path?: string } | undefined;
return `${match.pathname}|${handle?.path ?? ""}`;
})
@@ -77,19 +76,11 @@ export function RouterBridge({
const routes = useMemo<RouteStub[]>(
() =>
matches.map((match) => {
- // `handle` is typed `unknown`; we only ever put `{ path, props }` on it.
- const handle = match.route.handle as
- | { path?: string; props?: PlainRoute["props"] }
- | undefined;
+ // `handle` is typed `unknown`; we only ever put `{ path }` on it.
+ const handle = match.route.handle as { path?: string } | 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?.path,
- props: handle?.props,
- pathnameBase: match.pathname,
- };
+ return { path: handle?.path, pathnameBase: match.pathname };
}),
// Keyed on the matched branch, not the array identity, which changes each render.
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -133,11 +124,7 @@ export function RouterBridge({
return (
<RouterContext.Provider value={value}>
- <RouteContext.Provider value={route}>
- <OutletContext.Provider value={<V7Outlet />}>
- {v3Element}
- </OutletContext.Provider>
- </RouteContext.Provider>
+ <RouteContext.Provider value={route}>{v3Element}</RouteContext.Provider>
</RouterContext.Provider>
);
}
diff --git a/frontend/src/metabase/router/v7/map-to-v7.tsx b/frontend/src/metabase/router/v7/map-to-v7.tsx
index 608fc5c2b77..913c361ac70 100644
--- a/frontend/src/metabase/router/v7/map-to-v7.tsx
+++ b/frontend/src/metabase/router/v7/map-to-v7.tsx
@@ -44,7 +44,7 @@ export function mapToV7(node: ReactNode): ReactNode {
}
function toV7Route(element: ReactElement<RouteElementProps>): ReactElement {
- const { path, index, element: routeElement, children, props } = element.props;
+ const { path, index, element: routeElement, children } = element.props;
// v7 defaults a route with no `element` to `<Outlet/>`; only wrap (and publish
// context) when the facade route actually renders something.
@@ -53,11 +53,9 @@ function toV7Route(element: ReactElement<RouteElementProps>): ReactElement {
<RouterBridge v3Element={routeElement} />
) : 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;
+ // Keep the route `path` on `handle`: the matched-route branch the facade
+ // republishes exposes it, and consumers read it (`redirect` reads `route.path`).
+ const handle = path != null ? { path } : undefined;
if (index) {
return <V7Route index element={bridged} handle={handle} />;
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 62275e1aed2..0989dfcf606 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -126,11 +126,7 @@ export const getRoutes = (store: AppStore) => {
<Route element={<RoutedApp />}>
{/* SETUP */}
<Route element={<RedirectIfSetup />}>
- <Route
- path="/setup"
- element={<Setup />}
- props={{ disableCommandPalette: true }}
- />
+ <Route path="/setup" element={<Setup />} />
</Route>
{/* For compatibility: use the standard setup for embedding */}