Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 127 additions & 2 deletions apps/docs/scripts/a11y-keyboard.mjs
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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"));
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 5 additions & 1 deletion apps/docs/scripts/stitch-parity.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 3 additions & 1 deletion packages/docs-next/src/shell.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -214,14 +215,15 @@ 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,
}) as unknown as { props: { children: { type?: unknown }[] } };
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
Expand Down
2 changes: 2 additions & 0 deletions packages/docs-next/src/shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -181,6 +182,7 @@ export function DocsShell({
{children}
</DocsLayout>
<UserContentAnchors />
<TocSmoothScroll />
<SkipLinkFocus />
</DocsProvider>
);
Expand Down
84 changes: 84 additions & 0 deletions packages/docs-next/src/toc-smooth-scroll.test.tsx
Original file line number Diff line number Diff line change
@@ -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<void> {
document.body.innerHTML = html;
const host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
await act(async () => root?.render(<TocSmoothScroll />));
}

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 = `
<nav id="nd-toc"><a href="#install"><span>Install</span></a></nav>
<details data-inline-toc open><nav><a href="#configure">Configure</a></nav></details>
<p><a id="body-link" href="#install">see Install</a></p>
<h2 id="install">Install</h2>
<h2 id="configure">Configure</h2>`;

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();
}
});
23 changes: 23 additions & 0 deletions packages/docs-next/src/toc-smooth-scroll.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLAnchorElement>(TOC_LINK_SELECTOR)
: null;
if (link) followSectionLink(event, link);
};
document.addEventListener("click", onClick);
return () => document.removeEventListener("click", onClick);
}, []);
return null;
}
76 changes: 75 additions & 1 deletion packages/docs-theme/src/brand.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Loading
Loading