diff --git a/src/components/Asciidoc.svelte b/src/components/Asciidoc.svelte index dda68987f..707787bbb 100644 --- a/src/components/Asciidoc.svelte +++ b/src/components/Asciidoc.svelte @@ -4,16 +4,17 @@ import type { AsciidocSource } from "@app/lib/asciidoc"; import { renderAsciidoc } from "@app/lib/asciidoc"; import { enhanceCodeBlocks } from "@app/lib/codeBlocks"; + import type { OpenFile } from "@app/lib/documentLinks"; import { - enhanceRepoImages, - RepoImages, - resolveRepoPath, - } from "@app/lib/repoImages"; - import { scrollIntoView, twemoji } from "@app/lib/utils"; + enhanceDocumentLink, + scrollToLocationFragment, + } from "@app/lib/documentLinks"; + import { enhanceRepoImages, RepoImages } from "@app/lib/repoImages"; + import { twemoji } from "@app/lib/utils"; interface Props extends AsciidocSource { content: string; - onNavigate?: (path: string) => void; + onNavigate: OpenFile; } const { content, rid, sha, path, onNavigate }: Props = $props(); @@ -21,7 +22,7 @@ let container: HTMLElement | undefined = $state(); let html = $state(""); let error: string | undefined = $state(); - let scrolledToHash = false; + let scrolledAt: string | undefined; const images = new RepoImages(); @@ -62,33 +63,13 @@ function enhance(container: HTMLElement) { for (const anchor of container.querySelectorAll("a")) { - const href = anchor.getAttribute("href"); - if (!href || href.startsWith("#")) { - continue; - } - - // A link relative to the document is a path in the repository, not in - // the app. Following it would navigate the window away, so open the - // file in the source view instead. - const repoPath = resolveRepoPath(href, path); - if (repoPath) { - anchor.onclick = event => { - event.preventDefault(); - onNavigate?.(repoPath); - }; - } else { - anchor.target = "_blank"; - anchor.rel = "noopener noreferrer"; - } + enhanceDocumentLink(anchor, () => ({ path, openFile: onNavigate })); } enhanceRepoImages(container, { rid, sha, path }, images); enhanceCodeBlocks(container); - if (!scrolledToHash && window.location.hash) { - scrollIntoView(window.location.hash.substring(1)); - } - scrolledToHash = true; + scrolledAt = scrollToLocationFragment(scrolledAt); } diff --git a/src/components/Markdown.svelte b/src/components/Markdown.svelte index 6dd3bc15b..482e23f24 100644 --- a/src/components/Markdown.svelte +++ b/src/components/Markdown.svelte @@ -12,6 +12,11 @@ import { mount, tick, unmount } from "svelte"; import { enhanceCodeBlocks } from "@app/lib/codeBlocks"; + import type { OpenFile } from "@app/lib/documentLinks"; + import { + enhanceDocumentLink, + scrollToLocationFragment, + } from "@app/lib/documentLinks"; import { decodeEmbed, embedPreviewKind, retinaWidth } from "@app/lib/embeds"; import { parseFrontmatter } from "@app/lib/frontmatter"; import { invoke } from "@app/lib/invoke"; @@ -26,7 +31,8 @@ import { renderMermaidBlocks } from "@app/lib/mermaid"; import { isOid } from "@app/lib/radUri"; import { enhanceRepoImages, RepoImages } from "@app/lib/repoImages"; - import { scrollIntoView, twemoji } from "@app/lib/utils"; + import * as router from "@app/lib/router"; + import { twemoji } from "@app/lib/utils"; import Icon from "@app/components/Icon.svelte"; import Mention from "@app/components/Mention.svelte"; @@ -45,6 +51,9 @@ // If true, add
on a single line break breaks?: boolean; toggleTaskItem?: (content: string) => Promise | void; + // Opens a file linked from the document. By default it opens in the + // source view of the repository at its default branch. + onNavigate?: OpenFile; } const { @@ -54,11 +63,23 @@ sha = undefined, breaks = false, toggleTaskItem = undefined, + onNavigate = undefined, }: Props = $props(); + const openFile = $derived( + onNavigate ?? + (rid + ? (filePath: string | undefined, fragment: string | undefined) => + void router.push( + { resource: "repo.home", rid, path: filePath }, + fragment, + ) + : undefined), + ); + let taskInFlight = $state(false); let refocusTask: number | undefined = undefined; - let scrolledToHash = false; + let scrolledAt: string | undefined; let container: HTMLElement; @@ -337,15 +358,6 @@ continue; } - try { - const url = new URL(e.href); - if (url.origin !== window.origin) { - e.target = "_blank"; - e.rel = "noopener noreferrer"; - } - } catch (e) { - console.warn("Not able to parse url", e); - } // Don't underline tags that contain images. // Make an exception for emojis. if ( @@ -355,11 +367,11 @@ e.classList.add("no-underline"); } - // Iterate over all links, and try to add a base64 preview beneath it. const href = e.getAttribute("href"); - // If the markdown link is an oid embed - if (href && isOid(href)) { + if (!href || !isOid(href)) { + enhanceDocumentLink(e, () => ({ path, openFile })); + } else { e.onclick = event => { event.preventDefault(); invoke("save_embed_to_disk", { @@ -422,10 +434,7 @@ enhanceCodeBlocks(container); - if (!scrolledToHash && window.location.hash) { - scrollIntoView(window.location.hash.substring(1)); - } - scrolledToHash = true; + scrolledAt = scrollToLocationFragment(scrolledAt); }); return () => { diff --git a/src/lib/documentLinks.ts b/src/lib/documentLinks.ts new file mode 100644 index 000000000..cda5e5a43 --- /dev/null +++ b/src/lib/documentLinks.ts @@ -0,0 +1,115 @@ +import { show } from "@app/lib/modal"; +import { decodeComponent, resolveRepoTarget } from "@app/lib/repoImages"; + +import UnopenableLink from "@app/modals/UnopenableLink.svelte"; + +export type DocumentLink = + | { type: "fragment"; id: string } + // A path in the repository, undefined for its root. + | { type: "file"; path: string | undefined; fragment?: string } + | { type: "external" } + | { type: "unsupported" }; + +export type OpenFile = ( + path: string | undefined, + fragment: string | undefined, +) => void; + +// The schemes the shell plugin hands to the operating system when an anchor +// with `target="_blank"` is clicked. +const externalScheme = /^(?:https?|mailto|tel):/i; +const scheme = /^[a-z][a-z\d+.-]*:/i; + +/** + * Classify a link in the document at `from`. Links without a scheme are + * paths in the repository, as they are on code forges, so they never point + * at a page of the app. + */ +export function classifyDocumentLink(href: string, from: string): DocumentLink { + if (href === "" || href.startsWith("#")) { + return { type: "fragment", id: decodeComponent(href.slice(1)) }; + } + + if (scheme.test(href)) { + return externalScheme.test(href) + ? { type: "external" } + : { type: "unsupported" }; + } + + const target = resolveRepoTarget(href, from); + if (!target) { + return { type: "unsupported" }; + } + + const path = target.path.replace(/\/+$/, ""); + if (path === from && target.fragment !== undefined) { + return { type: "fragment", id: target.fragment }; + } + + return { type: "file", path: path || undefined, fragment: target.fragment }; +} + +// Markdown headings get lowercase ids, so a link written with the heading's +// own casing falls back to the lowercase id. +export function scrollToFragment(id: string) { + const target = + document.getElementById(id) ?? + document.getElementsByName(id)[0] ?? + document.getElementById(id.toLowerCase()); + target?.scrollIntoView(); +} + +// Scrolls once per location, so that re-rendering a document doesn't scroll +// it back. +export function scrollToLocationFragment( + scrolledAt: string | undefined, +): string { + const { href, hash } = window.location; + if (hash && href !== scrolledAt) { + scrollToFragment(decodeComponent(hash.slice(1))); + } + return href; +} + +export interface DocumentLinkOptions { + path: string; + openFile?: OpenFile; +} + +/** + * Make a link in a rendered document work inside the app. Following any link + * that isn't external would otherwise load another page into the window and + * restart the app. The document's options are read when the link is + * followed, as the same markup can be shown for another file. + */ +export function enhanceDocumentLink( + anchor: HTMLAnchorElement, + options: () => DocumentLinkOptions, +) { + const href = anchor.getAttribute("href"); + if (href === null) { + return; + } + + if (classifyDocumentLink(href, "").type === "external") { + anchor.target = "_blank"; + anchor.rel = "noopener noreferrer"; + return; + } + + anchor.onclick = event => { + event.preventDefault(); + const { path, openFile } = options(); + const link = classifyDocumentLink(href, path); + if (link.type === "fragment") { + scrollToFragment(link.id); + } else if (link.type === "file" && openFile) { + openFile(link.path, link.fragment); + } else { + show({ + component: UnopenableLink, + props: { link: href, reason: "unsupported" }, + }); + } + }; +} diff --git a/src/lib/markdown.ts b/src/lib/markdown.ts index 1df5e1a7b..b9bd5ec4a 100644 --- a/src/lib/markdown.ts +++ b/src/lib/markdown.ts @@ -222,9 +222,7 @@ export class Renderer extends BaseRenderer { link({ href, title, tokens }: Tokens.Link): string { const text = this.parser.parseInline(tokens); - const normalizedHref = href.startsWith("#") ? href.toLowerCase() : href; - - const attrs = [`href="${escape(normalizedHref)}"`]; + const attrs = [`href="${escape(href)}"`]; if (title) { attrs.push(`title="${escape(title)}"`); } diff --git a/src/lib/repoImages.ts b/src/lib/repoImages.ts index 9cc8507c2..79740bb6b 100644 --- a/src/lib/repoImages.ts +++ b/src/lib/repoImages.ts @@ -6,15 +6,25 @@ import { invoke } from "@app/lib/invoke"; // is never requested. const repoOrigin = "https://repo.radicle.invalid"; +export function decodeComponent(component: string): string { + try { + return decodeURIComponent(component); + } catch { + // A `%` that doesn't start an escape is part of the name. + return component; + } +} + /** * Resolve a link written relative to the document at `from` into a repository - * path. Returns undefined when the link points to another origin or to the - * repository root. Targets that climb above the root stop at it. + * path, which is empty for the repository root, and the fragment it points + * to. Returns undefined when the link points to another origin. Targets that + * climb above the root stop at it. */ -export function resolveRepoPath( +export function resolveRepoTarget( href: string, from: string, -): string | undefined { +): { path: string; fragment: string | undefined } | undefined { const dir = from.split("/").slice(0, -1).join("/"); let url: URL; @@ -30,14 +40,17 @@ export function resolveRepoPath( return undefined; } - let path = url.pathname; - try { - path = decodeURIComponent(path); - } catch { - // A `%` that doesn't start an escape is part of the file name. - } + return { + path: decodeComponent(url.pathname).replace(/^\//, ""), + fragment: url.hash ? decodeComponent(url.hash.slice(1)) : undefined, + }; +} - return path.replace(/^\//, "") || undefined; +export function resolveRepoPath( + href: string, + from: string, +): string | undefined { + return resolveRepoTarget(href, from)?.path || undefined; } // Rewrite GitHub "blob" image URLs so they resolve to the raw image content. A diff --git a/src/lib/router.ts b/src/lib/router.ts index 11f15c456..b3c35d5c6 100644 --- a/src/lib/router.ts +++ b/src/lib/router.ts @@ -98,6 +98,11 @@ const offPopstate = on(window, "popstate", () => { }); const offNavigateAnchor = on(document, "click", e => { + // A link that handled its own click, like one in a rendered document, + // must not be followed as a route as well. + if (e.defaultPrevented) { + return; + } const [anchor] = e .composedPath() .flatMap(target => (target instanceof HTMLAnchorElement ? [target] : [])); @@ -122,6 +127,7 @@ const loadExecutor = mutexExecutor.create(); async function navigate( action: "push" | "replace", newRoute: Route, + fragment?: string, ): Promise { const historyNav = pendingHistoryNavigation; pendingHistoryNavigation = false; @@ -136,7 +142,11 @@ async function navigate( // Pushing the route that is already active would mint a duplicate // history entry, making Back appear to do nothing. Booting has no path. const index = historyIndex() + 1; - window.history.pushState(stamp(newRoute, index), "", path); + window.history.pushState( + stamp(newRoute, index), + "", + fragment ? `${path}#${encodeURIComponent(fragment)}` : path, + ); updateNavigationState(index, true); } else if (action === "replace") { const index = historyIndex(); @@ -168,8 +178,8 @@ async function navigate( }); } -export async function push(newRoute: Route): Promise { - await navigate("push", newRoute); +export async function push(newRoute: Route, fragment?: string): Promise { + await navigate("push", newRoute, fragment); } export async function replace(newRoute: Route): Promise { diff --git a/src/modals/UnopenableLink.svelte b/src/modals/UnopenableLink.svelte index 0ab34364d..f92190a6c 100644 --- a/src/modals/UnopenableLink.svelte +++ b/src/modals/UnopenableLink.svelte @@ -5,7 +5,7 @@ interface Props { link: string; - reason: "invalid" | "no-page"; + reason: "invalid" | "no-page" | "unsupported"; } const { link, reason }: Props = $props(); @@ -62,6 +62,8 @@ {#if reason === "invalid"} This isn't a valid rad: link. + {:else if reason === "unsupported"} + The app doesn't know how to open this link. {:else} Neither this app nor the explorer has a page for this link. {/if} diff --git a/src/views/repo/RepoHome.svelte b/src/views/repo/RepoHome.svelte index a8b8f90a0..ac41a8fac 100644 --- a/src/views/repo/RepoHome.svelte +++ b/src/views/repo/RepoHome.svelte @@ -86,8 +86,8 @@ } }); - function showPath(filePath: string) { - void router.push({ ...baseRoute, path: filePath }); + function showPath(filePath: string | undefined, fragment?: string) { + void router.push({ ...baseRoute, path: filePath }, fragment); } function isMarkdownPath(path: string): boolean { @@ -112,9 +112,10 @@ currentPath = path; error = undefined; } catch (err) { - if (err instanceof InvokeError) { - error = err; - } + error = + err instanceof InvokeError + ? err + : new InvokeError(err instanceof Error ? err.message : String(err)); currentPath = path; } return; @@ -232,7 +233,7 @@
- {#if blob === null} + {#if blob === null && !error}
- {#if blob} + {#if blob && !error}
{/if} {/snippet}
- {#if showLineNumbers} + {#if blob && showLineNumbers} {#each blob.content .trimEnd() .split("\n") @@ -301,7 +302,17 @@ {/if}
- {#if blob.binary} + {#if error || !blob} +
+ + {#if error?.code === "PayloadError.TooLarge"} + File size exceeds limit of 10 MB. + {:else} + {capitalize(error?.message)} + {/if} +
+ {:else if blob.binary} {#if blob.mimeType.startsWith("image")} + content={blob.content} + onNavigate={showPath} /> {/if}
{:else if blob.content.trim() === ""} @@ -334,16 +346,6 @@ class="txt-body-m-regular blob-placeholder txt-missing"> Empty file
- {:else if error} -
- - {#if error.code === "PayloadError.TooLarge"} - File size exceeds limit of 10 MB. - {:else} - {capitalize(error.message)} - {/if} -
{:else}
 `Filler line ${i}.\n`),
+      "## Bottom",
+      "",
+      "The end.",
+      "",
+    ].join("\n"),
+  );
+  await Fs.writeFile(
+    Path.join(repoFolder, "docs", "guide.md"),
+    [
+      "# Guide",
+      "",
+      "Guide body.",
+      "",
+      "[Back to the readme](../README.md)",
+      "",
+      "[Repository root](/)",
+      "",
+      "[Spec](spec.adoc)",
+      "",
+      ...Array.from({ length: 200 }, (_, i) => `Guide filler ${i}.\n`),
+      "## Details",
+      "",
+      "The details.",
+      "",
+    ].join("\n"),
+  );
+  await Fs.writeFile(
+    Path.join(repoFolder, "docs", "spec.adoc"),
+    [
+      "= Spec",
+      "",
+      "Spec body.",
+      "",
+      "link:/README.md[Rooted readme]",
+      "",
+      "link:ftp://example.invalid/file[Odd scheme]",
+      "",
+    ].join("\n"),
+  );
+  await peer.git(["add", "."], { cwd: repoFolder });
+  await peer.git(["commit", "-m", "Link the docs"], { cwd: repoFolder });
+  await peer.git(["push", "rad", "main"], { cwd: repoFolder });
+  return { rid, repoFolder };
+}
+
+// Following a link the app doesn't handle loads another page into the window,
+// which restarts the app and drops this marker.
+async function markWindow(page: Page) {
+  await page.evaluate(() => {
+    (window as unknown as { linkMarker?: boolean }).linkMarker = true;
+  });
+}
+
+async function expectSameWindow(page: Page) {
+  expect(
+    await page.evaluate(
+      () => (window as unknown as { linkMarker?: boolean }).linkMarker,
+    ),
+  ).toBe(true);
+}
+
+test("follow relative links between Markdown files", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+  await markWindow(page);
+
+  const doc = page.locator(".markdown");
+  await doc.getByRole("link", { name: "Relative guide" }).click();
+  await expect(doc.getByText("Guide body.")).toBeVisible();
+  await expect(page).toHaveURL(/\?path=docs(%2F|\/)guide\.md/);
+
+  await doc.getByRole("link", { name: "Back to the readme" }).click();
+  await expect(doc.getByText("The end.")).toBeVisible();
+  await expect(page).toHaveURL(/\?path=README\.md/);
+
+  await page.goBack();
+  await expect(doc.getByText("Guide body.")).toBeVisible();
+  await expectSameWindow(page);
+});
+
+test("follow links rooted at the repository", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+  await markWindow(page);
+
+  const doc = page.locator(".markdown");
+  await doc.getByRole("link", { name: "Rooted guide" }).click();
+  await expect(doc.getByText("Guide body.")).toBeVisible();
+
+  await doc.getByRole("link", { name: "Repository root" }).click();
+  await expect(doc.getByText("The end.")).toBeVisible();
+  await expect(page).toHaveURL(new RegExp(`/repos/${rid}/home$`));
+  await expectSameWindow(page);
+});
+
+test("show that a linked file is missing", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+  await markWindow(page);
+
+  await page
+    .locator(".markdown")
+    .getByRole("link", { name: "Missing file" })
+    .click();
+  await expect(page).toHaveURL(/\?path=docs(%2F|\/)missing\.md/);
+  await expect(page.getByText(/does not exist/)).toBeVisible();
+  // The readme the link was followed from isn't shown as the missing file.
+  await expect(page.locator(".markdown")).toHaveCount(0);
+  await expectSameWindow(page);
+});
+
+test("show a missing file in a repository without a readme", async ({
+  page,
+  peer,
+}) => {
+  const { rid, repoFolder } = await createRepo(peer, { name: "empty" });
+  const issueId = await issue.create(
+    peer,
+    "Write the docs",
+    "Start with the [guide](docs/guide.md).",
+    [],
+    { cwd: repoFolder },
+  );
+  await page.goto(`/repos/${rid}/issues/${issueId}`);
+
+  await page
+    .locator(".markdown")
+    .getByRole("link", { name: "guide", exact: true })
+    .click();
+  await expect(page).toHaveURL(/\?path=docs(%2F|\/)guide\.md/);
+  await expect(page.getByText(/does not exist/)).toBeVisible();
+  await expect(page.getByText("No README.md")).toBeHidden();
+});
+
+test("explain a link the app can't open", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+  await markWindow(page);
+  const url = page.url();
+
+  await page
+    .locator(".markdown")
+    .getByRole("link", { name: "Odd scheme" })
+    .click();
+  await expect(page.getByText("Can't open link")).toBeVisible();
+  await expect(page.getByText("ftp://example.invalid/file")).toBeVisible();
+  expect(page.url()).toBe(url);
+  await expectSameWindow(page);
+});
+
+test("open external links outside the app", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+
+  await expect(
+    page.locator(".markdown").getByRole("link", { name: "Website" }),
+  ).toHaveAttribute("target", "_blank");
+});
+
+test("scroll to a heading in the same document", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+  await markWindow(page);
+  const url = page.url();
+
+  const doc = page.locator(".markdown");
+  const heading = doc.getByRole("heading", { name: "Bottom" });
+  await expect(heading).not.toBeInViewport();
+
+  await doc.getByRole("link", { name: "Down below", exact: true }).click();
+  await expect(heading).toBeInViewport();
+  expect(page.url()).toBe(url);
+  await expectSameWindow(page);
+
+  await reload(page);
+  await markWindow(page);
+  await expect(heading).not.toBeInViewport();
+  await doc.getByRole("link", { name: "Down below, by file" }).click();
+  await expect(heading).toBeInViewport();
+  expect(page.url()).toBe(url);
+  await expectSameWindow(page);
+});
+
+test("open a file at the section a link points to", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+  await markWindow(page);
+
+  const doc = page.locator(".markdown");
+  await doc.getByRole("link", { name: "Guide details" }).click();
+  const heading = doc.getByRole("heading", { name: "Details" });
+  await expect(heading).toBeInViewport();
+  await expect(page).toHaveURL(/\?path=docs(%2F|\/)guide\.md#Details$/);
+
+  await page.goBack();
+  await expect(doc.getByText("The end.")).toBeVisible();
+  await page.goForward();
+  await expect(heading).toBeInViewport();
+  await expectSameWindow(page);
+});
+
+test("follow links from AsciiDoc to Markdown", async ({ page, peer }) => {
+  const { rid } = await createLinkedRepo(peer);
+  await page.goto(`/repos/${rid}/home`);
+  await markWindow(page);
+
+  const doc = page.locator(".markdown");
+  await doc.getByRole("link", { name: "Relative guide" }).click();
+  await doc.getByRole("link", { name: "Spec" }).click();
+  await expect(page.locator(".asciidoc").getByText("Spec body.")).toBeVisible();
+
+  await page
+    .locator(".asciidoc")
+    .getByRole("link", { name: "Rooted readme" })
+    .click();
+  await expect(page.locator(".markdown").getByText("The end.")).toBeVisible();
+  await expect(page).toHaveURL(new RegExp(`/repos/${rid}/home`));
+
+  await page.goBack();
+  await page
+    .locator(".asciidoc")
+    .getByRole("link", { name: "Odd scheme" })
+    .click();
+  await expect(page.getByText("Can't open link")).toBeVisible();
+  await expectSameWindow(page);
+});
+
+test("open a file linked from an issue", async ({ page, peer }) => {
+  const { rid, repoFolder } = await createLinkedRepo(peer);
+  const issueId = await issue.create(
+    peer,
+    "Improve the docs",
+    "The [guide](docs/guide.md) needs a section on links, next to its [details](docs/guide.md#details).",
+    [],
+    { cwd: repoFolder },
+  );
+  await page.goto(`/repos/${rid}/issues/${issueId}`);
+  await markWindow(page);
+
+  await page
+    .locator(".markdown")
+    .getByRole("link", { name: "guide", exact: true })
+    .click();
+  await expect(
+    page.locator(".markdown").getByText("Guide body."),
+  ).toBeVisible();
+  await expect(page).toHaveURL(/\?path=docs(%2F|\/)guide\.md/);
+  await expectSameWindow(page);
+
+  await page.goBack();
+  await page
+    .locator(".markdown")
+    .getByRole("link", { name: "details", exact: true })
+    .click();
+  await expect(
+    page.locator(".markdown").getByRole("heading", { name: "Details" }),
+  ).toBeInViewport();
+  await expectSameWindow(page);
+});
diff --git a/tests/unit/documentLinks.test.ts b/tests/unit/documentLinks.test.ts
new file mode 100644
index 000000000..f3bfad878
--- /dev/null
+++ b/tests/unit/documentLinks.test.ts
@@ -0,0 +1,251 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import type { DocumentLink } from "@app/lib/documentLinks";
+import {
+  classifyDocumentLink,
+  enhanceDocumentLink,
+  scrollToFragment,
+  scrollToLocationFragment,
+} from "@app/lib/documentLinks";
+
+const { show } = vi.hoisted(() => ({ show: vi.fn() }));
+vi.mock("@app/lib/modal", () => ({ show }));
+
+describe("classifyDocumentLink", () => {
+  test.each<[string, string, DocumentLink]>([
+    ["docs/guide.md", "README.md", { type: "file", path: "docs/guide.md" }],
+    ["./guide.md", "docs/index.md", { type: "file", path: "docs/guide.md" }],
+    ["../README.md", "docs/index.md", { type: "file", path: "README.md" }],
+    ["/src/main.rs", "docs/index.md", { type: "file", path: "src/main.rs" }],
+    ["docs/", "README.md", { type: "file", path: "docs" }],
+    [
+      "docs/guide.md#usage",
+      "README.md",
+      { type: "file", path: "docs/guide.md", fragment: "usage" },
+    ],
+    [
+      "guide.md#caf%C3%A9",
+      "README.md",
+      { type: "file", path: "guide.md", fragment: "café" },
+    ],
+    ["guide.md?plain=1", "README.md", { type: "file", path: "guide.md" }],
+    ["my%20notes.md", "README.md", { type: "file", path: "my notes.md" }],
+    ["LICENSE", "", { type: "file", path: "LICENSE" }],
+    ["/", "docs/index.md", { type: "file", path: undefined }],
+    ["..", "README.md", { type: "file", path: undefined }],
+    ["#usage", "README.md", { type: "fragment", id: "usage" }],
+    ["#caf%C3%A9", "README.md", { type: "fragment", id: "café" }],
+    ["README.md#usage", "README.md", { type: "fragment", id: "usage" }],
+    ["README.md#Usage", "README.md", { type: "fragment", id: "Usage" }],
+    ["#caf%", "README.md", { type: "fragment", id: "caf%" }],
+    ["#", "README.md", { type: "fragment", id: "" }],
+    ["", "README.md", { type: "fragment", id: "" }],
+    ["https://radicle.xyz", "README.md", { type: "external" }],
+    ["HTTP://radicle.xyz", "README.md", { type: "external" }],
+    ["mailto:alice@example.com", "README.md", { type: "external" }],
+    ["tel:+123", "README.md", { type: "external" }],
+    ["ftp://example.com/file", "README.md", { type: "unsupported" }],
+    ["javascript:alert(1)", "README.md", { type: "unsupported" }],
+    ["//radicle.xyz/notes.md", "README.md", { type: "unsupported" }],
+  ])("classifies %j in %j", (href, from, expected) => {
+    expect(classifyDocumentLink(href, from)).toEqual(expected);
+  });
+});
+
+describe("enhanceDocumentLink", () => {
+  let container: HTMLElement;
+
+  function link(href: string | undefined): HTMLAnchorElement {
+    const anchor = document.createElement("a");
+    if (href !== undefined) {
+      anchor.setAttribute("href", href);
+    }
+    anchor.textContent = "link";
+    container.appendChild(anchor);
+    return anchor;
+  }
+
+  function click(anchor: HTMLAnchorElement): MouseEvent {
+    const event = new MouseEvent("click", { bubbles: true, cancelable: true });
+    anchor.dispatchEvent(event);
+    return event;
+  }
+
+  beforeEach(() => {
+    container = document.createElement("div");
+    document.body.appendChild(container);
+  });
+
+  afterEach(() => {
+    container.remove();
+    vi.restoreAllMocks();
+    show.mockReset();
+  });
+
+  test("opens a file in the repository instead of following the link", () => {
+    const openFile = vi.fn();
+    const anchor = link("../CONTRIBUTING.md");
+    enhanceDocumentLink(anchor, () => ({ path: "docs/index.md", openFile }));
+
+    expect(click(anchor).defaultPrevented).toBe(true);
+    expect(openFile).toHaveBeenCalledWith("CONTRIBUTING.md", undefined);
+    expect(show).not.toHaveBeenCalled();
+  });
+
+  test("opens the repository root", () => {
+    const openFile = vi.fn();
+    const anchor = link("/");
+    enhanceDocumentLink(anchor, () => ({ path: "docs/index.md", openFile }));
+
+    expect(click(anchor).defaultPrevented).toBe(true);
+    expect(openFile).toHaveBeenCalledWith(undefined, undefined);
+  });
+
+  test("resolves against the document shown when the link is followed", () => {
+    const openFile = vi.fn();
+    let path = "README.md";
+    const anchor = link("guide.md");
+    enhanceDocumentLink(anchor, () => ({ path, openFile }));
+
+    path = "docs/README.md";
+    click(anchor);
+    expect(openFile).toHaveBeenCalledWith("docs/guide.md", undefined);
+  });
+
+  test("opens a file at the section it links to", () => {
+    const openFile = vi.fn();
+    const anchor = link("guide.md#Usage");
+    enhanceDocumentLink(anchor, () => ({ path: "README.md", openFile }));
+
+    click(anchor);
+    expect(openFile).toHaveBeenCalledWith("guide.md", "Usage");
+  });
+
+  test("opens external links outside the app", () => {
+    const anchor = link("https://radicle.xyz");
+    enhanceDocumentLink(anchor, () => ({ path: "README.md" }));
+
+    expect(anchor.target).toBe("_blank");
+    expect(anchor.rel).toBe("noopener noreferrer");
+    expect(anchor.onclick).toBeNull();
+  });
+
+  test("scrolls to a fragment in the document", () => {
+    const heading = document.createElement("h2");
+    heading.id = "usage";
+    container.appendChild(heading);
+    const scroll = vi
+      .spyOn(heading, "scrollIntoView")
+      .mockReturnValue(undefined);
+    const anchor = link("#usage");
+    enhanceDocumentLink(anchor, () => ({ path: "README.md" }));
+
+    expect(click(anchor).defaultPrevented).toBe(true);
+    expect(scroll).toHaveBeenCalled();
+  });
+
+  test("scrolls to a named anchor", () => {
+    const target = document.createElement("a");
+    target.setAttribute("name", "legacy");
+    container.appendChild(target);
+    const scroll = vi
+      .spyOn(target, "scrollIntoView")
+      .mockReturnValue(undefined);
+    const anchor = link("#legacy");
+    enhanceDocumentLink(anchor, () => ({ path: "README.md" }));
+
+    click(anchor);
+    expect(scroll).toHaveBeenCalled();
+  });
+
+  test("stays put for a missing fragment", () => {
+    const anchor = link("#missing");
+    enhanceDocumentLink(anchor, () => ({ path: "README.md" }));
+
+    expect(click(anchor).defaultPrevented).toBe(true);
+    expect(show).not.toHaveBeenCalled();
+  });
+
+  test.each([
+    ["ftp://example.com/file", true],
+    ["//radicle.xyz/notes.md", true],
+    // A document that isn't part of a repository has no files to open.
+    ["guide.md", false],
+  ])("explains why %j can't be opened", (href, inRepo) => {
+    const openFile = vi.fn();
+    const anchor = link(href);
+    enhanceDocumentLink(anchor, () => ({
+      path: "README.md",
+      openFile: inRepo ? openFile : undefined,
+    }));
+
+    expect(click(anchor).defaultPrevented).toBe(true);
+    expect(openFile).not.toHaveBeenCalled();
+    expect(show).toHaveBeenCalledWith(
+      expect.objectContaining({
+        props: { link: href, reason: "unsupported" },
+      }),
+    );
+  });
+
+  test("leaves anchors without a link alone", () => {
+    const anchor = link(undefined);
+    enhanceDocumentLink(anchor, () => ({ path: "README.md" }));
+
+    expect(anchor.onclick).toBeNull();
+    expect(anchor.target).toBe("");
+  });
+});
+
+describe("scrollToFragment", () => {
+  let container: HTMLElement;
+
+  function target(tag: string, attribute: string, value: string) {
+    const element = document.createElement(tag);
+    element.setAttribute(attribute, value);
+    container.appendChild(element);
+    return vi.spyOn(element, "scrollIntoView").mockReturnValue(undefined);
+  }
+
+  beforeEach(() => {
+    container = document.createElement("div");
+    document.body.appendChild(container);
+  });
+
+  afterEach(() => {
+    container.remove();
+    vi.restoreAllMocks();
+    window.history.replaceState(null, "", "/");
+  });
+
+  test("falls back to the lowercase id of a heading", () => {
+    const heading = target("h2", "id", "usage");
+
+    scrollToFragment("Usage");
+    expect(heading).toHaveBeenCalled();
+  });
+
+  test("prefers an exact match over the lowercase id", () => {
+    const heading = target("h2", "id", "usage");
+    const anchor = target("a", "name", "Usage");
+
+    scrollToFragment("Usage");
+    expect(anchor).toHaveBeenCalled();
+    expect(heading).not.toHaveBeenCalled();
+  });
+
+  test("scrolls to the location's fragment once per location", () => {
+    const heading = target("h2", "id", "café");
+    window.history.replaceState(null, "", "/repos#caf%C3%A9");
+
+    const scrolledAt = scrollToLocationFragment(undefined);
+    expect(heading).toHaveBeenCalledTimes(1);
+
+    scrollToLocationFragment(scrolledAt);
+    expect(heading).toHaveBeenCalledTimes(1);
+
+    window.history.replaceState(null, "", "/other#caf%C3%A9");
+    scrollToLocationFragment(scrolledAt);
+    expect(heading).toHaveBeenCalledTimes(2);
+  });
+});
diff --git a/tests/unit/router.test.ts b/tests/unit/router.test.ts
index 7c37aa804..608e98bcd 100644
--- a/tests/unit/router.test.ts
+++ b/tests/unit/router.test.ts
@@ -5,6 +5,7 @@ import type { Route } from "@app/lib/router";
 import {
   activeUnloadedRouteStore,
   loadFromLocation,
+  push,
   routeToPath,
 } from "@app/lib/router";
 
@@ -100,3 +101,48 @@ test.each([
     expect.stringContaining("Could not resolve route"),
   );
 });
+
+describe("clicks on app links", () => {
+  function clickLink(href: string, handle?: (event: Event) => void) {
+    const anchor = document.createElement("a");
+    anchor.setAttribute("href", href);
+    if (handle) {
+      anchor.addEventListener("click", handle);
+    }
+    document.body.appendChild(anchor);
+    anchor.click();
+    anchor.remove();
+  }
+
+  test("navigate to the route", async () => {
+    await resolve("/guide");
+
+    clickLink("/inbox");
+    await vi.waitFor(() =>
+      expect(get(activeUnloadedRouteStore)).toEqual({ resource: "inbox" }),
+    );
+  });
+
+  test("leave links that handled their own click alone", async () => {
+    await resolve("/guide");
+
+    clickLink("/inbox", event => event.preventDefault());
+    expect(get(activeUnloadedRouteStore)).toEqual({ resource: "guide" });
+    expect(window.location.pathname).toBe("/guide");
+  });
+});
+
+test("push a route with a fragment to scroll to", async () => {
+  await resolve("/guide");
+
+  await push({ resource: "repo.home", rid, path: "docs/guide.md" }, "café");
+  expect(get(activeUnloadedRouteStore)).toEqual({
+    resource: "repo.home",
+    rid,
+    path: "docs/guide.md",
+  });
+  expect(decodeURIComponent(window.location.hash)).toBe("#café");
+
+  await push({ resource: "guide" });
+  expect(window.location.hash).toBe("");
+});