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
66 changes: 65 additions & 1 deletion source.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
import { rehypeCodeDefaultOptions } from "fumadocs-core/mdx-plugins";
import { metaSchema, pageSchema } from "fumadocs-core/source/schema";
import { defineConfig, defineDocs } from "fumadocs-mdx/config";
import { codeSampleLabel } from "./src/lib/code-sample-label.mjs";

type HastNode = {
type?: string;
tagName?: string;
name?: string;
properties?: Record<string, unknown>;
children?: HastNode[];
};

function textProp(value: unknown) {
return typeof value === "string" ? value : undefined;
}

function stampCodeOrder() {
return (tree: HastNode) => {
const blocks: HastNode[] = [];
const walk = (node: HastNode) => {
const isPre =
(node.type === "element" && node.tagName === "pre") ||
((node.type === "mdxJsxFlowElement" ||
node.type === "mdxJsxTextElement") &&
node.name === "pre");
if (isPre) blocks.push(node);
for (const child of node.children ?? []) walk(child);
};
walk(tree);
const used = new Set<string>();
for (const [index, block] of blocks.entries()) {
const order = index + 1;
if (!block.properties) block.properties = {};
const props = block.properties;
const title = textProp(props.dataTitle) ?? textProp(props.title);
const language = textProp(props.dataLanguage);
props.dataOrder = order;
props.dataCodeLabel = codeSampleLabel({
title,
language,
order,
used,
});
}
};
}

// You can customize Zod schemas for frontmatter and `meta.json` here
// see https://fumadocs.dev/docs/mdx/collections
Expand All @@ -18,6 +63,25 @@ export const docs = defineDocs({

export default defineConfig({
mdxOptions: {
// MDX options
rehypeCodeOptions: {
...rehypeCodeDefaultOptions,
transformers: [
...(rehypeCodeDefaultOptions.transformers ?? []),
{
name: "kimetsu-code-language",
pre(node) {
const lang = this.options.lang;
if (typeof lang === "string" && lang.length > 0) {
node.properties.dataLanguage = lang;
}
const title = this.options.meta?.title;
if (typeof title === "string" && title.length > 0) {
node.properties.dataTitle = title;
}
},
},
],
},
rehypePlugins: (plugins) => [...plugins, stampCodeOrder],
},
});
20 changes: 19 additions & 1 deletion src/app/docs/[[...slug]]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { createRelativeLink } from "fumadocs-ui/mdx";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { DocsPre } from "@/components/docs-code";
import { getMDXComponents } from "@/components/mdx";
import { gitConfig } from "@/lib/shared";
import { getPageImage, getPageMarkdownUrl, source } from "@/lib/source";
Expand All @@ -22,7 +23,23 @@ export default async function Page(props: PageProps<"/docs/[[...slug]]">) {
const markdownUrl = getPageMarkdownUrl(page).url;

return (
<DocsPage toc={page.data.toc} full={page.data.full}>
<DocsPage
toc={page.data.toc}
full={page.data.full}
role="main"
tableOfContent={{
container: {
role: "navigation",
"aria-label": "On this page",
},
}}
tableOfContentPopover={{
container: {
role: "navigation",
"aria-label": "Page sections",
},
}}
>
<DocsTitle>{page.data.title}</DocsTitle>
<DocsDescription className="mb-0">
{page.data.description}
Expand All @@ -39,6 +56,7 @@ export default async function Page(props: PageProps<"/docs/[[...slug]]">) {
components={getMDXComponents({
// this allows you to link to other pages with relative file paths
a: createRelativeLink(source, page),
pre: DocsPre,
})}
/>
</DocsBody>
Expand Down
2 changes: 2 additions & 0 deletions src/app/docs/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { DocsLayout } from "fumadocs-ui/layouts/docs";
import { DocsLandmarks } from "@/components/docs-landmarks";
import { baseOptions } from "@/lib/layout.shared";
import { source } from "@/lib/source";

export default function Layout({ children }: LayoutProps<"/docs">) {
return (
<DocsLayout tree={source.getPageTree()} {...baseOptions()}>
<DocsLandmarks />
{children}
</DocsLayout>
);
Expand Down
10 changes: 10 additions & 0 deletions src/app/global.css
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@
--color-fd-muted-foreground: #a3a3a3;
}

/* Shiki comment gray #6A737D is 3.65:1 on the dark code background #191919.
The token sets the variable inline, so the override has to win that declaration.
Server HTML omits the space after the colon; the client render inserts one. */
.dark .shiki span[style*="--shiki-dark:#6A737D"],
.dark .shiki span[style*="--shiki-dark: #6A737D"],
.dark .shiki span[style*="--shiki-dark:#6a737d"],
.dark .shiki span[style*="--shiki-dark: #6a737d"] {
--shiki-dark: #8b949e !important;
}

html {
scrollbar-gutter: stable;
}
Expand Down
38 changes: 38 additions & 0 deletions src/components/docs-code.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"use client";

import { CodeBlock, Pre } from "fumadocs-ui/components/codeblock";
import type { ComponentProps } from "react";
import { codeSampleLabel } from "@/lib/code-sample-label.mjs";

type DocsPreProps = ComponentProps<"pre"> & {
title?: string;
"data-language"?: string;
"data-title"?: string;
"data-order"?: number | string;
"data-code-label"?: string;
};

export function DocsPre({
children,
title,
"data-language": dataLanguage,
"data-title": dataTitle,
"data-order": dataOrder,
"data-code-label": dataCodeLabel,
...props
}: DocsPreProps) {
const order = Number(dataOrder);
const label =
dataCodeLabel ??
codeSampleLabel({
title: title ?? dataTitle,
language: dataLanguage,
order: Number.isFinite(order) ? order : 1,
used: new Set(),
});
return (
<CodeBlock {...props} viewportProps={{ "aria-label": label }}>
<Pre>{children}</Pre>
</CodeBlock>
);
}
24 changes: 24 additions & 0 deletions src/components/docs-landmarks.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use client";

import { usePathname } from "next/navigation";
import { useLayoutEffect } from "react";

// The mobile contents control is a <header> inside the TOC popover. Fumadocs
// has no prop for that element. A header stays a banner landmark unless its
// own role changes, so this sets role="group" after each client navigation.
// usePathname() is the dependency because the docs layout stays mounted while
// the page swaps; an empty dependency list would leave the next page's header
// unlabeled.
export function DocsLandmarks() {
const pathname = usePathname();

useLayoutEffect(() => {
if (!pathname.startsWith("/docs")) return;
for (const header of document.querySelectorAll("#nd-docs-layout header")) {
if (header.id === "nd-subnav") continue;
header.setAttribute("role", "group");
}
}, [pathname]);

return null;
}
23 changes: 23 additions & 0 deletions src/lib/code-sample-label.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const forbidden = /[«»:]/g;

function clean(value) {
return value.replace(forbidden, "").replace(/\s+/g, " ").trim();
}

export function codeSampleLabel({ title, language, order, used }) {
const named = clean(title ?? "");
const lang = clean(language ?? "");
const base = named
? named
: lang
? `${lang} code ${order}`
: `Code sample ${order}`;
let label = base;
let extra = 2;
while (used.has(label)) {
label = `${base} ${extra}`;
extra += 1;
}
used.add(label);
return label;
}
157 changes: 157 additions & 0 deletions tests/docs-a11y-chrome.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { codeSampleLabel } from "../src/lib/code-sample-label.mjs";

const css = await readFile(
new URL("../src/app/global.css", import.meta.url),
"utf8",
);
const page = await readFile(
new URL("../src/app/docs/[[...slug]]/page.tsx", import.meta.url),
"utf8",
);
const landmarks = await readFile(
new URL("../src/components/docs-landmarks.tsx", import.meta.url),
"utf8",
);
const code = await readFile(
new URL("../src/components/docs-code.tsx", import.meta.url),
"utf8",
);
const labelSource = await readFile(
new URL("../src/lib/code-sample-label.mjs", import.meta.url),
"utf8",
);
const sourceConfig = await readFile(
new URL("../source.config.ts", import.meta.url),
"utf8",
);
const fumadocsPage = await readFile(
new URL(
"../node_modules/fumadocs-ui/dist/layouts/docs/page/slots/container.js",
import.meta.url,
),
"utf8",
);
const fumadocsToc = await readFile(
new URL(
"../node_modules/fumadocs-ui/dist/layouts/docs/page/slots/toc.js",
import.meta.url,
),
"utf8",
);
const fumadocsLayout = await readFile(
new URL(
"../node_modules/fumadocs-ui/dist/layouts/docs/slots/container.js",
import.meta.url,
),
"utf8",
);
const fumadocsHeader = await readFile(
new URL(
"../node_modules/fumadocs-ui/dist/layouts/docs/slots/header.js",
import.meta.url,
),
"utf8",
);
const fumadocsCode = await readFile(
new URL(
"../node_modules/fumadocs-ui/dist/components/codeblock.js",
import.meta.url,
),
"utf8",
);

test("pins the fumadocs ids the docs chrome fix depends on", () => {
assert.match(fumadocsPage, /id:\s*"nd-page"/);
assert.match(fumadocsToc, /id:\s*"nd-toc"/);
assert.match(fumadocsLayout, /id:\s*"nd-docs-layout"/);
assert.match(fumadocsHeader, /id:\s*"nd-subnav"/);
assert.match(fumadocsCode, /\.\.\.viewportProps,\s*role:\s*"region"/);
});

test("pins the dark Shiki comment color override", () => {
for (const token of [
"--shiki-dark:#6A737D",
"--shiki-dark: #6A737D",
"--shiki-dark:#6a737d",
"--shiki-dark: #6a737d",
]) {
assert.equal(css.includes(token), true, token);
}
assert.match(css, /--shiki-dark:\s*#8b949e\s*!important;/);
});

test("sets docs landmark roles through fumadocs props", () => {
assert.match(page, /role="main"/);
assert.match(page, /role:\s*"navigation"/);
assert.match(page, /"aria-label":\s*"On this page"/);
assert.match(page, /"aria-label":\s*"Page sections"/);
assert.match(page, /pre:\s*DocsPre/);
assert.equal(page.includes("DocsCodeScope"), false);
assert.match(code, /codeSampleLabel\(/);
assert.match(code, /"data-order":\s*dataOrder/);
assert.match(code, /viewportProps=\{\{\s*"aria-label":\s*label\s*\}\}/);
assert.equal(code.includes("usePathname"), false);
assert.equal(code.includes("+="), false);
assert.match(sourceConfig, /dataOrder\s*=\s*order/);
assert.match(sourceConfig, /stampCodeOrder/);
});

test("builds readable code labels without screen-reader id marks", () => {
assert.match(labelSource, /\$\{lang\} code \$\{order\}/);
assert.match(labelSource, /`Code sample \$\{order\}`/);
assert.equal(code.includes("useId"), false);
const titled = new Set();
assert.equal(
codeSampleLabel({
title: "Install",
language: "bash",
order: 1,
used: titled,
}),
"Install",
);
const plain = new Set();
assert.equal(
codeSampleLabel({ language: "bash", order: 1, used: plain }),
"bash code 1",
);
assert.equal(
codeSampleLabel({ language: "json", order: 2, used: plain }),
"json code 2",
);
const untitled = new Set();
assert.equal(codeSampleLabel({ order: 1, used: untitled }), "Code sample 1");
const noisy = new Set();
const cleaned = codeSampleLabel({
title: "Note: «read»",
order: 1,
used: noisy,
});
assert.equal(cleaned, "Note read");
const built = [
cleaned,
"bash code 1",
"json code 2",
"Code sample 1",
"Install",
];
for (const label of built) {
assert.equal(label.includes("«"), false, label);
assert.equal(label.includes("»"), false, label);
assert.equal(label.includes(":"), false, label);
}
assert.match(sourceConfig, /dataCodeLabel = codeSampleLabel/);
});

test("reapplies the uncovered header role when the docs path changes", () => {
assert.match(landmarks, /usePathname\(\)/);
assert.match(landmarks, /useLayoutEffect\([\s\S]*?,\s*\[pathname\]\s*\)/);
assert.match(landmarks, /#nd-docs-layout header/);
assert.match(landmarks, /header\.id === "nd-subnav"/);
assert.match(landmarks, /setAttribute\("role", "group"\)/);
assert.equal(landmarks.includes("useLayoutEffect(() => {"), true);
assert.equal(/\],\s*\[\s*\]\s*\)/.test(landmarks), false);
});
Loading