- {#if blob === null}
+ {#if blob === null && !error}
- {#if blob}
+ {#if blob && !error}
`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("");
+});