From 9358884b10a58cec5f19ff62ab592905aa1d25e6 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 4 Nov 2026 19:45:06 +0000 Subject: [PATCH 1/3] feat(docs-ui): replace the heading copy button with a # section link Readers expect the icon beside a heading to go to that section, but Fumadocs' heading button copies the URL instead, and the heading text was the real link. Headings are now plain text followed by a # link that appears on hover and focus, is named after the heading, and scrolls smoothly to the section unless reduced motion is on. Linking the heading text again is one constant in the MDX map, or the headingTextLinks option per call, in case readers miss it. Assisted-by: AI --- apps/docs/scripts/a11y-keyboard.mjs | 97 +++++++++++- apps/docs/scripts/stitch-parity.e2e.mjs | 6 +- packages/docs-theme/src/brand.css | 42 +++++- packages/docs-ui/src/heading.test.tsx | 167 +++++++++++++++++++++ packages/docs-ui/src/heading.tsx | 64 ++++++++ packages/docs-ui/src/mdx.test.tsx | 22 +++ packages/docs-ui/src/mdx.tsx | 17 +++ packages/docs-ui/src/scroll-table.test.tsx | 2 +- packages/docs-ui/src/scroll-table.tsx | 2 +- 9 files changed, 414 insertions(+), 5 deletions(-) create mode 100644 packages/docs-ui/src/heading.test.tsx create mode 100644 packages/docs-ui/src/heading.tsx diff --git a/apps/docs/scripts/a11y-keyboard.mjs b/apps/docs/scripts/a11y-keyboard.mjs index d2bad6fb..f07780c2 100644 --- a/apps/docs/scripts/a11y-keyboard.mjs +++ b/apps/docs/scripts/a11y-keyboard.mjs @@ -1,5 +1,5 @@ // 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 outline +// link's Tab order and focus hand-off, the heading # links, and the version switcher's outline // contrast in the mobile drawer. Runs in Chromium and Firefox, at desktop and phone widths. import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -69,6 +69,98 @@ async function checkSkipLink(page, fail) { if ((await articleTabindex(page)) !== null) fail("the article keeps its tabindex after blur"); } +const HEADING = "#nd-page h2[id]:has(> [data-heading-anchor])"; + +// The last heading's # link: shown on focus and hover without moving the heading, +// named after the heading, and scrolling smoothly unless motion is reduced. +async function checkHeadingAnchor(page, fail) { + const heading = page.locator(HEADING).last(); + if ((await page.locator(HEADING).count()) === 0) { + fail("no heading carries a # link"); + return "no heading # link"; + } + const anchor = heading.locator("[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}`, + name: link + .getAttribute("aria-labelledby") + .split(/\s+/) + .map((id) => document.getElementById(id)?.textContent ?? "") + .join(" "), + text: link.parentElement.textContent, + links: link.parentElement.querySelectorAll("a").length, + }; + }); + const idle = await state(); + if (idle.links !== 1) + fail(`the heading "${idle.text}" holds ${idle.links} links, not just its #`); + if (idle.name !== idle.text) fail(`the # link is named "${idle.name}", not "${idle.text}"`); + + 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 (motion) => { + await page.evaluate((value) => { + document.documentElement.setAttribute("data-motion", value); + history.replaceState(null, "", location.pathname); + window.scrollTo({ top: 0, behavior: "instant" }); + }, motion); + await anchor.evaluate((link) => link.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 reduced = await scrollAfterClick("reduced"); + if (reduced.first !== reduced.last) + fail(`with reduced motion the # link scrolled from ${reduced.first} instead of jumping`); + const full = await scrollAfterClick("full"); + if (full.first >= full.last) + fail(`with full motion the # link jumped to ${full.last} instead of scrolling`); + for (const { hash } of [reduced, full]) { + if (hash !== `#${id}`) fail(`the # link left the address at "${hash}", not "#${id}"`); + } + await page.evaluate(() => document.documentElement.removeAttribute("data-motion")); + return `heading # link "${idle.text}"`; +} + async function checkDrawerSwitcher(page, fail) { await page.getByRole("button", { name: "Open Sidebar" }).click(); const trigger = page.locator('#nd-sidebar-mobile button.border[aria-haspopup="dialog"]').first(); @@ -151,6 +243,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, fail)); } } finally { await context.close(); diff --git a/apps/docs/scripts/stitch-parity.e2e.mjs b/apps/docs/scripts/stitch-parity.e2e.mjs index 9558f731..ff5e5504 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-theme/src/brand.css b/packages/docs-theme/src/brand.css index c8b6b9ed..41158ef9 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -668,10 +668,50 @@ samp { transition-property: opacity, visibility; } -.group\/heading > button:focus-visible { +[data-heading-anchor] { + position: relative; + display: inline-flex; + flex-shrink: 0; + align-items: center; + justify-content: center; + min-width: 1.5rem; + min-height: 1.5rem; + margin-inline-start: 0.25rem; + border-radius: 0.375rem; + color: var(--color-fd-muted-foreground); + text-decoration: none; + opacity: 0; + transition-property: opacity, color; + transition-duration: 100ms; +} + +[data-heading-anchor]::before { + content: "#"; +} + +.group\/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; + } +} + #nd-sidebar[data-collapsed="true"]:not([data-hovered="true"]) { visibility: hidden; transition-property: width, inset-block, transform, translate, background-color, visibility; diff --git a/packages/docs-ui/src/heading.test.tsx b/packages/docs-ui/src/heading.test.tsx new file mode 100644 index 00000000..f220f932 --- /dev/null +++ b/packages/docs-ui/src/heading.test.tsx @@ -0,0 +1,167 @@ +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; +} + +function accessibleName(element: Element): string | null { + const labelledBy = element.getAttribute("aria-labelledby"); + if (!labelledBy) return element.getAttribute("aria-label"); + return labelledBy + .split(/\s+/) + .map((id) => document.getElementById(id)?.textContent ?? "") + .join(" "); +} + +// 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 text is plain text and a # link follows it, named after the heading", async () => { + const host = await mount( + + Coder Workspaces + , + ); + const heading = host.querySelector("h2#coder-workspaces"); + assert.ok(heading); + assert.equal(heading.textContent, "Coder Workspaces"); + assert.equal(heading.querySelectorAll("a").length, 1); + assert.equal(heading.querySelector("button"), null); + const anchor = anchorOf(host); + assert.equal(anchor.getAttribute("href"), "#coder-workspaces"); + assert.equal(anchor.textContent, ""); + assert.equal(accessibleName(anchor), "Coder Workspaces"); + assert.equal(heading.lastElementChild, anchor); +}); + +test("textLink makes the heading text a link to the section as well", async () => { + const host = await mount( + + Install + , + ); + const links = [...host.querySelectorAll("h3 a")]; + assert.deepEqual( + links.map((link) => link.getAttribute("href")), + ["#install", "#install"], + ); + assert.equal(links[0]?.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..5dee6076 --- /dev/null +++ b/packages/docs-ui/src/heading.tsx @@ -0,0 +1,64 @@ +"use client"; + +import { type ComponentPropsWithoutRef, type MouseEvent, useId } from "react"; +import { prefersReducedMotion } from "./motion-preference.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; +}; + +const isPlainClick = (event: MouseEvent) => + event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey; + +function scrollToSection(event: MouseEvent, id: string): void { + if (event.defaultPrevented || !isPlainClick(event) || prefersReducedMotion()) return; + const target = document.getElementById(id); + if (!target) return; + event.preventDefault(); + const oldURL = window.location.href; + if (window.location.hash !== `#${id}`) { + window.history.pushState(null, "", `#${id}`); + // pushState fires no hashchange; listeners such as the TOC still need one. + window.dispatchEvent( + new HashChangeEvent("hashchange", { oldURL, newURL: window.location.href }), + ); + } + target.scrollIntoView({ behavior: "smooth", block: "start" }); +} + +/** + * A docs heading followed by a `#` link to its own section, shown on hover and + * focus and named after the heading text. 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 textId = useId(); + const { id } = props; + if (!id) return {children}; + const className = ["group/heading flex scroll-m-28 flex-row items-center", props.className] + .filter(Boolean) + .join(" "); + return ( + + {textLink ? ( + + {children} + + ) : ( + {children} + )} + {/* oxlint-disable-next-line jsx-a11y/anchor-has-content -- named by aria-labelledby; the # is CSS content so it stays out of the heading text. */} + scrollToSection(event, id)} + /> + + ); +} diff --git a/packages/docs-ui/src/mdx.test.tsx b/packages/docs-ui/src/mdx.test.tsx index 7cdf1ee8..5066b863 100644 --- a/packages/docs-ui/src/mdx.test.tsx +++ b/packages/docs-ui/src/mdx.test.tsx @@ -418,3 +418,25 @@ test("the MDX map renders tables through the keyboard-scrollable wrapper", () => assert.ok(wrapper.classList.contains("overflow-auto")); 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("button"), null, `${level} has no copy button`); + const links = [...heading.querySelectorAll("a")]; + assert.equal(links.length, 1, `${level} has only the # link`); + assert.ok(links[0]?.hasAttribute("data-heading-anchor")); + assert.equal(links[0]?.getAttribute("href"), "#next-steps"); + } +}); + +test("headingTextLinks makes the MDX map's heading text a link again", () => { + const H = getMDXComponents(undefined, { headingTextLinks: true }).h2 as ElementType; + const heading = renderToFragment(Next steps).querySelector("h2"); + const text = heading?.querySelector("a:not([data-heading-anchor])"); + assert.equal(text?.getAttribute("href"), "#next-steps"); + assert.equal(text?.textContent, "Next steps"); +}); diff --git a/packages/docs-ui/src/mdx.tsx b/packages/docs-ui/src/mdx.tsx index cba0bb90..bad00000 100644 --- a/packages/docs-ui/src/mdx.tsx +++ b/packages/docs-ui/src/mdx.tsx @@ -17,6 +17,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 { LocalVideoPlayer } from "./local-video.js"; import { OSTab } from "./os-tab.js"; import { ReleasesTable } from "./releases-table.js"; @@ -338,6 +339,21 @@ function createCodeBlock() { export interface MdxComponentOptions { /** Base path the site is served under (`""` for the root); refer to `prefixAssetPath`. */ assetBasePath?: string; + /** Make each heading's text a link to its section too, besides its `#` link. */ + headingTextLinks?: boolean; +} + +// 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">) => , + ]), + ); } export function getMDXComponents(components?: MDXComponents, options: MdxComponentOptions = {}) { @@ -350,6 +366,7 @@ export function getMDXComponents(components?: MDXComponents, options: MdxCompone return { ...defaultMdxComponents, ...stubComponents, + ...createHeadings(options.headingTextLinks ?? HEADING_TEXT_LINKS), Callout, Accordions, Accordion, 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