Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 0 additions & 78 deletions coral/src/app/components/InternalLinkButton.test.tsx

This file was deleted.

39 changes: 0 additions & 39 deletions coral/src/app/components/InternalLinkButton.tsx

This file was deleted.

157 changes: 157 additions & 0 deletions coral/src/app/components/Link.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { cleanup, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useLocation } from "react-router-dom";
import { Link } from "src/app/components/Link";
import { customRender } from "src/services/test-utils/render-with-wrappers";
import { mockIntersectionObserver } from "src/services/test-utils/mock-intersection-observer";

const testTo = "/test/url";
const testText = "My nice link";

function LocationDisplay() {
const location = useLocation();
return <div data-testid="location">{location.pathname}</div>;
}

describe("Link.Button", () => {
mockIntersectionObserver();

afterEach(cleanup);

it("renders a link and resolves `to` into the href attribute", () => {
customRender(<Link.Button to={testTo}>{testText}</Link.Button>, {
memoryRouter: true,
customRoutePath: "/start",
});

const link = screen.getByRole("link", { name: testText });
expect(link).toBeVisible();
expect(link).toHaveAttribute("href", testTo);
});

it("navigates client-side via react-router when `to` is used", async () => {
const user = userEvent.setup();
customRender(
<>
<Link.Button to={testTo}>{testText}</Link.Button>
<LocationDisplay />
</>,
{ memoryRouter: true, customRoutePath: "/start" }
);

expect(screen.getByTestId("location")).toHaveTextContent("/start");
await user.click(screen.getByRole("link", { name: testText }));
expect(screen.getByTestId("location")).toHaveTextContent(testTo);
});

it("does not intercept clicks when only `href` is given (plain DS behavior)", async () => {
const user = userEvent.setup();
// jsdom cannot perform real navigations and logs "Not implemented" on click
const consoleError = jest
.spyOn(console, "error")
.mockImplementation(() => {});
let defaultPrevented: boolean | undefined;
customRender(
<>
<Link.Button
href="#docs"
onClick={(event) => {
defaultPrevented = event.defaultPrevented;
}}
>
{testText}
</Link.Button>
<LocationDisplay />
</>,
{ memoryRouter: true, customRoutePath: "/start" }
);

const link = screen.getByRole("link", { name: testText });
// useHref resolves the hash against the current route
expect(link).toHaveAttribute("href", "/start#docs");
await user.click(link);
// native navigation was NOT prevented -> no client-side routing for plain href
expect(defaultPrevented).toBe(false);
expect(screen.getByTestId("location")).toHaveTextContent("/start");
consoleError.mockRestore();
});

it("calls a passed onClick handler and still router-navigates with `to`", async () => {
const user = userEvent.setup();
const onClick = jest.fn();
customRender(
<>
<Link.Button to={testTo} onClick={onClick}>
{testText}
</Link.Button>
<LocationDisplay />
</>,
{ memoryRouter: true, customRoutePath: "/start" }
);

await user.click(screen.getByRole("link", { name: testText }));
expect(onClick).toHaveBeenCalledTimes(1);
expect(screen.getByTestId("location")).toHaveTextContent(testTo);
});

it("does not router-navigate when onClick called preventDefault", async () => {
const user = userEvent.setup();
customRender(
<>
<Link.Button to={testTo} onClick={(event) => event.preventDefault()}>
{testText}
</Link.Button>
<LocationDisplay />
</>,
{ memoryRouter: true, customRoutePath: "/start" }
);

await user.click(screen.getByRole("link", { name: testText }));
expect(screen.getByTestId("location")).toHaveTextContent("/start");
});

it("renders a disabled link button without href", () => {
customRender(
<Link.Button to={testTo} disabled={true}>
{testText}
</Link.Button>,
{ memoryRouter: true, customRoutePath: "/start" }
);

const link = screen.getByRole("link", { name: testText });
expect(link).toBeDisabled();
expect(link).not.toHaveAttribute("href");
expect(link).toHaveAttribute("aria-disabled", "true");
});

it("passes kind through to the DS button styling", () => {
customRender(
<Link.Button to={testTo} kind={"secondary"}>
{testText}
</Link.Button>,
{ memoryRouter: true, customRoutePath: "/start" }
);

expect(screen.getByRole("link", { name: testText })).toBeVisible();
});
});

describe("Link", () => {
mockIntersectionObserver();

afterEach(cleanup);

it("navigates client-side when `to` is used", async () => {
const user = userEvent.setup();
customRender(
<>
<Link to={testTo}>{testText}</Link>
<LocationDisplay />
</>,
{ memoryRouter: true, customRoutePath: "/start" }
);

await user.click(screen.getByRole("link", { name: testText }));
expect(screen.getByTestId("location")).toHaveTextContent(testTo);
});
});
97 changes: 97 additions & 0 deletions coral/src/app/components/Link.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import {
Button,
Link as DsLink,
type ButtonProps,
type LinkProps as DsLinkProps,
} from "@aivenio/aquarium";
import type { ComponentType, MouseEvent, ReactNode } from "react";
import { useHref, useLinkClickHandler, type To } from "react-router-dom";

type Either<A, B> =
| (A & { [K in keyof B]?: never })
| (B & { [K in keyof A]?: never });

// `to` (with optional replace/state) makes the link router-aware
// `href` keeps the plain link behavior
type RouterLinkProps = { to: To; replace?: boolean; state?: unknown };
type HrefLinkProps = { href: string };

type LinkComponentProps<P> = Either<HrefLinkProps, RouterLinkProps> &
Omit<P, "href" | "onClick"> & {
onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;
children?: ReactNode;
};

/**
* Wraps the DS link component so it additionally
* accepts `to` for client-side navigation via react-router.
*
* TODO: expose the remaining DS variants (Link.Button.Ghost/.Primary/...)
* once we upgrade aquarium.
*/
function withRouterLink<P extends { href?: string }>(
Component: ComponentType<
P & { onClick?: (event: MouseEvent<HTMLAnchorElement>) => void }
>
): ComponentType<LinkComponentProps<P>> {
function RouterLink(props: LinkComponentProps<P>) {
const { onClick, ...rest } = props;
const hasTo = "to" in props;

const to = (hasTo ? props.to : props.href) as To;

const {
to: _to,
replace: _replace,
state: _state,
...componentProps
} = rest as typeof rest & RouterLinkProps;
const resolvedHref = useHref(to);
const handleRouterClick = useLinkClickHandler(to, {
replace: hasTo ? props.replace : undefined,
state: hasTo ? props.state : undefined,
});

return (
<Component
{...(componentProps as unknown as P)}
href={resolvedHref}
onClick={(event: MouseEvent<HTMLAnchorElement>) => {
onClick?.(event);
if (!event.defaultPrevented && hasTo) {
handleRouterClick(event);
}
}}
/>
);
}
return RouterLink as ComponentType<LinkComponentProps<P>>;
}

type LinkButtonProps = LinkComponentProps<
DsLinkProps & Pick<ButtonProps, "kind" | "dense"> & { disabled?: boolean }
>;

const RouterAwareLinkButton = withRouterLink(DsLink.Button);

// Link.Button: router-aware DS link button. A disabled link cannot be a real
// <a>, so we render a disabled button with role="link" for assistive technology.
const LinkButton = (props: LinkButtonProps) => {
if (props.disabled) {
return (
<Button
role={"link"}
aria-disabled={true}
disabled={true}
kind={props.kind}
>
{props.children}
</Button>
);
}
return <RouterAwareLinkButton {...props} />;
};

const Link = Object.assign(withRouterLink(DsLink), { Button: LinkButton });

export { Link };

This file was deleted.

Loading
Loading