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
82 changes: 82 additions & 0 deletions integration/link-download-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { readFile } from "node:fs/promises";
import { expect, test } from "@playwright/test";

import {
createAppFixture,
createFixture,
js,
} from "./helpers/create-fixture.js";
import { PlaywrightFixture } from "./helpers/playwright-fixture.js";

for (let templateName of ["vite-8-template", "rsc-vite-framework"] as const) {
test(`${templateName} leaves downloads to the browser and preserves custom navigation`, async ({
page,
}) => {
let contents = "id,name\n1,Example\n";
let fixture = await createFixture({
templateName,
files: {
"public/report.csv": contents,
"app/routes/_index.tsx": js`
"use client";

import { useEffect, useState } from "react";
import { Link, useLinkClickHandler } from "react-router";

export default function Index() {
let [hydrated, setHydrated] = useState(false);
let navigate = useLinkClickHandler<HTMLFormElement>("/next");
useEffect(() => setHydrated(true), []);

return (
<main data-hydrated={hydrated}>
<Link to="/report.csv" download>Download report</Link>
<Link to="/report.csv" download="custom.csv">Download renamed report</Link>
<form onClick={navigate}>
<input type="hidden" name="matches" />
<button type="button">Continue</button>
</form>
</main>
);
}
`,
"app/routes/next.tsx": js`
export default function Next() {
return <h1>Next page</h1>;
}
`,
},
});
let appFixture = await createAppFixture(fixture);

try {
let app = new PlaywrightFixture(appFixture, page);
await app.goto("/");
await expect(page.locator("main")).toHaveAttribute(
"data-hydrated",
"true",
);

for (let [label, filename] of [
["Download report", "report.csv"],
["Download renamed report", "custom.csv"],
]) {
let [download] = await Promise.all([
page.waitForEvent("download"),
page.getByRole("link", { name: label, exact: true }).click(),
]);

expect(download.suggestedFilename()).toBe(filename);
expect(await readFile(await download.path(), "utf8")).toBe(contents);
await expect(page).toHaveURL(new URL("/", appFixture.serverUrl).href);
}

await page.getByRole("button", { name: "Continue" }).click();
await expect(
page.getByRole("heading", { name: "Next page" }),
).toBeVisible();
} finally {
appFixture.close();
}
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Let the browser handle clicks on a `<Link download>` (and on custom links built with `useLinkClickHandler`) so the file is downloaded instead of being navigated to with client-side routing
76 changes: 76 additions & 0 deletions packages/react-router/__tests__/dom/link-click-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,82 @@ describe("A <Link> click", () => {
});
});

describe("when the link has a download attribute", () => {
it("lets the browser download the file", () => {
function Home() {
return (
<div>
<h1>Home</h1>
<Link to="../report.csv" download>
Report
</Link>
</div>
);
}

act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Home />} />
<Route path="*" element={<h1>Not Found</h1>} />
</Routes>
</MemoryRouter>,
);
});

let anchor = node.querySelector("a");
expect(anchor).not.toBeNull();

let event: MouseEvent;
act(() => {
event = click(anchor);
});

expect(event.defaultPrevented).toBe(false);
let h1 = node.querySelector("h1");
expect(h1).not.toBeNull();
expect(h1?.textContent).toEqual("Home");
});

it("navigates to the new page when download is false", () => {
function Home() {
return (
<div>
<h1>Home</h1>
<Link to="../about" download={false}>
About
</Link>
</div>
);
}

act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route path="home" element={<Home />} />
<Route path="about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>,
);
});

let anchor = node.querySelector("a");
expect(anchor).not.toBeNull();

let event: MouseEvent;
act(() => {
event = click(anchor);
});

expect(event.defaultPrevented).toBe(true);
let h1 = node.querySelector("h1");
expect(h1).not.toBeNull();
expect(h1?.textContent).toEqual("About");
});
});

describe("when the modifier keys are used", () => {
it("stays on the same page", () => {
function Home() {
Expand Down
101 changes: 101 additions & 0 deletions packages/react-router/__tests__/dom/useLinkClickHandler-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,107 @@ describe("Custom link with useLinkClickHandler", () => {
});
});

describe("when the link has a download attribute", () => {
it("leaves a click on a child of a named download link to the browser", () => {
act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter initialEntries={["/home"]}>
<Routes>
<Route
path="home"
element={
<div>
<h1>Home</h1>
<CustomLink to="../about" download="about.html">
<span>About</span>
</CustomLink>
</div>
}
/>
<Route path="about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>,
);
});

let label = node.querySelector("a span");
expect(label).not.toBeNull();

let event = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
});
act(() => {
label?.dispatchEvent(event);
});

expect(event.defaultPrevented).toBe(false);
let h1 = node.querySelector("h1");
expect(h1).not.toBeNull();
expect(h1?.textContent).toEqual("Home");
});
});

it("navigates when used on a button with a download attribute", () => {
function NavigationButton() {
let handleClick = useLinkClickHandler<HTMLButtonElement>("/about");
return (
<button {...{ download: "" }} onClick={handleClick}>
About
</button>
);
}

act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter>
<Routes>
<Route path="/" element={<NavigationButton />} />
<Route path="/about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>,
);
});

let button = node.querySelector("button");
expect(button).toHaveAttribute("download");
act(() => {
button?.click();
});

expect(node.querySelector("h1")).toHaveTextContent("About");
});

it("navigates when a download anchor has no href", () => {
act(() => {
ReactDOM.createRoot(node).render(
<MemoryRouter>
<Routes>
<Route
path="/"
element={
<CustomLink to="/about" download>
About
</CustomLink>
}
/>
<Route path="/about" element={<h1>About</h1>} />
</Routes>
</MemoryRouter>,
);
});

let anchor = node.querySelector("a");
expect(anchor).toHaveAttribute("download");
anchor?.removeAttribute("href");
act(() => {
anchor?.click();
});

expect(node.querySelector("h1")).toHaveTextContent("About");
});

describe("when the modifier keys are used", () => {
it("stays on the same page", () => {
act(() => {
Expand Down
10 changes: 8 additions & 2 deletions packages/react-router/lib/dom/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function isInputElement(object: any): object is HTMLInputElement {
type LimitedMouseEvent = Pick<
MouseEvent,
"button" | "metaKey" | "altKey" | "ctrlKey" | "shiftKey"
>;
> & { currentTarget: Element | null };

function isModifiedEvent(event: LimitedMouseEvent) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
Expand All @@ -35,10 +35,16 @@ export function shouldProcessLinkClick(
event: LimitedMouseEvent,
target?: string,
) {
let element = event.currentTarget;
return (
event.button === 0 && // Ignore everything but left clicks
(!target || target === "_self") && // Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
!isModifiedEvent(event) && // Ignore clicks with modifier keys
!(
(element?.localName === "a" || element?.localName === "area") &&
element.hasAttribute("href") &&
element.hasAttribute("download")
) // Let the browser handle download links
);
}

Expand Down