Skip to content

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

Move the app's link onto react-router's NavLink (#79296)

Romeo Van Snickffc964cd5382
diff --git a/frontend/src/metabase/common/components/Link/BaseLink.tsx b/frontend/src/metabase/common/components/Link/BaseLink.tsx
new file mode 100644
index 00000000000..8d6c7327e51
--- /dev/null
+++ b/frontend/src/metabase/common/components/Link/BaseLink.tsx
@@ -0,0 +1,149 @@
+import {
+ type CSSProperties,
+ type HTMLProps,
+ type Ref,
+ forwardRef,
+} from "react";
+
+import {
+ NavLink,
+ type NavLinkProps,
+ type NavLinkRenderProps,
+ Link as RouterLink,
+ type To,
+ useInRouterContext,
+} from "metabase/router";
+
+const INACTIVE: NavLinkRenderProps = {
+ isActive: false,
+ isPending: false,
+ isTransitioning: false,
+};
+
+function resolveClassName(
+ className: NavLinkProps["className"],
+ state: NavLinkRenderProps,
+): string | undefined {
+ return typeof className === "function" ? className(state) : className;
+}
+
+function resolveStyle(
+ style: NavLinkProps["style"],
+ state: NavLinkRenderProps,
+): CSSProperties | undefined {
+ return typeof style === "function" ? style(state) : style;
+}
+
+function hrefFor(target: To): string {
+ if (typeof target === "string") {
+ return target;
+ }
+ return `${target.pathname ?? ""}${target.search ?? ""}${target.hash ?? ""}`;
+}
+
+/**
+ * A bare path such as `to="reference"` means `/reference` throughout the app,
+ * but react-router resolves it against the current route instead, which would
+ * nest it. Anchor it so the target does not depend on where the link renders.
+ *
+ * Left alone: a leading `?` or `#`, which keeps the current path by design, and
+ * anything carrying a scheme (`https:`, `mailto:`) or a protocol-relative `//`,
+ * which is not a route at all.
+ */
+function toRootRelative(pathname: string): string {
+ const isAlreadyAnchored = pathname === "" || /^[/?#]/.test(pathname);
+ const hasScheme = /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(pathname);
+ return isAlreadyAnchored || hasScheme ? pathname : `/${pathname}`;
+}
+
+function anchorTarget(to: To): To {
+ if (typeof to === "string") {
+ return toRootRelative(to);
+ }
+ return typeof to.pathname === "string"
+ ? { ...to, pathname: toRootRelative(to.pathname) }
+ : to;
+}
+
+export interface BaseLinkProps extends Omit<
+ HTMLProps<any>,
+ "className" | "style"
+> {
+ // Optional: a link with no destination is used as a button, navigating through
+ // its own `onClick`.
+ to?: To;
+ /**
+ * Pass a callback to style the link by whether its target is the active route.
+ */
+ className?: NavLinkProps["className"];
+ /**
+ * Pass a callback to style the link by whether its target is the active route.
+ */
+ style?: NavLinkProps["style"];
+ // Match the target exactly rather than as a route prefix, for `isActive`.
+ end?: boolean;
+ // Mantine forwards a ref through this name; see `ForwardRefLink`.
+ innerRef?: Ref<HTMLAnchorElement>;
+}
+
+/**
+ * The app's unstyled router link. Renders react-router's `NavLink` when a call
+ * site asks for active styling and its plain `Link` otherwise, so only the links
+ * that need it subscribe to the current route.
+ */
+export const BaseLink = forwardRef<HTMLAnchorElement, BaseLinkProps>(
+ function BaseLink({ to, innerRef, className, style, end, ...rest }, ref) {
+ const linkRef = ref ?? innerRef;
+ const inRouter = useInRouterContext();
+
+ // A link with no destination (`to` null or `""`) is used as a button: it
+ // navigates through its `onClick`. A real `<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.
+ //
+ // `<Link>` also 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 that path never runs there.
+ if (to == null || to === "" || !inRouter) {
+ const href = to == null || to === "" ? undefined : hrefFor(to);
+ return (
+ <a
+ {...rest}
+ href={href}
+ className={resolveClassName(className, INACTIVE)}
+ style={resolveStyle(style, INACTIVE)}
+ ref={linkRef}
+ />
+ );
+ }
+
+ const target = anchorTarget(to);
+
+ if (typeof className === "function" || typeof style === "function") {
+ return (
+ <NavLink
+ {...rest}
+ to={target}
+ end={end}
+ // Normalize both to callbacks: given a plain string `NavLink` appends
+ // its own `active` class, which the app does not use.
+ className={(state) => resolveClassName(className, state)}
+ style={(state) => resolveStyle(style, state)}
+ ref={linkRef}
+ />
+ );
+ }
+
+ return (
+ <RouterLink
+ {...rest}
+ to={target}
+ className={className}
+ style={style}
+ ref={linkRef}
+ />
+ );
+ },
+);
diff --git a/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx b/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx
index 448e917981c..4dc9d140b85 100644
--- a/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx
+++ b/frontend/src/metabase/common/components/Link/ForwardRefLink.tsx
@@ -3,12 +3,11 @@
import { forwardRef } from "react";
-import type { RouterLinkProps as LinkProps } from "metabase/router";
-import { RouterLink as Link } from "metabase/router/router-link";
+import { BaseLink, type BaseLinkProps } from "./BaseLink";
// `ref` prop, we have to manually forward it to the correct prop name to make hover work as expected.
-export const ForwardRefLink = forwardRef<HTMLAnchorElement, LinkProps>(
+export const ForwardRefLink = forwardRef<HTMLAnchorElement, BaseLinkProps>(
function _ForwardRefLink(props, ref) {
- return <Link {...props} innerRef={ref} />;
+ return <BaseLink {...props} innerRef={ref} />;
},
);
diff --git a/frontend/src/metabase/common/components/Link/Link.tsx b/frontend/src/metabase/common/components/Link/Link.tsx
index b45cb55ca6c..6e85a47a07d 100644
--- a/frontend/src/metabase/common/components/Link/Link.tsx
+++ b/frontend/src/metabase/common/components/Link/Link.tsx
@@ -1,8 +1,9 @@
import cx from "classnames";
-import { RouterLink } from "metabase/router/router-link";
+import type { NavLinkRenderProps } from "metabase/router";
import { Tooltip } from "metabase/ui";
+import { BaseLink } from "./BaseLink";
import S from "./Link.module.css";
import type { LinkProps } from "./types";
@@ -15,25 +16,30 @@ export const Link = ({
className,
...props
}: LinkProps): JSX.Element => {
+ const styleClassName = cx(S.link, {
+ [S.disabled]: disabled,
+ [S.brand]: variant === "brand",
+ [S.brandBold]: variant === "brandBold",
+ });
+
+ // Keep the callback form a callback: resolving it here would make every link
+ // track the active route, including the ones that never style themselves by it.
+ const linkClassName =
+ typeof className === "function"
+ ? (state: NavLinkRenderProps) => cx(styleClassName, className(state))
+ : cx(styleClassName, className);
+
const link = (
- <RouterLink
+ <BaseLink
{...props}
- className={cx(
- S.link,
- {
- [S.disabled]: disabled,
- [S.brand]: variant === "brand",
- [S.brandBold]: variant === "brandBold",
- },
- className,
- )}
+ className={linkClassName}
to={to}
disabled={disabled}
tabIndex={disabled ? -1 : undefined}
aria-disabled={disabled}
>
{children}
- </RouterLink>
+ </BaseLink>
);
const tooltipProps =
diff --git a/frontend/src/metabase/common/components/Link/Link.unit.spec.tsx b/frontend/src/metabase/common/components/Link/Link.unit.spec.tsx
index 57928ed0361..9a80caac26b 100644
--- a/frontend/src/metabase/common/components/Link/Link.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Link/Link.unit.spec.tsx
@@ -1,11 +1,166 @@
-import { render, screen } from "__support__/ui";
+import userEvent from "@testing-library/user-event";
+
+import { act, render, renderWithProviders, screen } from "__support__/ui";
+import { Outlet, Route, useLocation, useNavigate } from "metabase/router";
import { Link } from "./Link";
+function Home() {
+ const { pathname, key } = useLocation();
+ const navigate = useNavigate();
+ return (
+ <div>
+ <span data-testid="location">{pathname}</span>
+ <span data-testid="location-key">{key}</span>
+ <Link to="/other">go</Link>
+ {/* A `<Link>` used as a button: it navigates through its own onClick. */}
+ <Link onClick={() => navigate("/other")}>act</Link>
+ {/* A button-like `<Link to="">` (e.g. the undo toast) must not navigate. */}
+ <Link to="" onClick={() => undefined}>
+ noop
+ </Link>
+ <Link
+ to="/"
+ end
+ className={({ isActive }) => (isActive ? "is-active" : "")}
+ >
+ home
+ </Link>
+ <Link
+ to="/other"
+ className={({ isActive }) => (isActive ? "is-active" : "")}
+ >
+ section
+ </Link>
+ {/* A bare path resolves against the root, not the current route. */}
+ <Link to="other">bare</Link>
+ <Link to="https://www.metabase.com/docs">external</Link>
+ <Link to="mailto:[email protected]">mail</Link>
+ <Outlet />
+ </div>
+ );
+}
+
+const tree = (
+ <Route path="/" element={<Home />}>
+ <Route path="other" element={<span data-testid="other">other</span>} />
+ </Route>
+);
+
describe("Link", () => {
it("should render correctly", () => {
render(<Link to="/">Home</Link>);
expect(screen.getByText("Home")).toBeInTheDocument();
});
+
+ 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");
+ });
+
+ it("resolves a bare relative path against the root", async () => {
+ renderWithProviders(tree, {
+ withRouter: true,
+ initialRoute: "/",
+ });
+
+ await userEvent.click(screen.getByRole("link", { name: "bare" }));
+
+ 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: "/",
+ });
+
+ expect(screen.getByRole("link", { name: "external" })).toHaveAttribute(
+ "href",
+ "https://www.metabase.com/docs",
+ );
+ expect(screen.getByRole("link", { name: "mail" })).toHaveAttribute(
+ "href",
+ "mailto:[email protected]",
+ );
+ });
+
+ // react-router downgrades a click to a `replace` when the target equals the
+ // current URL, so the entry is reused rather than stacked. The navigation is
+ // still observable: the location gets a fresh key, which is what the documents
+ // page keys its unsaved-changes prompt off.
+ it("replaces the entry when linking to the current url, with a new location key", async () => {
+ const { history } = renderWithProviders(tree, {
+ withRouter: true,
+ initialRoute: "/",
+ });
+
+ await userEvent.click(screen.getByRole("link", { name: "go" }));
+ await screen.findByTestId("other");
+ const keyBefore = screen.getByTestId("location-key").textContent;
+
+ await userEvent.click(screen.getByRole("link", { name: "go" }));
+
+ expect(screen.getByTestId("location-key")).not.toHaveTextContent(
+ String(keyBefore),
+ );
+
+ // The second click reused the entry instead of stacking one, so a single
+ // step back lands on the page we came from.
+ await act(() => history?.goBack());
+ expect(await screen.findByTestId("location")).toHaveTextContent("/");
+ });
+
+ it("styles the link that matches the route through the isActive callback", async () => {
+ renderWithProviders(tree, {
+ withRouter: true,
+ initialRoute: "/other",
+ });
+
+ await screen.findByTestId("other");
+
+ // The `end` 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: "/",
+ });
+
+ // The click handler performs the navigation; the link itself must not
+ // navigate, or it would clobber it and never reach /other.
+ await userEvent.click(screen.getByText("act"));
+
+ 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",
+ });
+
+ await screen.findByTestId("other");
+
+ // An empty `to` resolves to "/" and would navigate 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");
+ });
});
diff --git a/frontend/src/metabase/common/components/Link/types.ts b/frontend/src/metabase/common/components/Link/types.ts
index 030d2813024..7f1fc6865cd 100644
--- a/frontend/src/metabase/common/components/Link/types.ts
+++ b/frontend/src/metabase/common/components/Link/types.ts
@@ -1,11 +1,8 @@
-import type { RouterLinkProps } from "metabase/router";
import type { TooltipProps } from "metabase/ui";
-export interface LinkProps extends Omit<RouterLinkProps, "to"> {
- // A link with no destination is used as a button: it navigates through its own
- // `onClick` instead. v3's types make `to` required, but both engines handle it
- // being absent, so the app's `Link` allows it.
- to?: RouterLinkProps["to"];
+import type { BaseLinkProps } from "./BaseLink";
+
+export interface LinkProps extends Omit<BaseLinkProps, "innerRef"> {
variant?: "default" | "brand" | "brandBold";
tooltip?: string | TooltipProps;
}
diff --git a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsx b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsx
index d273312ffd9..bb3e08277e8 100644
--- a/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsx
+++ b/frontend/src/metabase/models/components/ModelActions/ModelActionDetails/ModelActionListItem.tsx
@@ -3,8 +3,8 @@ import { useCallback } from "react";
import { t } from "ttag";
import { ActionExecuteModal } from "metabase/actions/containers/ActionExecuteModal";
+import { ForwardRefLink } from "metabase/common/components/Link";
import { useConfirmation } from "metabase/common/hooks/use-confirmation";
-import { RouterLink } from "metabase/router";
import { ActionIcon, Icon, Menu, Tooltip } from "metabase/ui";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
@@ -104,7 +104,7 @@ function ModelActionListItem({
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
- component={RouterLink}
+ component={ForwardRefLink}
data-testid="entity-menu-link"
leftSection={
<Icon name={canEdit ? "pencil" : "eye"} aria-hidden />
diff --git a/frontend/src/metabase/reference/components/SidebarItem/SidebarItem.tsx b/frontend/src/metabase/reference/components/SidebarItem/SidebarItem.tsx
index 77f85c9b940..59c26f92e2c 100644
--- a/frontend/src/metabase/reference/components/SidebarItem/SidebarItem.tsx
+++ b/frontend/src/metabase/reference/components/SidebarItem/SidebarItem.tsx
@@ -1,3 +1,4 @@
+import cx from "classnames";
import { memo } from "react";
import { Link } from "metabase/common/components/Link";
@@ -24,8 +25,7 @@ const SidebarItemInner = ({
<li>
<Link
to={href}
- className={S.item}
- activeClassName={S.selected}
+ className={({ isActive }) => cx(S.item, { [S.selected]: isActive })}
onClick={onClick}
>
<LabelIcon className={S.icon} icon={icon} />
diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.ts
index 32794e41358..f1f1e3d23a6 100644
--- a/frontend/src/metabase/router/index.ts
+++ b/frontend/src/metabase/router/index.ts
@@ -1,7 +1,12 @@
export {
+ Link,
+ NavLink,
+ type NavLinkProps,
+ type NavLinkRenderProps,
Navigate,
Outlet,
Route,
+ useInRouterContext,
useLocation,
useNavigate,
useNavigationType,
@@ -11,7 +16,6 @@ export {
export * from "./middleware";
export * from "./navigation";
export * from "./redirect";
-export * from "./router-link";
export * from "./to-route-objects";
export * from "./location-change";
export * from "./RouterProvider";
diff --git a/frontend/src/metabase/router/router-link.tsx b/frontend/src/metabase/router/router-link.tsx
deleted file mode 100644
index a2d28060e40..00000000000
--- a/frontend/src/metabase/router/router-link.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { type Ref, forwardRef } from "react";
-import {
- Link as ReactRouterLink,
- type LinkProps as ReactRouterLinkProps,
- NavLink as ReactRouterNavLink,
- useInRouterContext,
-} from "react-router";
-
-import type { RouterLinkProps } from "./types";
-
-function hrefFor(target: ReactRouterLinkProps["to"]): string {
- if (typeof target === "string") {
- return target;
- }
- return `${target.pathname ?? ""}${target.search ?? ""}${target.hash ?? ""}`;
-}
-
-type V3To = RouterLinkProps["to"];
-
-// v3 descriptors carry `state` inline; v7 takes it as a separate prop. Translate
-// so existing call sites keep working on v7.
-/**
- * v3 resolved a bare path against the root, so call sites write `to="reference"`
- * meaning `/reference`. v7 resolves it against the current route instead, which
- * would nest it (that link sits on `/browse/databases`). Anchor it so the target
- * does not depend on where the link is rendered.
- *
- * Left alone: a leading `?` or `#`, which keeps the current path by design, and
- * anything carrying a scheme (`https:`, `mailto:`) or a protocol-relative `//`,
- * which is not a route at all.
- */
-function toRootRelative(pathname: string): string {
- const isAlreadyAnchored = pathname === "" || /^[/?#]/.test(pathname);
- const hasScheme = /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(pathname);
- return isAlreadyAnchored || hasScheme ? pathname : `/${pathname}`;
-}
-
-function toReactRouterTarget(to: V3To): {
- to: ReactRouterLinkProps["to"];
- state?: unknown;
-} {
- if (to == null) {
- return { to: "" };
- }
- if (typeof to === "string") {
- return { to: toRootRelative(to) };
- }
- if (typeof to === "function") {
- // v3's function form of `to` has no v7 analog and is not used in the app.
- return { to: "" };
- }
- const { pathname, search, hash, state } = to;
- return {
- to: {
- pathname: pathname == null ? "" : toRootRelative(pathname),
- search,
- hash,
- },
- state,
- };
-}
-
-interface Props extends Omit<RouterLinkProps, "to"> {
- // Optional: a link with no destination is used as a button, navigating through
- // its own `onClick`.
- to?: V3To;
- // v3's ref-forwarding prop; the facade's `ForwardRefLink` still passes it.
- innerRef?: Ref<HTMLAnchorElement>;
-}
-
-export const RouterLink = forwardRef<HTMLAnchorElement, Props>(
- function RouterLink({ to, innerRef, ...props }, ref) {
- const linkRef = ref ?? innerRef;
- const inRouter = useInRouterContext();
-
- // 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 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: reactRouterTo, state } = toReactRouterTarget(to);
-
- // 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(reactRouterTo)} ref={linkRef} />;
- }
-
- // 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 (
- <ReactRouterNavLink
- {...navRest}
- to={reactRouterTo}
- state={state}
- ref={linkRef}
- end={onlyActiveOnIndex}
- className={({ isActive }) =>
- [className, isActive ? activeClassName : null]
- .filter(Boolean)
- .join(" ")
- }
- style={({ isActive }) =>
- isActive ? { ...style, ...activeStyle } : style
- }
- />
- );
- }
-
- return (
- <ReactRouterLink
- {...rest}
- to={reactRouterTo}
- state={state}
- ref={linkRef}
- />
- );
- },
-);
diff --git a/frontend/src/metabase/router/router-link.unit.spec.tsx b/frontend/src/metabase/router/router-link.unit.spec.tsx
deleted file mode 100644
index 3ce899396f8..00000000000
--- a/frontend/src/metabase/router/router-link.unit.spec.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import userEvent from "@testing-library/user-event";
-
-import { act, renderWithProviders, screen } from "__support__/ui";
-import {
- RouterLink as Link,
- Outlet,
- Route,
- useLocation,
- useNavigate,
-} from "metabase/router";
-
-function Home() {
- const { pathname, key } = useLocation();
- const navigate = useNavigate();
- return (
- <div>
- <span data-testid="location">{pathname}</span>
- <span data-testid="location-key">{key}</span>
- <Link to="/other">go</Link>
- {/* A `<Link>` used as a button: it navigates through its own onClick. */}
- <Link onClick={() => navigate("/other")}>act</Link>
- {/* A button-like `<Link to="">` (e.g. the undo toast) must not navigate. */}
- <Link to="" onClick={() => undefined}>
- noop
- </Link>
- <Link to="/" activeClassName="is-active" onlyActiveOnIndex>
- home
- </Link>
- <Link to="/other" activeClassName="is-active">
- section
- </Link>
- {/* v3 resolved a bare path against the root, not the current route. */}
- <Link to="other">bare</Link>
- <Link to="https://www.metabase.com/docs">external</Link>
- <Link to="mailto:[email protected]">mail</Link>
- <Outlet />
- </div>
- );
-}
-
-const tree = (
- <Route path="/" element={<Home />}>
- <Route path="other" element={<span data-testid="other">other</span>} />
- </Route>
-);
-
-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: "/",
- });
-
- await userEvent.click(screen.getByRole("link", { name: "bare" }));
-
- 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: "/",
- });
-
- 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, so the entry is reused rather than stacked. The navigation is
- // still observable: the location gets a fresh key, which is what the documents
- // page keys its unsaved-changes prompt off.
- it("replaces the entry when linking to the current url, with a new location key", async () => {
- const { history } = renderWithProviders(tree, {
- withRouter: true,
- initialRoute: "/",
- });
-
- await userEvent.click(screen.getByRole("link", { name: "go" }));
- await screen.findByTestId("other");
- const keyBefore = screen.getByTestId("location-key").textContent;
-
- await userEvent.click(screen.getByRole("link", { name: "go" }));
-
- expect(screen.getByTestId("location-key")).not.toHaveTextContent(
- String(keyBefore),
- );
-
- // The second click reused the entry instead of stacking one, so a single
- // step back lands on the page we came from.
- await act(() => history?.goBack());
- expect(await screen.findByTestId("location")).toHaveTextContent("/");
- });
-
- it("applies activeClassName to the link that matches the route", async () => {
- renderWithProviders(tree, {
- withRouter: true,
- initialRoute: "/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");
- });
-
- it("does not navigate on its own when used as a button (no `to`)", async () => {
- renderWithProviders(tree, {
- withRouter: true,
- initialRoute: "/",
- });
-
- // The click handler performs the navigation; the link itself must not
- // navigate, or on v7 it would clobber it and never reach /other.
- await userEvent.click(screen.getByText("act"));
-
- 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",
- });
-
- 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"));
-
- expect(screen.getByTestId("other")).toBeInTheDocument();
- expect(screen.getByTestId("location")).toHaveTextContent("/other");
- });
-});
diff --git a/frontend/src/metabase/router/types.ts b/frontend/src/metabase/router/types.ts
index 1ca58aef2a1..7f2ef39e67a 100644
--- a/frontend/src/metabase/router/types.ts
+++ b/frontend/src/metabase/router/types.ts
@@ -1,9 +1,4 @@
-import type {
- CSSProperties,
- ComponentClass,
- FunctionComponent,
- HTMLProps,
-} from "react";
+import type { ComponentClass, FunctionComponent } from "react";
import type { Location, Path } from "react-router";
export type {
@@ -81,14 +76,3 @@ export interface History {
* call sites that annotate the injected `route` / `routes` props.
*/
export type RouteComponent = ComponentClass<any> | FunctionComponent<any>;
-
-/**
- * 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;
- activeClassName?: string;
- activeStyle?: CSSProperties;
- onlyActiveOnIndex?: boolean;
-}