diff --git a/apps/docs/scripts/a11y-keyboard.mjs b/apps/docs/scripts/a11y-keyboard.mjs
index 1479820e..69bc1a1e 100644
--- a/apps/docs/scripts/a11y-keyboard.mjs
+++ b/apps/docs/scripts/a11y-keyboard.mjs
@@ -1,6 +1,6 @@
// Keyboard, focus and pointer checks axe cannot make: button cursors, the skip
-// link's Tab order and focus hand-off, and the version switcher's More contrast
-// outline in the mobile drawer, and inline code that fits its line. Runs in
+// link's Tab order and focus hand-off, the heading # links, the version switcher's More
+// contrast outline in the mobile drawer, and inline code that fits its line. Runs in
// Chromium and Firefox, at desktop and phone widths.
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -71,6 +71,128 @@ async function checkSkipLink(page, fail) {
if ((await articleTabindex(page)) !== null) fail("the article keeps its tabindex after blur");
}
+const HEADING = "#nd-page [data-heading]:has(> h2[id] + [data-heading-anchor])";
+const ANCHOR_TITLE = "Link to this section";
+
+// The last heading's # link: shown on focus and hover without moving the heading,
+// beside the heading and named after it; it and its TOC entry scroll smoothly unless motion is reduced.
+async function checkHeadingAnchor(page, browserName, fail) {
+ const wrapper = page.locator(HEADING).last();
+ if ((await page.locator(HEADING).count()) === 0) {
+ fail("no heading has a # link beside it");
+ return "no heading # link";
+ }
+ const heading = wrapper.locator(":scope > h2");
+ const anchor = wrapper.locator(":scope > [data-heading-anchor]");
+ const shown = () =>
+ anchor.evaluate(
+ (link) =>
+ new Promise((resolve) => {
+ const deadline = performance.now() + 2000;
+ const frame = () => {
+ const opacity = Number(getComputedStyle(link).opacity);
+ if (opacity === 1 || performance.now() > deadline) return resolve(opacity);
+ requestAnimationFrame(frame);
+ };
+ frame();
+ }),
+ );
+ const state = () =>
+ anchor.evaluate((link) => {
+ const box = link.parentElement.getBoundingClientRect();
+ return {
+ size: `${box.width}x${box.height}`,
+ title: link.title,
+ text: link.previousElementSibling.textContent,
+ links: link.previousElementSibling.querySelectorAll("a").length,
+ aria: [link.parentElement, ...link.parentElement.querySelectorAll("*")].flatMap((el) =>
+ [...el.attributes].filter((a) => a.name.startsWith("aria-")).map((a) => a.name),
+ ),
+ };
+ });
+ const idle = await state();
+ if (idle.links !== 0) fail(`the heading "${idle.text}" holds ${idle.links} links`);
+ if (idle.aria.length > 0) fail(`the heading and its # link carry ${idle.aria.join(", ")}`);
+ if (idle.title !== ANCHOR_TITLE)
+ fail(`the # link's tooltip is "${idle.title}", not "${ANCHOR_TITLE}"`);
+ const named = await wrapper.getByRole("link", { name: idle.text, exact: true }).count();
+ if (named !== 1) fail(`no # link is named "${idle.text}"`);
+ if (browserName === "chromium") {
+ // Playwright's own name computation misses a doubled heading name, so read Chromium's tree.
+ const cdp = await page.context().newCDPSession(page);
+ const { nodes } = await cdp.send("Accessibility.getFullAXTree");
+ await cdp.detach();
+ const text = (node) => node.name?.value ?? "";
+ const headings = nodes.filter((node) => node.role?.value === "heading");
+ if (!headings.some((node) => text(node) === idle.text))
+ fail(`no heading is named exactly "${idle.text}"`);
+ for (const node of nodes) {
+ if (
+ node.role?.value === "link" &&
+ text(node) === idle.text &&
+ node.description?.value === idle.text
+ )
+ fail(`a link named "${idle.text}" repeats it as its description`);
+ }
+ }
+
+ await anchor.focus();
+ const focusedOpacity = await shown();
+ if (focusedOpacity !== 1) fail(`the focused # link has opacity ${focusedOpacity}`);
+ await anchor.blur();
+ await heading.hover();
+ const hoveredOpacity = await shown();
+ const hovered = await state();
+ if (hoveredOpacity !== 1) fail(`the # link has opacity ${hoveredOpacity} on hover`);
+ if (hovered.size !== idle.size)
+ fail(`the heading resized on hover (${idle.size} to ${hovered.size})`);
+
+ const id = await heading.getAttribute("id");
+ const scrollAfterClick = async (link, motion) => {
+ await page.evaluate((value) => {
+ document.documentElement.setAttribute("data-motion", value);
+ history.replaceState(null, "", location.pathname);
+ window.scrollTo({ top: 0, behavior: "instant" });
+ }, motion);
+ await link.evaluate((element) => element.click());
+ const first = await page.evaluate(() => window.scrollY);
+ // Settled once the position holds for ten frames.
+ const last = await page.evaluate(
+ () =>
+ new Promise((resolve) => {
+ let y = window.scrollY;
+ let still = 0;
+ const frame = () => {
+ if (window.scrollY !== y) [y, still] = [window.scrollY, 0];
+ else if (++still >= 10) return resolve(y);
+ requestAnimationFrame(frame);
+ };
+ requestAnimationFrame(frame);
+ }),
+ );
+ return { first, last, hash: await page.evaluate(() => location.hash) };
+ };
+ const tocEntry = page.locator(`#nd-toc a[href="#${id}"]`);
+ if ((await tocEntry.count()) !== 1) fail(`the On this page list has no entry for #${id}`);
+ for (const [what, link] of [
+ ["the # link", anchor],
+ ["the On this page entry", tocEntry],
+ ]) {
+ if ((await link.count()) !== 1) continue;
+ const reduced = await scrollAfterClick(link, "reduced");
+ if (reduced.first !== reduced.last)
+ fail(`with reduced motion ${what} scrolled from ${reduced.first} instead of jumping`);
+ const full = await scrollAfterClick(link, "full");
+ if (full.first >= full.last)
+ fail(`with full motion ${what} jumped to ${full.last} instead of scrolling`);
+ for (const { hash } of [reduced, full]) {
+ if (hash !== `#${id}`) fail(`${what} left the address at "${hash}", not "#${id}"`);
+ }
+ }
+ await page.evaluate(() => document.documentElement.removeAttribute("data-motion"));
+ return `heading # link and TOC entry "${idle.text}"`;
+}
+
// The standard outline is the site's --line, which the switcher's label and chevron identify; More contrast must reach 3:1.
async function checkDrawerSwitcher(page, fail) {
await page.evaluate(() => document.documentElement.setAttribute("data-contrast", "more"));
@@ -193,6 +315,9 @@ async function check({ browsers, base, pagePath, run }) {
if (mobile) {
await page.goto(base + pagePath, { waitUntil: "networkidle" });
notes.push(await checkDrawerSwitcher(page, fail));
+ } else {
+ await page.goto(base + pagePath, { waitUntil: "networkidle" });
+ notes.push(await checkHeadingAnchor(page, run.browser, fail));
}
notes.push(await checkInlineCodeFit(page, base, fail));
} finally {
diff --git a/apps/docs/scripts/stitch-parity.e2e.mjs b/apps/docs/scripts/stitch-parity.e2e.mjs
index 393c8174..d708bd1f 100644
--- a/apps/docs/scripts/stitch-parity.e2e.mjs
+++ b/apps/docs/scripts/stitch-parity.e2e.mjs
@@ -191,10 +191,14 @@ test(
);
const tocEntry = (doc, id) => doc.querySelector(`#nd-toc a[href="#${id}"]`);
assert.equal(
- users.querySelector('h2#next-steps > a[href="#next-steps"]')?.textContent,
+ users.querySelector("h2#next-steps")?.textContent,
"Next steps",
"the heading renders in the body",
);
+ assert.ok(
+ users.querySelector('h2#next-steps + a[data-heading-anchor][href="#next-steps"]'),
+ "the heading has its # section link",
+ );
assert.ok(
tocEntry(users, "next-steps"),
"the Next steps heading has its TOC entry like any other heading",
diff --git a/packages/docs-next/src/shell.test.tsx b/packages/docs-next/src/shell.test.tsx
index 7f0b5966..a04cc1fb 100644
--- a/packages/docs-next/src/shell.test.tsx
+++ b/packages/docs-next/src/shell.test.tsx
@@ -13,6 +13,7 @@ import { DocsShell } from "./shell.js";
import { SidebarFolder } from "./sidebar-folder.js";
import { SkipLinkFocus, prepareSkipTarget } from "./skip-link-focus.js";
import { stateBadgesPlugin } from "./state-badges-plugin.js";
+import { TocSmoothScroll } from "./toc-smooth-scroll.js";
import { UserContentAnchors } from "./user-content-anchors.js";
// `DocsShell` renders fumadocs' Next `DocsLayout`, whose sidebar reads
@@ -214,7 +215,7 @@ test("prepareSkipTarget leaves an already-focusable target's tabindex alone", ()
assert.equal(article.getAttribute("tabindex"), "0");
});
-test("DocsShell mounts the skip-link focus keeper after the layout, and the raw-anchor follower", () => {
+test("DocsShell mounts the skip-link focus keeper after the layout, the raw-anchor follower and the TOC scroll", () => {
const element = DocsShell({
source: { pageTree: { name: "root", children: [] } } as never,
children: null,
@@ -222,6 +223,7 @@ test("DocsShell mounts the skip-link focus keeper after the layout, and the raw-
const children = element.props.children;
assert.equal(children[children.length - 1]?.type, SkipLinkFocus);
assert.ok(children.some((child) => child?.type === UserContentAnchors));
+ assert.ok(children.some((child) => child?.type === TocSmoothScroll));
});
// The article inside the shell: fumadocs' `DocsPage` reads the layout and
diff --git a/packages/docs-next/src/shell.tsx b/packages/docs-next/src/shell.tsx
index e18e548d..20038f64 100644
--- a/packages/docs-next/src/shell.tsx
+++ b/packages/docs-next/src/shell.tsx
@@ -14,6 +14,7 @@ import { SidebarLandmarks } from "./sidebar-landmarks.js";
import { SidebarScrollbar } from "./sidebar-scrollbar.js";
import { SkipLinkFocus } from "./skip-link-focus.js";
import { slimPageTree } from "./slim-tree.js";
+import { TocSmoothScroll } from "./toc-smooth-scroll.js";
import type { DocsSource } from "./types.js";
import { UserContentAnchors } from "./user-content-anchors.js";
@@ -181,6 +182,7 @@ export function DocsShell({
{children}
+
);
diff --git a/packages/docs-next/src/toc-smooth-scroll.test.tsx b/packages/docs-next/src/toc-smooth-scroll.test.tsx
new file mode 100644
index 00000000..c2618b82
--- /dev/null
+++ b/packages/docs-next/src/toc-smooth-scroll.test.tsx
@@ -0,0 +1,84 @@
+import assert from "node:assert/strict";
+import test, { afterEach } from "node:test";
+import { act } from "react";
+import { type Root, createRoot } from "react-dom/client";
+import { TocSmoothScroll } from "./toc-smooth-scroll.js";
+
+let root: Root | undefined;
+afterEach(async () => {
+ if (root) await act(async () => root?.unmount());
+ root = undefined;
+ document.body.innerHTML = "";
+ document.documentElement.removeAttribute("data-motion");
+ window.history.replaceState(null, "", "/");
+});
+
+async function mount(html: string): Promise {
+ document.body.innerHTML = html;
+ const host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => root?.render( ));
+}
+
+function spyScroll(): { calls: [string, unknown][]; restore(): void } {
+ const proto = Element.prototype;
+ const original = proto.scrollIntoView;
+ const calls: [string, unknown][] = [];
+ proto.scrollIntoView = function (this: Element, options) {
+ calls.push([this.id, options]);
+ };
+ return { calls, restore: () => (proto.scrollIntoView = original) };
+}
+
+const click = (selector: string) =>
+ document
+ .querySelector(selector)
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+
+const PAGE = `
+ Install
+ Configure
+ see Install
+ Install
+ `;
+
+test("an entry in either table of contents scrolls smoothly to its heading", async () => {
+ const scroll = spyScroll();
+ try {
+ await mount(PAGE);
+ assert.equal(click("#nd-toc a span"), false, "the jump is replaced");
+ assert.equal(window.location.hash, "#install");
+ assert.equal(click("[data-inline-toc] a"), false);
+ assert.equal(window.location.hash, "#configure");
+ assert.deepEqual(scroll.calls, [
+ ["install", { behavior: "smooth", block: "start" }],
+ ["configure", { behavior: "smooth", block: "start" }],
+ ]);
+ } finally {
+ scroll.restore();
+ }
+});
+
+test("under reduced motion a table of contents entry jumps as a plain link", async () => {
+ const scroll = spyScroll();
+ try {
+ await mount(PAGE);
+ document.documentElement.setAttribute("data-motion", "reduced");
+ assert.equal(click("#nd-toc a"), true, "the click is left to the browser");
+ assert.deepEqual(scroll.calls, []);
+ } finally {
+ scroll.restore();
+ }
+});
+
+test("links outside the tables of contents are not taken over", async () => {
+ const scroll = spyScroll();
+ try {
+ await mount(PAGE);
+ assert.equal(click("#body-link"), true);
+ assert.deepEqual(scroll.calls, []);
+ } finally {
+ scroll.restore();
+ }
+});
diff --git a/packages/docs-next/src/toc-smooth-scroll.tsx b/packages/docs-next/src/toc-smooth-scroll.tsx
new file mode 100644
index 00000000..80be6a6f
--- /dev/null
+++ b/packages/docs-next/src/toc-smooth-scroll.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import { followSectionLink } from "@coder/docs-ui";
+import { useEffect } from "react";
+
+/** The "On this page" entries: the desktop list and the small-screen one under the title. */
+export const TOC_LINK_SELECTOR = '#nd-toc a[href^="#"], [data-inline-toc] a[href^="#"]';
+
+/** Scrolls smoothly to a heading picked from either table of contents, unless motion is reduced. */
+export function TocSmoothScroll(): null {
+ useEffect(() => {
+ const onClick = (event: MouseEvent) => {
+ const link =
+ event.target instanceof Element
+ ? event.target.closest(TOC_LINK_SELECTOR)
+ : null;
+ if (link) followSectionLink(event, link);
+ };
+ document.addEventListener("click", onClick);
+ return () => document.removeEventListener("click", onClick);
+ }, []);
+ return null;
+}
diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css
index f24ffd6e..773b37b5 100644
--- a/packages/docs-theme/src/brand.css
+++ b/packages/docs-theme/src/brand.css
@@ -885,6 +885,80 @@ figure.shiki:not(.not-fumadocs-codeblock *) pre {
border-color: var(--docs-control-border);
}
-.group\/heading > button:focus-visible {
+/* No block padding or border, so the heading's prose margins still collapse through it. */
+[data-heading] {
+ position: relative;
+ width: fit-content;
+ max-width: 100%;
+ padding-inline-end: 1.75rem;
+}
+
+.prose :where([data-heading]:has(> :is(h2, h3, h4)) + *),
+.prose :where([data-heading]:has(> :is(h2, h3, h4)) + [data-heading] > :first-child) {
+ margin-top: 0;
+}
+
+.prose > [data-heading]:first-child > :first-child {
+ margin-top: 0;
+}
+
+[data-heading-anchor] {
+ position: absolute;
+ inset-inline-end: 0;
+ top: 50%;
+ translate: 0 -50%;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 1.5rem;
+ min-height: 1.5rem;
+ border-radius: 0.375rem;
+ font-weight: 600;
+ color: var(--color-fd-muted-foreground);
+ text-decoration: none;
+ opacity: 0;
+ transition-property: opacity, color;
+ transition-duration: 100ms;
+}
+
+[data-heading-anchor]::before {
+ content: "#";
+}
+
+[data-heading]:has(> h2) > [data-heading-anchor] {
+ font-size: 1.5em;
+}
+
+[data-heading]:has(> h3) > [data-heading-anchor] {
+ font-size: 1.25em;
+}
+
+/* Empty alt text keeps the # out of the link's name, so its hidden text names it. */
+@supports (content: "#" / "") {
+ [data-heading-anchor]::before {
+ content: "#" / "";
+ }
+}
+
+[data-heading]:hover > [data-heading-anchor],
+[data-heading-anchor]:focus-visible {
opacity: 1;
}
+
+[data-heading-anchor]:hover {
+ color: var(--color-fd-foreground);
+}
+
+@media (hover: none) {
+ [data-heading-anchor] {
+ opacity: 1;
+ }
+}
+
+@media (pointer: coarse) {
+ [data-heading-anchor]::after {
+ content: "";
+ position: absolute;
+ inset: -0.625rem;
+ }
+}
diff --git a/packages/docs-ui/src/heading.test.tsx b/packages/docs-ui/src/heading.test.tsx
new file mode 100644
index 00000000..0514598a
--- /dev/null
+++ b/packages/docs-ui/src/heading.test.tsx
@@ -0,0 +1,171 @@
+import assert from "node:assert/strict";
+import test, { afterEach } from "node:test";
+import { type ReactNode, act } from "react";
+import { type Root, createRoot } from "react-dom/client";
+import { Heading } from "./heading.js";
+
+const mounted: { root: Root; host: HTMLElement }[] = [];
+afterEach(async () => {
+ for (const { root, host } of mounted.splice(0)) {
+ await act(async () => root.unmount());
+ host.remove();
+ }
+ document.documentElement.removeAttribute("data-motion");
+ window.history.replaceState(null, "", "/");
+});
+
+async function mount(tree: ReactNode): Promise {
+ const host = document.createElement("article");
+ document.body.append(host);
+ const root = createRoot(host);
+ mounted.push({ root, host });
+ await act(async () => root.render(tree));
+ return host;
+}
+
+function anchorOf(host: HTMLElement): HTMLAnchorElement {
+ const anchor = host.querySelector("[data-heading-anchor]");
+ assert.ok(anchor, "the heading has a # link");
+ return anchor;
+}
+
+// Name from content: the element's text, with no ARIA naming to override it.
+function accessibleName(element: Element): string {
+ assert.equal(
+ [...element.querySelectorAll("*"), element].some((node) =>
+ [...node.attributes].some((attribute) => attribute.name.startsWith("aria-")),
+ ),
+ false,
+ "no ARIA attributes",
+ );
+ return element.textContent ?? "";
+}
+
+// Spies on scrollIntoView for one test and reports each call's options.
+function spyScroll(): { calls: (ScrollIntoViewOptions | boolean | undefined)[]; restore(): void } {
+ const proto = Element.prototype;
+ const original = proto.scrollIntoView;
+ const calls: (ScrollIntoViewOptions | boolean | undefined)[] = [];
+ proto.scrollIntoView = function (options) {
+ calls.push(options);
+ };
+ return { calls, restore: () => (proto.scrollIntoView = original) };
+}
+
+const click = (element: Element, init: MouseEventInit = {}) =>
+ element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, ...init }));
+
+test("the heading is plain text and a # link beside it is named by hidden text", async () => {
+ const host = await mount(
+
+ Coder Workspaces
+ ,
+ );
+ const heading = host.querySelector("h2#coder-workspaces");
+ assert.ok(heading);
+ assert.equal(heading.querySelector("a, button"), null, "the heading holds no control");
+ assert.equal(accessibleName(heading), "Coder Workspaces", "the heading's name is its text");
+ const anchor = anchorOf(host);
+ assert.equal(heading.nextElementSibling, anchor, "the # link follows the heading");
+ assert.ok(anchor.parentElement?.hasAttribute("data-heading"));
+ assert.equal(anchor.getAttribute("href"), "#coder-workspaces");
+ assert.equal(accessibleName(anchor), "Coder Workspaces");
+ assert.ok(anchor.querySelector(":scope > span.sr-only"), "the name is visually hidden text");
+ assert.equal(anchor.title, "Link to this section", "the tooltip doesn't repeat the name");
+});
+
+test("textLink makes the heading text a link to the section as well", async () => {
+ const host = await mount(
+
+ Install
+ ,
+ );
+ const links = [...host.querySelectorAll("a")];
+ assert.deepEqual(
+ links.map((link) => link.getAttribute("href")),
+ ["#install", "#install"],
+ );
+ assert.equal(host.querySelector("h3 > a")?.textContent, "Install");
+ assert.equal(accessibleName(anchorOf(host)), "Install");
+});
+
+test("a heading without an id renders with no link", async () => {
+ const host = await mount(Untitled );
+ assert.equal(host.querySelector("h2")?.textContent, "Untitled");
+ assert.equal(host.querySelector("a"), null);
+});
+
+test("each heading's # link is named after its own heading", async () => {
+ const host = await mount(
+ <>
+
+ One
+
+
+ Two
+
+ >,
+ );
+ const names = [...host.querySelectorAll("[data-heading-anchor]")].map(accessibleName);
+ assert.deepEqual(names, ["One", "Two"]);
+});
+
+test("clicking the # link scrolls smoothly to the heading and updates the URL", async () => {
+ const scroll = spyScroll();
+ try {
+ const host = await mount(
+
+ Next steps
+ ,
+ );
+ const hashChanges: string[] = [];
+ const onHashChange = (event: HashChangeEvent) => hashChanges.push(event.newURL);
+ window.addEventListener("hashchange", onHashChange);
+ const followed = click(anchorOf(host));
+ window.removeEventListener("hashchange", onHashChange);
+ assert.equal(followed, false, "the default jump is replaced");
+ assert.equal(window.location.hash, "#next-steps");
+ assert.deepEqual(hashChanges, [window.location.href], "hashchange listeners still hear it");
+ assert.deepEqual(scroll.calls, [{ behavior: "smooth", block: "start" }]);
+
+ const entries = window.history.length;
+ click(anchorOf(host));
+ assert.equal(window.history.length, entries, "a second click adds no history entry");
+ assert.equal(scroll.calls.length, 2, "a second click scrolls back to the heading");
+ } finally {
+ scroll.restore();
+ }
+});
+
+test("under reduced motion the # link jumps with the browser's own navigation", async () => {
+ document.documentElement.setAttribute("data-motion", "reduced");
+ const scroll = spyScroll();
+ try {
+ const host = await mount(
+
+ Next steps
+ ,
+ );
+ assert.equal(click(anchorOf(host)), true, "the click is left to the browser");
+ assert.deepEqual(scroll.calls, []);
+ } finally {
+ scroll.restore();
+ }
+});
+
+test("a modified click on the # link is left to the browser", async () => {
+ const scroll = spyScroll();
+ try {
+ const host = await mount(
+
+ Next steps
+ ,
+ );
+ for (const init of [{ metaKey: true }, { ctrlKey: true }, { shiftKey: true }]) {
+ assert.equal(click(anchorOf(host), init), true, JSON.stringify(init));
+ }
+ assert.deepEqual(scroll.calls, []);
+ } finally {
+ scroll.restore();
+ }
+});
diff --git a/packages/docs-ui/src/heading.tsx b/packages/docs-ui/src/heading.tsx
new file mode 100644
index 00000000..e9b4cd47
--- /dev/null
+++ b/packages/docs-ui/src/heading.tsx
@@ -0,0 +1,64 @@
+"use client";
+
+import {
+ type ComponentPropsWithoutRef,
+ type MouseEvent,
+ type ReactNode,
+ isValidElement,
+} from "react";
+import { followSectionLink } from "./section-scroll.js";
+
+type Level = "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
+
+export type HeadingProps = ComponentPropsWithoutRef<"h1"> & {
+ as: Level;
+ /** Also make the heading text a link to its section. */
+ textLink?: boolean;
+};
+
+/** The text a reader sees in rendered children, with whitespace collapsed. */
+export function plainText(node: ReactNode): string {
+ const walk = (child: ReactNode): string => {
+ if (typeof child === "string" || typeof child === "number") return String(child);
+ if (Array.isArray(child)) return child.map(walk).join("");
+ if (isValidElement<{ children?: ReactNode }>(child)) return walk(child.props.children);
+ return "";
+ };
+ return walk(node).replace(/\s+/g, " ").trim();
+}
+
+/**
+ * A docs heading with a `#` link to its own section beside it, shown on hover and
+ * focus. The link sits outside the heading, so its name, visually hidden text,
+ * isn't added to the heading's. Replaces Fumadocs' `Heading` (fumadocs-ui
+ * 16.15.14), whose icon beside the text copies the URL instead.
+ */
+export function Heading({ as: As, textLink = false, children, ...props }: HeadingProps) {
+ const { id } = props;
+ if (!id) return {children} ;
+ const className = ["scroll-m-28", props.className].filter(Boolean).join(" ");
+ const follow = (event: MouseEvent) =>
+ followSectionLink(event, event.currentTarget);
+ return (
+
+ );
+}
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index e25f2b9b..0988ea2c 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -32,6 +32,7 @@ export {
onMotionPreferenceChange,
prefersReducedMotion,
} from "./motion-preference.js";
+export { followSectionLink, type SectionLinkClick } from "./section-scroll.js";
export { ExternalLink } from "./external-link.js";
export { ReleasesTable, type ReleasesTableProps } from "./releases-table.js";
export { CoderMark } from "./coder-mark.js";
diff --git a/packages/docs-ui/src/mdx.test.tsx b/packages/docs-ui/src/mdx.test.tsx
index 99bad1ac..2eea2267 100644
--- a/packages/docs-ui/src/mdx.test.tsx
+++ b/packages/docs-ui/src/mdx.test.tsx
@@ -419,6 +419,19 @@ test("the MDX map renders tables through the keyboard-scrollable wrapper", () =>
assert.equal(wrapper.querySelector(":scope > table td")?.textContent, "cell");
});
+test("the MDX map renders headings as plain text followed by a # section link", () => {
+ const components = getMDXComponents();
+ for (const level of ["h2", "h3", "h4"] as const) {
+ const H = components[level] as ElementType;
+ const heading = renderToFragment(Next steps ).querySelector(level);
+ assert.ok(heading, level);
+ assert.equal(heading.querySelector("a, button"), null, `${level} holds no control`);
+ const anchor = heading.nextElementSibling;
+ assert.ok(anchor?.hasAttribute("data-heading-anchor"), `${level} is followed by its # link`);
+ assert.equal(anchor?.getAttribute("href"), "#next-steps");
+ }
+});
+
test("the MDX map renders a Card as a link with its title heading and description", () => {
const Cards = getMDXComponents().Cards as ElementType;
const Card = getMDXComponents().Card as ElementType;
diff --git a/packages/docs-ui/src/mdx.tsx b/packages/docs-ui/src/mdx.tsx
index d9eb81a1..78f725db 100644
--- a/packages/docs-ui/src/mdx.tsx
+++ b/packages/docs-ui/src/mdx.tsx
@@ -19,6 +19,7 @@ import { ExperimentalNote, PremiumCallout, PremiumNote } from "./annotations.js"
import { Callout } from "./callout.js";
import { Experimental, Premium, Var } from "./docs-context.js";
import { ExternalLink } from "./external-link.js";
+import { Heading } from "./heading.js";
import { ExternalLinkMark } from "./icons.js";
import { LocalVideoPlayer } from "./local-video.js";
import { OSTab } from "./os-tab.js";
@@ -385,6 +386,21 @@ export interface MdxComponentOptions {
assetBasePath?: string;
}
+// Set to true to make heading text link to its section again, as in Fumadocs.
+const HEADING_TEXT_LINKS = false;
+
+function createHeadings(textLink: boolean): MDXComponents {
+ const levels = ["h1", "h2", "h3", "h4", "h5", "h6"] as const;
+ return Object.fromEntries(
+ levels.map((level) => [
+ level,
+ (props: ComponentProps<"h1">) => ,
+ ]),
+ );
+}
+
+const headings = createHeadings(HEADING_TEXT_LINKS);
+
export function getMDXComponents(components?: MDXComponents, options: MdxComponentOptions = {}) {
const assetBasePath = options.assetBasePath ?? "";
// The docs page passes `a` as Fumadocs' relative-link resolver. Pull it out
@@ -395,6 +411,7 @@ export function getMDXComponents(components?: MDXComponents, options: MdxCompone
return {
...defaultMdxComponents,
...engineComponents,
+ ...headings,
table: ScrollTable,
pre: createCodeBlock(),
img: createLocalImg(assetBasePath),
diff --git a/packages/docs-ui/src/scroll-table.test.tsx b/packages/docs-ui/src/scroll-table.test.tsx
index 4196ddac..b11d747f 100644
--- a/packages/docs-ui/src/scroll-table.test.tsx
+++ b/packages/docs-ui/src/scroll-table.test.tsx
@@ -108,7 +108,7 @@ test("an uncaptioned table is named after the closest heading before it", async
const wrappers = await mount(
<>
Install
- {/* The rendered heading shape: a self-link, then a copy button with screen-reader text. */}
+ {/* A button inside a heading keeps its screen-reader text out of the name. */}
Server flags
diff --git a/packages/docs-ui/src/scroll-table.tsx b/packages/docs-ui/src/scroll-table.tsx
index 7eb1dcc5..613cbac2 100644
--- a/packages/docs-ui/src/scroll-table.tsx
+++ b/packages/docs-ui/src/scroll-table.tsx
@@ -9,7 +9,7 @@ type RegionName = { "aria-labelledby": string } | { "aria-label": string };
const captionOf = (wrapper: Element) => wrapper.querySelector(":scope > table > caption");
-// The heading's own text, without its copy-link button's screen-reader label.
+// The heading's own text, without the screen-reader label of any button inside it.
function headingText(heading: Element): string {
const copy = heading.cloneNode(true) as Element;
for (const button of copy.querySelectorAll("button")) button.remove();
diff --git a/packages/docs-ui/src/section-scroll.test.ts b/packages/docs-ui/src/section-scroll.test.ts
new file mode 100644
index 00000000..3199b484
--- /dev/null
+++ b/packages/docs-ui/src/section-scroll.test.ts
@@ -0,0 +1,108 @@
+import assert from "node:assert/strict";
+import test, { afterEach } from "node:test";
+import { followSectionLink } from "./section-scroll.js";
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ document.documentElement.removeAttribute("data-motion");
+ window.history.replaceState(null, "", "/");
+});
+
+// Spies on scrollIntoView and reports each call's target and options.
+function spyScroll(): { calls: [string, unknown][]; restore(): void } {
+ const proto = Element.prototype;
+ const original = proto.scrollIntoView;
+ const calls: [string, unknown][] = [];
+ proto.scrollIntoView = function (this: Element, options) {
+ calls.push([this.id, options]);
+ };
+ return { calls, restore: () => (proto.scrollIntoView = original) };
+}
+
+function page(html: string): HTMLAnchorElement {
+ document.body.innerHTML = html;
+ const link = document.querySelector("a[data-test]");
+ assert.ok(link, "the page has the link under test");
+ return link;
+}
+
+function click(link: HTMLAnchorElement, init: MouseEventInit = {}) {
+ const event = new MouseEvent("click", { bubbles: true, cancelable: true, ...init });
+ return { taken: followSectionLink(event, link), event };
+}
+
+test("a same-page section link scrolls smoothly and records the fragment", () => {
+ const scroll = spyScroll();
+ try {
+ const link = page('Install Install ');
+ const heard: string[] = [];
+ const onHashChange = (event: HashChangeEvent) => heard.push(event.newURL);
+ window.addEventListener("hashchange", onHashChange);
+ const { taken, event } = click(link);
+ window.removeEventListener("hashchange", onHashChange);
+ assert.equal(taken, true);
+ assert.equal(event.defaultPrevented, true);
+ assert.equal(window.location.hash, "#install");
+ assert.deepEqual(heard, [window.location.href]);
+ assert.deepEqual(scroll.calls, [["install", { behavior: "smooth", block: "start" }]]);
+
+ const entries = window.history.length;
+ click(link);
+ assert.equal(window.history.length, entries, "a repeat click adds no history entry");
+ assert.equal(scroll.calls.length, 2, "a repeat click scrolls back to the section");
+ } finally {
+ scroll.restore();
+ }
+});
+
+test("reduced motion, modified clicks and other buttons are left to the browser", () => {
+ const scroll = spyScroll();
+ try {
+ const link = page('Install Install ');
+ for (const init of [{ metaKey: true }, { ctrlKey: true }, { shiftKey: true }, { button: 1 }]) {
+ assert.equal(click(link, init).taken, false, JSON.stringify(init));
+ }
+ document.documentElement.setAttribute("data-motion", "reduced");
+ const { taken, event } = click(link);
+ assert.equal(taken, false);
+ assert.equal(event.defaultPrevented, false);
+ assert.deepEqual(scroll.calls, []);
+ } finally {
+ scroll.restore();
+ }
+});
+
+test("links to another page, a missing id or a hidden section are left to the browser", () => {
+ const scroll = spyScroll();
+ try {
+ for (const html of [
+ 'x Install ',
+ 'x ',
+ 'x
Flags
',
+ 'x More Flags ',
+ 'x
Flags ',
+ ]) {
+ assert.equal(click(page(html)).taken, false, html);
+ }
+ assert.deepEqual(scroll.calls, []);
+ } finally {
+ scroll.restore();
+ }
+});
+
+test("a percent-encoded fragment finds its section", () => {
+ const scroll = spyScroll();
+ try {
+ const link = page('x Café ');
+ assert.equal(click(link).taken, true);
+ assert.deepEqual(
+ scroll.calls.map(([id]) => id),
+ ["café"],
+ );
+ const entries = window.history.length;
+ click(link);
+ assert.equal(window.history.length, entries, "the decoded fragment counts as current");
+ } finally {
+ scroll.restore();
+ }
+});
diff --git a/packages/docs-ui/src/section-scroll.ts b/packages/docs-ui/src/section-scroll.ts
new file mode 100644
index 00000000..3dd39e36
--- /dev/null
+++ b/packages/docs-ui/src/section-scroll.ts
@@ -0,0 +1,61 @@
+import { prefersReducedMotion } from "./motion-preference.js";
+
+/** The parts of a React or DOM click event the section scroll reads. */
+export interface SectionLinkClick {
+ button: number;
+ metaKey: boolean;
+ ctrlKey: boolean;
+ shiftKey: boolean;
+ altKey: boolean;
+ defaultPrevented: boolean;
+ preventDefault(): void;
+}
+
+const HIDDEN =
+ '[hidden], [inert], [role="tabpanel"][data-state="inactive"], details:not([open]) > :not(summary)';
+
+function decodeFragment(raw: string): string {
+ try {
+ return decodeURIComponent(raw);
+ } catch {
+ return raw;
+ }
+}
+
+function sectionTarget(link: HTMLAnchorElement): HTMLElement | null {
+ const url = new URL(link.href, window.location.href);
+ const here = window.location;
+ if (url.origin !== here.origin || url.pathname !== here.pathname || url.search !== here.search) {
+ return null;
+ }
+ const id = decodeFragment(url.hash.slice(1));
+ if (!id) return null;
+ const target = document.getElementById(id);
+ // A hidden target, such as a heading in an inactive tab, is left to the reveal handlers.
+ return target && !target.closest(HIDDEN) ? target : null;
+}
+
+/**
+ * Scrolls smoothly to the section a same-page `#id` link names and records the
+ * fragment, unless motion is reduced, the click is modified, or the target is
+ * missing or hidden; those are left to the browser's own jump. Returns whether
+ * it took over the click.
+ */
+export function followSectionLink(event: SectionLinkClick, link: HTMLAnchorElement): boolean {
+ if (event.defaultPrevented || event.button !== 0) return false;
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;
+ if (prefersReducedMotion()) return false;
+ const target = sectionTarget(link);
+ if (!target) return false;
+ event.preventDefault();
+ if (decodeFragment(window.location.hash.slice(1)) !== target.id) {
+ const oldURL = window.location.href;
+ window.history.pushState(null, "", `#${target.id}`);
+ // pushState fires no hashchange; the TOC and other fragment listeners still need one.
+ window.dispatchEvent(
+ new HashChangeEvent("hashchange", { oldURL, newURL: window.location.href }),
+ );
+ }
+ target.scrollIntoView({ behavior: "smooth", block: "start" });
+ return true;
+}