From 2bf826bfe6225de04365ebfee00f7d74ae0feb79 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:37:57 +0000 Subject: [PATCH 1/4] refactor: cut comments to what the code cannot say, and check new ones --- .github/workflows/ci.yml | 36 +-- .github/workflows/codeql.yml | 13 +- .github/workflows/pr-description.yml | 8 +- .github/workflows/release.yml | 15 +- scripts/check-comments.mjs | 283 +++++++++++++++++ scripts/check-comments.test.mjs | 294 ++++++++++++++++++ scripts/check-pack.ts | 12 +- scripts/check-pr-description.ts | 17 +- src/components/analytics.test.tsx | 5 +- src/components/analytics.tsx | 27 +- src/components/callout.tsx | 5 +- src/components/cards.tsx | 5 +- src/components/code-tabs.tsx | 9 +- src/components/code.tsx | 42 +-- src/components/docs-error.tsx | 3 - src/components/docs-header.test.tsx | 4 +- src/components/docs-header.tsx | 35 +-- src/components/error-page.tsx | 14 +- src/components/home-menu.tsx | 15 +- src/components/mdx-components.test.tsx | 5 - src/components/mdx-components.tsx | 8 +- src/components/not-found.tsx | 3 - src/components/page-actions.tsx | 16 +- src/components/page-footer.test.tsx | 2 - src/components/page-footer.tsx | 8 +- src/components/page-header.tsx | 9 +- .../page-table-of-contents.test.tsx | 3 +- src/components/page-table-of-contents.tsx | 4 +- src/components/pointer-focus.tsx | 10 +- src/components/search-dialog.tsx | 14 +- src/components/section-nav.tsx | 28 +- src/components/sidebar-sections.test.tsx | 1 - src/components/sidebar-sections.tsx | 10 +- src/components/site-header.tsx | 8 +- src/components/steps.test.tsx | 4 - src/components/steps.tsx | 28 +- src/components/theme-switch.tsx | 6 +- src/entries.test.ts | 9 +- src/lib/accept.ts | 9 +- src/lib/analytics.test.ts | 40 +-- src/lib/analytics.ts | 110 ++----- src/lib/build.ts | 45 +-- src/lib/canonical.ts | 14 +- src/lib/code-options.ts | 17 +- src/lib/docs-map.ts | 16 +- src/lib/http-status.ts | 3 - src/lib/inline-code.tsx | 8 +- src/lib/layout.tsx | 6 +- src/lib/llms.test.ts | 16 +- src/lib/llms.ts | 88 +----- src/lib/page-head.ts | 19 +- src/lib/page-limits-suite.ts | 6 +- src/lib/page-limits.test.ts | 16 +- src/lib/page-limits.ts | 114 ++----- src/lib/search-results.ts | 22 +- src/lib/search.test.ts | 8 +- src/lib/search.ts | 237 ++++---------- src/lib/sidebar-label.test.ts | 2 - src/lib/sidebar-label.ts | 14 +- src/lib/sitemap.ts | 9 +- src/lib/source.test.ts | 1 - src/lib/source.ts | 37 +-- src/lib/table-labels.ts | 26 +- src/lib/translations.test.ts | 3 +- src/lib/translations.ts | 6 +- src/lib/worker.test.ts | 9 +- src/lib/worker.ts | 57 +--- src/styles.test.ts | 10 +- src/test/fake-source.ts | 4 - styles.css | 283 ++++------------- 70 files changed, 918 insertions(+), 1355 deletions(-) create mode 100644 scripts/check-comments.mjs create mode 100644 scripts/check-comments.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88dc90f..f74eda6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,14 +1,7 @@ -# The kit is small, so one job type-checks, tests, builds and packs it. Two -# sites build on it, which is why the pack check matters: it runs `pnpm pack` -# and reads the tarball, so a file missing from the published package fails -# here and not in a consumer's build. -# +# The pack check fails a file missing from the published package here, not in a consumer's build. # `Full CI` is the one required check, a roll-up of the jobs below. -# -# A run that Dependabot starts is held: every job a pull request can start is -# skipped, so it uses no runner, and no `Full CI` is reported, so the required -# check stays expected and blocks a merge. To opt a pull request in, start a run yourself with `gh pr ready --undo && gh pr ready `, or -# push to its branch. Rerunning a held run keeps Dependabot as the actor. +# A run that Dependabot starts is held: its jobs are skipped and no `Full CI` is reported, so the required check blocks the merge (`AGENTS.md` says how to start one). +# Rerunning a held run keeps Dependabot as the actor. name: CI on: @@ -21,12 +14,8 @@ on: workflow_dispatch: concurrency: - # A push to `main` or a manual run gets a group of its own, so a later push - # never cancels the verdict on a commit; only a pull request's run is - # superseded. A draft and a ready pull request have groups of their own: a - # draft pushed and marked ready a moment later starts two runs, and in one - # group the later queued run cancels the other, which can leave `Full CI` - # unreported. + # Only a pull request's run is superseded. A draft and a ready pull request have groups of their own: a draft marked ready + # a moment after a push starts two runs, and in one group the later queued run cancels the other, which can leave `Full CI` unreported. group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event_name == 'pull_request' && format('{0}-{1}', github.ref, github.event.pull_request.draft && 'draft' || 'ready') || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} @@ -42,6 +31,7 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + fetch-depth: 0 persist-credentials: false - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: @@ -51,6 +41,12 @@ jobs: node-version: 22 cache: pnpm + - if: ${{ github.event_name == 'pull_request' }} + run: node scripts/check-comments.mjs + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + - run: node --test scripts/check-comments.test.mjs - run: pnpm install --frozen-lockfile - run: pnpm types:check - run: pnpm test @@ -58,12 +54,8 @@ jobs: - run: pnpm build - run: pnpm pack:check - # The one required check. A skipped job satisfies a required check, so this - # job turns the result of the others into one verdict. On a draft it is named - # `Draft CI`, so the required `Full CI` stays expected, which blocks a merge, - # until the run that marking the pull request ready starts has finished. It - # runs after a failed job and fails then; a cancelled run skips it, and a - # skipped job never reports as `Full CI`, so a cancel cannot leave it green. + # A skipped job satisfies a required check, so this turns the others' results into one verdict. On a draft it is named `Draft CI`, + # so `Full CI` stays expected until the run that marking ready starts has finished. A cancelled run skips it, and a skipped job never reports as `Full CI`. gate: name: ${{ github.event_name == 'pull_request' && github.actor == 'dependabot[bot]' && 'Held CI' || (github.event.pull_request.draft && 'Draft CI' || 'Full CI') }} needs: [build] diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index dffcef7..7830d1b 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,10 +1,6 @@ name: CodeQL -# A pull request or a push to `main` that changes only documentation or agent -# instructions starts no run. CodeQL is not a required check, so a run that -# never starts leaves no check pending. A draft pull request is analyzed once -# it is marked ready for review, and on every push after that. A weekly run -# analyzes the whole tree. +# A change to only documentation or agent instructions starts no run, which is fine because CodeQL is not a required check. A draft is analyzed once marked ready. on: push: branches: [main] @@ -34,9 +30,7 @@ on: - cron: "41 4 * * 1" concurrency: - # A draft and a ready pull request have groups of their own, so a draft's - # run, queued a moment after the ready one, never cancels it. A push to - # `main` gets a group of its own, so a later push never cancels its run. + # A draft and a ready pull request have groups of their own, so a draft's queued run never cancels the ready one. A push to `main` has its own too. group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event_name == 'pull_request' && format('{0}-{1}', github.ref, github.event.pull_request.draft && 'draft' || 'ready') || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} @@ -46,8 +40,7 @@ permissions: jobs: analyze: name: Analyze (${{ matrix.language }}) - # Public repositories can scan without a paid Code Security license. A run - # that Dependabot starts on a pull request is held, as `ci.yml` says. + # Public repositories scan without a paid license. A run Dependabot starts is held, as `ci.yml` says. if: ${{ !(github.event_name == 'pull_request' && github.actor == 'dependabot[bot]') && github.event.repository.private == false && !github.event.pull_request.draft }} runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.github/workflows/pr-description.yml b/.github/workflows/pr-description.yml index e3d6ea7..781ad9e 100644 --- a/.github/workflows/pr-description.yml +++ b/.github/workflows/pr-description.yml @@ -1,8 +1,6 @@ name: Pull request description -# GitHub cannot require the pull request template, and a body passed from the -# command line skips it, so this check does. It is its own workflow so that -# editing a description reruns only this and never `ci.yml`. +# Its own workflow, so editing a description reruns only this and never `ci.yml`. on: pull_request: branches: [main] @@ -18,8 +16,7 @@ permissions: jobs: description: name: Pull request description - # A skipped job satisfies a required check, so a bot's pull request - # (Dependabot and the like) passes without a description. + # A skipped job satisfies a required check, so a bot's pull request passes without a description. if: ${{ github.event.pull_request.user.type != 'Bot' }} runs-on: ubuntu-latest timeout-minutes: 2 @@ -32,5 +29,4 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 - # The body is read from the event file, never put on a command line. - run: node scripts/check-pr-description.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6df240f..1e8dba3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,13 +1,6 @@ -# Publishes a version. Push a tag `v` that matches `package.json`: -# the workflow builds the package, attaches the tarball to a GitHub release, -# and publishes it to npm. -# -# The GitHub release comes first and is the install source until npm has the -# package: a site depends on the release's tarball URL. npm publishes with -# trusted publishing (OIDC), so no token is stored. The first version of a -# package cannot be published that way, because trusted publishing is set up -# on a package that exists, so the first version is published by hand and the -# `publish` job skips a version npm already has. +# Push a tag `v` that matches `package.json`. +# The GitHub release comes first and is a site's install source until npm has the package. Trusted publishing is set up on an existing package, +# so a package's first version is published by hand, and the `publish` job skips a version npm already has. name: Release on: @@ -68,7 +61,6 @@ jobs: path: ${{ runner.temp }}/pack/*.tgz if-no-files-found: error - # A version with a hyphen (`0.0.1-alpha.0`) is a prerelease. - name: Create the GitHub release env: GH_TOKEN: ${{ github.token }} @@ -112,7 +104,6 @@ jobs: echo "@withmarfa/docs-kit@${VERSION} is already on npm, so there is nothing to publish." exit 0 fi - # A prerelease takes `latest` while npm has no stable version, so # `latest` never points at an older prerelease. current="$(npm view @withmarfa/docs-kit dist-tags.latest 2>/dev/null || true)" case "${VERSION}" in diff --git a/scripts/check-comments.mjs b/scripts/check-comments.mjs new file mode 100644 index 0000000..e0a8ed6 --- /dev/null +++ b/scripts/check-comments.mjs @@ -0,0 +1,283 @@ +// Fails when a line a change adds carries a whole-line comment the repository's comment rule bans. +// +// BASE= HEAD= node scripts/check-comments.mjs in CI: the lines added from BASE to HEAD +// node scripts/check-comments.mjs --all every line of the checked files counts as added +// +// Banned: our own issue or pull request numbers, the two markers for work left undone, and the two phrases that describe history, +// and a TSDoc paragraph of more than four prose lines. The cases are in `check-comments.test.mjs`. +// A `#` and three or four digits passes only as a hex colour: after a colour word, or in CSS as a declaration value. A trailing comment is not read. +import { execFileSync, spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' + +const limit = 4 +const suffix = + 'Put the reason in the pull request or an issue, or delete the comment.' + +const slashKinds = /\.(?:[cm]?[jt]sx?|css)$/ +const hashKinds = /\.(?:ya?ml|sh|bash|py)$/ + +export function isChecked(path) { + if (!slashKinds.test(path) && !hashKinds.test(path)) return false + return !( + path.endsWith('routeTree.gen.ts') || + /(^|\/)(dist|node_modules|_local|\.claude|\.codex|\.agents)\//.test(path) + ) +} + +const issueNumber = /(^|[^A-Za-z0-9_./-])#([0-9]{1,5})(?=[^0-9A-Za-z_]|$)/g +const prefixedNumber = /(?:^|[^A-Za-z0-9_])(?:PR|GH|issue|pull)#[0-9]{1,5}\b/i +// A colour word, then the `#`, as in `colour`, `hex:` or `rgb(` before it. Nothing else makes three or four digits a colour. +const colourBefore = + /(?:colou?rs?|hex|rgba?|hsla?)(?:\s*[:=(]|\s+(?:is|of|as|to|was))?\s*[`'"]?$/i +// In CSS, a declaration value or a function argument that a `;`, `,`, `)` or `}` ends also reads as a colour. +const cssValueBefore = /(?:[a-z-]+\s*:|[a-z-]+\([^()]*)\s*$/i + +function isColour(before, after, path) { + return ( + colourBefore.test(before) || + (path.endsWith('.css') && + cssValueBefore.test(before) && + /^\s*[;,)}]/.test(after)) + ) +} + +function namesOurIssue(text, path) { + if ( + /withmarfa\/[A-Za-z0-9._-]+#[0-9]/.test(text) || + /github\.com\/withmarfa\/[^ ]*\/(issues|pull)\/[0-9]/.test(text) || + prefixedNumber.test(text) + ) + return true + for (const match of text.matchAll(issueNumber)) { + const digits = match[2] + const start = match.index + match[1].length + const before = text.slice(0, start) + const after = text.slice(start + 1 + digits.length) + if ([3, 4].includes(digits.length) && isColour(before, after, path)) + continue + return true + } + return false +} + +// Returns [line, reason] pairs for the lines in `added` (a Set, or null for every line). +export function check(path, content, added) { + const slash = slashKinds.test(path) + const found = [] + const isAdded = (n) => added === null || added.has(n) + const lines = content.split('\n') + if (lines.at(-1) === '') lines.pop() + + let inBlock = false + let blockIsDoc = false + let paragraph = 0 + let first = 0 + let inList = false + let inTag = false + let fence = false + const endParagraph = () => { + if (paragraph > limit && first > 0) + found.push([ + first, + `This doc paragraph is ${paragraph} lines long, and the most it may be is ${limit}.`, + ]) + paragraph = 0 + first = 0 + } + const docLine = (n, body) => { + const trimmed = body.trim() + if (trimmed === '') { + endParagraph() + inList = false + inTag = false + return + } + if (trimmed.startsWith('```')) { + endParagraph() + inList = false + fence = !fence + return + } + if (fence) return + if (/^@\w/.test(trimmed) || /^(?:[-*+]|\d+[.)])(?:\s|$)/.test(trimmed)) { + endParagraph() + inTag = trimmed.startsWith('@') + inList = !inTag + return + } + if ((inList || inTag) && /^\s\s+/.test(body)) return + if (inTag) return + inList = false + paragraph++ + if (first === 0 && isAdded(n)) first = n + } + const leaveDoc = () => { + endParagraph() + inList = false + inTag = false + fence = false + } + + lines.forEach((line, index) => { + const n = index + 1 + const trimmed = line.trim() + let text = null + let doc = null + + if (slash) { + if (inBlock) { + text = trimmed + if (blockIsDoc) + doc = trimmed.replace(/^\*(?!\/)/, '').replace(/\*\/\s*$/, '') + if (trimmed.includes('*/')) inBlock = false + } else if (trimmed.startsWith('/*')) { + text = trimmed + blockIsDoc = trimmed.startsWith('/**') && !trimmed.startsWith('/**/') + if (blockIsDoc) + doc = trimmed.replace(/^\/\*\*/, '').replace(/\*\/\s*$/, '') + inBlock = !trimmed.slice(2).includes('*/') + } else if (trimmed.startsWith('//')) { + text = trimmed + } + } else if ( + trimmed.startsWith('#') && + !(n === 1 && trimmed.startsWith('#!')) + ) { + text = trimmed + } + + if (text === null) { + leaveDoc() + return + } + if (isAdded(n)) { + const body = text.replace(/^(\/+\*{0,2}|#+|\*+)/, '') + if (namesOurIssue(body, path)) + found.push([ + n, + 'This comment names one of our issues or pull requests.', + ]) + else if (/(^|[^A-Za-z0-9_])(TODO|FIXME)([^A-Za-z0-9_]|$)/.test(body)) + found.push([n, 'This comment holds a TODO or FIXME.']) + else if ( + /(^|[^a-z])(previously|used to be)([^a-z]|$)/.test(body.toLowerCase()) + ) + found.push([n, 'This comment says what the code did before.']) + } + if (doc !== null) docLine(n, doc) + else leaveDoc() + }) + endParagraph() + return found +} + +function git(args) { + return execFileSync('git', ['-c', 'core.quotePath=false', ...args], { + encoding: 'utf8', + maxBuffer: 1 << 28, + stdio: ['ignore', 'pipe', 'ignore'], + }) +} + +function tryGit(args) { + try { + return git(args) + } catch { + return null + } +} + +// Maps each path to the Set of new-file line numbers a unified diff with no context adds. +// A hunk's own lines are counted off, so an added line such as `++ x` after a removed `-- y` is not read as a file header. +export function addedLines(diff) { + const files = new Map() + let path = null + let previous = '' + let lines = null + let oldLeft = 0 + let newLeft = 0 + for (const line of diff.split('\n')) { + if (oldLeft > 0 || newLeft > 0) { + if (line.startsWith('-')) oldLeft-- + else if (line.startsWith('+')) newLeft-- + } else if (line.startsWith('+++ ') && previous.startsWith('--- ')) { + const target = line.slice(4).split('\t')[0] + path = target === '/dev/null' ? null : target.replace(/^b\//, '') + lines = path === null ? null : (files.get(path) ?? new Set()) + if (path !== null) files.set(path, lines) + } else if (line.startsWith('@@ ')) { + const match = /^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line) + oldLeft = match[1] === undefined ? 1 : Number(match[1]) + newLeft = match[3] === undefined ? 1 : Number(match[3]) + if (path !== null) { + const start = Number(match[2]) + for (let i = 0; i < newLeft; i++) lines.add(start + i) + } + } + previous = line + } + return files +} + +function main() { + const head = process.env.HEAD || 'HEAD' + let targets = [] + + if (process.argv.includes('--all')) { + const listing = tryGit(['ls-tree', '-r', '--name-only', head]) + if (listing === null) { + console.error(`check-comments: cannot list the files at ${head}.`) + return 2 + } + targets = listing + .split('\n') + .filter(Boolean) + .map((path) => [path, null]) + } else { + const base = process.env.BASE || '' + if (base === '' || /^0+$/.test(base)) { + console.log( + 'check-comments: no base commit, so no added line was checked.', + ) + return 0 + } + const has = () => tryGit(['cat-file', '-e', `${base}^{commit}`]) !== null + if (!has()) + spawnSync( + 'git', + ['fetch', '--quiet', '--no-tags', '--depth=1', 'origin', base], + { stdio: 'ignore' }, + ) + if (!has()) { + console.log( + `check-comments: the base commit ${base} is not available, so no added line was checked.`, + ) + return 0 + } + const diff = + tryGit(['diff', '-U0', '--no-color', `${base}...${head}`, '--']) ?? + tryGit(['diff', '-U0', '--no-color', base, head, '--']) + if (diff === null) { + console.error( + `check-comments: cannot read the diff from ${base} to ${head}, so no added line was checked.`, + ) + return 2 + } + targets = [...addedLines(diff)] + } + + let status = 0 + for (const [path, added] of targets) { + if (!isChecked(path)) continue + const content = tryGit(['show', `${head}:${path}`]) + if (content === null) continue + for (const [line, reason] of check(path, content, added)) { + console.log(`::error file=${path},line=${line}::${reason} ${suffix}`) + status = 1 + } + } + return status +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) + process.exitCode = main() diff --git a/scripts/check-comments.test.mjs b/scripts/check-comments.test.mjs new file mode 100644 index 0000000..a7f7a98 --- /dev/null +++ b/scripts/check-comments.test.mjs @@ -0,0 +1,294 @@ +import assert from 'node:assert/strict' +import { execFileSync, spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const script = join( + dirname(fileURLToPath(import.meta.url)), + 'check-comments.mjs', +) +const dir = mkdtempSync(join(tmpdir(), 'check-comments-')) +test.after(() => rmSync(dir, { recursive: true, force: true })) + +// A fixture writes "@" for "/", "%" for "#" and "{at}" for "@", so no line of this file is itself a comment. +const fixture = (text) => + text.replaceAll('@', '/').replaceAll('%', '#').replaceAll('{at}', '@') + +let counter = 0 +const git = (repo, ...args) => + execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8' }).trim() + +function repository() { + const repo = join(dir, `repo-${counter++}`) + mkdirSync(repo) + git(repo, 'init', '-q') + git(repo, 'config', 'user.email', 'test@example.invalid') + git(repo, 'config', 'user.name', 'test') + return repo +} + +function commit(repo, files) { + for (const [path, content] of Object.entries(files)) { + mkdirSync(dirname(join(repo, path)), { recursive: true }) + writeFileSync(join(repo, path), `${fixture(content)}\n`) + } + git(repo, 'add', '-A') + git(repo, 'commit', '-q', '-m', 'change') +} + +function run(repo, { env = {}, args = [] } = {}) { + const result = spawnSync('node', [script, ...args], { + cwd: repo, + encoding: 'utf8', + env: { ...process.env, BASE: '', HEAD: '', ...env }, + }) + const flagged = [ + ...result.stdout.matchAll(/^::error file=([^,]*),line=(\d+)::/gm), + ].map((match) => `${match[1]}:${match[2]}`) + return { status: result.status, flagged, out: result.stdout + result.stderr } +} + +// The lines the last commit added: a base commit with one code line, then the content. +function verdict(path, content) { + const repo = repository() + commit(repo, { [path]: 'const base = 1' }) + const base = git(repo, 'rev-parse', 'HEAD') + commit(repo, { [path]: content }) + const { flagged, status } = run(repo, { + env: { BASE: base, HEAD: git(repo, 'rev-parse', 'HEAD') }, + }) + return { flagged, status } +} + +const cases = [ + [ + 'an issue number in a line comment', + 'a.ts', + '@@ fixes %123\nconst x = 1', + ['a.ts:1'], + ], + [ + 'an issue number in a block comment', + 'a.ts', + '@* one\n * see %1234\n */', + ['a.ts:2'], + ], + [ + 'an organisation issue reference', + 'a.ts', + '@@ see withmarfa/docs-kit%12', + ['a.ts:1'], + ], + [ + 'an issue link', + 'a.ts', + '@@ https://github.com/withmarfa/docs-kit/issues/12', + ['a.ts:1'], + ], + [ + 'a pull request link in YAML', + 'a.yml', + '% https://github.com/withmarfa/docs-kit/pull/9', + ['a.yml:1'], + ], + [ + 'an outside bug link', + 'a.ts', + '@@ https://bugs.webkit.org/show_bug.cgi?id=123456', + [], + ], + [ + 'a hex colour next to a colour word', + 'a.ts', + '@@ the colour %000 on black', + [], + ], + ['a hex colour after a colon', 'a.ts', '@@ hex: %1234', []], + ['a hex colour in a function', 'a.ts', '@@ rgb(%123)', []], + ['a quoted hex colour', 'a.ts', '@@ the colour `%123`', []], + [ + 'an issue number is not a colour for the text', + 'a.ts', + '@@ see %123 for the text', + ['a.ts:1'], + ], + [ + 'a number next to border is an issue', + 'a.ts', + '@@ the border %123', + ['a.ts:1'], + ], + [ + 'a number next to theme is an issue', + 'a.ts', + '@@ see %1234 for the theme', + ['a.ts:1'], + ], + [ + 'a number next to hex but not after it', + 'a.ts', + '@@ %123 is not a hex', + ['a.ts:1'], + ], + [ + 'a colour and then an issue in one line', + 'a.ts', + '@@ colour %123, also %456', + ['a.ts:1'], + ], + ['a hex colour with letters', 'a.ts', '@@ use %ff0000', []], + ['a hex colour in a CSS declaration', 'a.css', '@* accent: %111; *@', []], + ['a hex colour in a CSS function', 'a.css', '@* mix(%111, %222) *@', []], + ['a bare number in CSS is an issue', 'a.css', '@* see %123 *@', ['a.css:1']], + [ + 'a number in parentheses in CSS', + 'a.css', + '@* fixes (see %123) *@', + ['a.css:1'], + ], + ['a bare number in CSS prose', 'a.css', '@* %111 *@', ['a.css:1']], + ['a prefixed pull request number', 'a.ts', '@@ see PR%123', ['a.ts:1']], + ['a prefixed issue number', 'a.ts', '@@ issue%9', ['a.ts:1']], + ['a number in a string', 'a.ts', "const id = '%123'", []], + ['a TODO', 'a.mjs', '@@ TODO later', ['a.mjs:1']], + ['a FIXME in shell', 'a.sh', '% FIXME', ['a.sh:1']], + ['a lower-case todo word', 'a.ts', '@@ a todo list', []], + ['the word previously', 'a.ts', '@@ Previously this did x', ['a.ts:1']], + ['used to be', 'a.py', '% used to be slower', ['a.py:1']], + ['no longer is allowed', 'a.ts', '@@ no longer needed', []], + ['a shebang', 'a.sh', '%!/usr/bin/env bash', []], + ['a trailing comment', 'a.ts', 'const x = 1 @@ TODO', []], + [ + 'a five-line TSDoc paragraph', + 'a.ts', + '@**\n * one\n * two\n * three\n * four\n * five\n */', + ['a.ts:2'], + ], + [ + 'a four-line TSDoc paragraph', + 'a.ts', + '@**\n * one\n * two\n * three\n * four\n */', + [], + ], + [ + 'paragraphs split by a blank line', + 'a.ts', + '@**\n * one\n * two\n * three\n *\n * four\n * five\n * six\n */', + [], + ], + [ + 'a list and tags are not paragraph lines', + 'a.ts', + '@**\n * Summary.\n *\n * - a\n * - b\n * - c\n * - d\n * - e\n * {at}param x one\n * two\n * three\n * four\n * five\n * {at}returns six\n */', + [], + ], + [ + 'a code fence is not a paragraph', + 'a.ts', + '@**\n * ```ts\n * a\n * b\n * c\n * d\n * e\n * ```\n */', + [], + ], + [ + 'a five-line plain block comment', + 'a.ts', + '@*\n one\n two\n three\n four\n five\n */', + [], + ], + [ + 'a long run of // lines in TypeScript', + 'a.ts', + '@@ one\n@@ two\n@@ three\n@@ four\n@@ five\n@@ six', + [], + ], + [ + 'a star list line in a template string', + 'a.ts', + 'const s = `\n* see %123\n`', + [], + ], + ['a generated file', 'site/src/routeTree.gen.ts', '@@ TODO', []], + ['a built file', 'dist/a.js', '@@ TODO', []], + ['Markdown', 'a.md', '\n@@ TODO', []], + ['an agent file', '.claude/a.ts', '@@ TODO', []], +] + +for (const [name, path, content, expected] of cases) + test(name, () => { + const { flagged, status } = verdict(path, content) + assert.deepEqual(flagged, expected) + assert.equal(status, expected.length > 0 ? 1 : 0) + }) + +test('only added lines are checked', () => { + const repo = repository() + commit(repo, { 'a.ts': '@@ TODO old\nconst x = 1' }) + const base = git(repo, 'rev-parse', 'HEAD') + commit(repo, { 'a.ts': '@@ TODO old\nconst x = 2\n@@ TODO new' }) + const { flagged } = run(repo, { + env: { BASE: base, HEAD: git(repo, 'rev-parse', 'HEAD') }, + }) + assert.deepEqual(flagged, ['a.ts:3']) +}) + +test('--all checks every line', () => { + const repo = repository() + commit(repo, { 'a.ts': '@@ TODO old\nconst x = 1' }) + assert.deepEqual(run(repo, { args: ['--all'] }).flagged, ['a.ts:1']) +}) + +test('a renamed file reports its own added lines', () => { + const repo = repository() + commit(repo, { 'a.ts': 'const x = 1\nconst y = 2\nconst z = 3\nconst w = 4' }) + const base = git(repo, 'rev-parse', 'HEAD') + git(repo, 'mv', 'a.ts', 'b.ts') + commit(repo, { + 'b.ts': 'const x = 1\nconst y = 2\n@@ TODO\nconst z = 3\nconst w = 4', + }) + const { flagged } = run(repo, { + env: { BASE: base, HEAD: git(repo, 'rev-parse', 'HEAD') }, + }) + assert.deepEqual(flagged, ['b.ts:3']) +}) + +test('an added line that looks like a file header keeps the file', () => { + const repo = repository() + commit(repo, { 'a.ts': '-- old\nconst x = 1\nconst y = 2' }) + const base = git(repo, 'rev-parse', 'HEAD') + commit(repo, { 'a.ts': '++ new\nconst x = 1\nconst y = 2\n@@ TODO' }) + const { flagged } = run(repo, { + env: { BASE: base, HEAD: git(repo, 'rev-parse', 'HEAD') }, + }) + assert.deepEqual(flagged, ['a.ts:4']) +}) + +test('with no base it passes and says so', () => { + const repo = repository() + commit(repo, { 'a.ts': '@@ TODO' }) + for (const base of ['', '0000000000000000000000000000000000000000']) { + const { status, out } = run(repo, { env: { BASE: base } }) + assert.equal(status, 0) + assert.match(out, /no base commit/) + } +}) + +test('with a base it cannot fetch it passes and says so', () => { + const repo = repository() + commit(repo, { 'a.ts': '@@ TODO' }) + const { status, out } = run(repo, { env: { BASE: 'f'.repeat(40) } }) + assert.equal(status, 0) + assert.match(out, /is not available/) +}) + +test('an unreadable diff fails', () => { + const repo = repository() + commit(repo, { 'a.ts': 'const x = 1' }) + const base = git(repo, 'rev-parse', 'HEAD') + const { status, out } = run(repo, { + env: { BASE: base, HEAD: 'no-such-ref' }, + }) + assert.equal(status, 2) + assert.match(out, /cannot read the diff/) +}) diff --git a/scripts/check-pack.ts b/scripts/check-pack.ts index 489b012..189a1bf 100644 --- a/scripts/check-pack.ts +++ b/scripts/check-pack.ts @@ -1,8 +1,5 @@ -/** - * Checks the package as it will be published: what `pnpm pack` puts in the - * tarball, that every path `exports` names is in it, and that the built code - * imports only what `package.json` declares. Run it after `pnpm build`. - */ +// Checks the package as published: the tarball's files, every path `exports` names, and the built code's imports. Run it after `pnpm build`. + import { execFileSync } from "node:child_process"; import { builtinModules } from "node:module"; import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; @@ -29,7 +26,6 @@ try { .map((line) => line.replace(/^package\//, "")); const have = new Set(entries); - // Only the build, the stylesheet and the package's own files ship. const allowed = /^(dist\/|package\.json$|README\.md$|LICENSE$|styles\.css$)/; for (const entry of entries) { if (!allowed.test(entry)) problems.push(`The tarball holds ${entry}, which does not ship.`); @@ -38,7 +34,6 @@ try { if (!have.has(required)) problems.push(`The tarball has no ${required}.`); } - // Every file `exports` names is in the tarball. for (const [subpath, target] of Object.entries(pkg.exports)) { const files = typeof target === "string" ? [target] : Object.values(target); for (const file of files) { @@ -46,14 +41,13 @@ try { } } - // The built code imports only what the package declares, or Node. const declared = new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.peerDependencies ?? {})]); const builtins = new Set(builtinModules.flatMap((name) => [name, `node:${name}`])); const packageOf = (specifier: string) => specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0]; for (const entry of entries.filter((name) => /^dist\/.*\.js$/.test(name))) { const code = execFileSync("tar", ["-xzOf", join(dir, tarball), `package/${entry}`], { encoding: "utf8" }); - // Comments show example imports, which are not the package's own. + // Comments show example imports. const source = code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, ""); for (const match of source.matchAll(/\bfrom\s+["']([^"']+)["'];|\bimport\(\s*["']([^"']+)["']\s*\)|^import\s+["']([^"']+)["'];/gm)) { const specifier = match[1] ?? match[2] ?? match[3]; diff --git a/scripts/check-pr-description.ts b/scripts/check-pr-description.ts index 039c01b..ae0d7e4 100644 --- a/scripts/check-pr-description.ts +++ b/scripts/check-pr-description.ts @@ -1,16 +1,9 @@ -/** - * Whether a pull request's description follows the organization's template - * (`.github/PULL_REQUEST_TEMPLATE.md` in withmarfa/.github). - * - * A pull request opened from the command line with `--body` skips the - * template, and GitHub cannot require one, so `pr-description.yml` runs this - * and fails the check. The body is untrusted input: it is read from the - * event file and never reaches a shell. - */ +// Whether a pull request's description follows the organization's template (`.github/PULL_REQUEST_TEMPLATE.md` in withmarfa/.github). +// The body is untrusted input: it is read from the event file and never reaches a shell. + import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; -/** The template's sections, in order. */ export const SECTIONS = [ "Summary", "Changes", @@ -19,10 +12,9 @@ export const SECTIONS = [ "Checklist", ] as const; -/** Sections that must say something; the others only have to be present. */ +// The other sections only have to be present. const FILLED: readonly string[] = ["Summary", "Changes", "Testing"]; -/** What the template puts under a heading, which says nothing. */ function hasContent(text: string): boolean { return text.split("\n").some((line) => { const trimmed = line.trim(); @@ -30,7 +22,6 @@ function hasContent(text: string): boolean { }); } -/** The problems with a description, empty when it follows the template. */ export function checkDescription(body: string | null | undefined): string[] { // An unclosed comment hides the rest of the page when GitHub renders it. const text = (body ?? "") diff --git a/src/components/analytics.test.tsx b/src/components/analytics.test.tsx index dc12eb8..62cf8e9 100644 --- a/src/components/analytics.test.tsx +++ b/src/components/analytics.test.tsx @@ -11,7 +11,7 @@ vi.mock('posthog-js', () => { return { default: posthog }; }); -// The component keeps "started" in module state, so each case takes a fresh copy. +// `started` is module state, so each case takes a fresh copy. async function mount(props: { site: string; posthogKey?: string }) { const { Analytics } = await import('./analytics'); const container = document.createElement('div'); @@ -20,7 +20,6 @@ async function mount(props: { site: string; posthogKey?: string }) { await act(async () => { root.render(createElement(Analytics, props)); }); - // The SDK arrives by a dynamic import, after the first render. await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); @@ -60,7 +59,7 @@ describe('Analytics', () => { expect(posthog.init.mock.calls[0][1]).toMatchObject({ cookieless_mode: 'always', persistence: 'memory' }); expect(posthog.register).toHaveBeenCalledWith({ site: 'docs' }); expect(first.container.innerHTML).toBe(''); - // A second mount, as React's development double effect does, starts nothing more. + // React's development double effect. const second = await mount({ site: 'docs', posthogKey: 'phc_test' }); expect(posthog.init).toHaveBeenCalledTimes(1); await first.unmount(); diff --git a/src/components/analytics.tsx b/src/components/analytics.tsx index 4a83809..e0769b2 100644 --- a/src/components/analytics.tsx +++ b/src/components/analytics.tsx @@ -2,31 +2,17 @@ import { useEffect } from 'react'; import { posthogOptions, setClient, siteProperties, type AnalyticsSite } from '../lib/analytics'; /** - * Loads PostHog, after the page is already up. - * - * **The deferral is the design, not an optimization.** A static import would - * put the SDK in the entry chunk, on the critical path, where a slow fetch or - * a parse error becomes the page's problem. The SDK is fetched in its own - * chunk once the document has rendered and hydrated. If PostHog is unreachable - * the import rejects, it is caught, and nothing about the page changes. - * - * Renders nothing, ever, on either side of hydration. + * Loads PostHog in its own chunk after hydration, never in the entry chunk: a slow fetch or a parse error must not become the page's problem. + * Renders nothing. */ -/** - * Module scope rather than component state, because React runs effects twice - * in development and `init` is not idempotent. - */ +// Module scope: React runs effects twice in development and `init` is not idempotent. + let started = false; -/** - * `posthogKey` is the project's public key, which the site's build supplies. - * Without one nothing loads and nothing is reported: a fork builds that way. - * `site` is sent on every event, so one PostHog project can tell sites apart. - */ +/** `posthogKey` is the project's public key. Without one nothing loads. `site` is sent on every event. */ export function Analytics({ site, posthogKey }: { site: AnalyticsSite; posthogKey?: string }) { useEffect(() => { - // No key, no analytics, no complaint. if (!posthogKey || started) return; started = true; @@ -37,8 +23,7 @@ export function Analytics({ site, posthogKey }: { site: AnalyticsSite; posthogKe setClient(posthog); }) .catch(() => { - // Deliberately silent. Analytics failing to load is not something to - // tell a reader about, and it must not become an error of its own. + // Silent: a failed load must not become an error of its own. started = false; }); }, [site, posthogKey]); diff --git a/src/components/callout.tsx b/src/components/callout.tsx index a1c5b96..dc4d03c 100644 --- a/src/components/callout.tsx +++ b/src/components/callout.tsx @@ -1,10 +1,7 @@ import type { ComponentProps, ReactNode } from 'react'; import { cn } from '../lib/cn'; -// A callout is a soft tinted panel: a bold title in the tint's dark color, the -// body under it, no border, shadow or icon. The tint says what kind of note it -// is and the title says what happens. The colors are the `--docs-kit-callout-*` -// tokens in app.css, which other components reuse. +// The colors are the `--docs-kit-callout-*` tokens, which other components reuse. type CalloutType = 'info' | 'warn' | 'warning' | 'error' | 'success' | 'tip' | 'idea'; diff --git a/src/components/cards.tsx b/src/components/cards.tsx index f3bcb0a..a7b5f23 100644 --- a/src/components/cards.tsx +++ b/src/components/cards.tsx @@ -2,10 +2,7 @@ import Link from 'fumadocs-core/link'; import type { ComponentProps, ReactNode } from 'react'; import { cn } from '../lib/cn'; -// Fumadocs' Cards and Card with the same props, drawn as quiet tiles: a -// hairline border, a fill on hover instead of a shadow, and the title a step -// above the description. Its own versions fix the title at 14px and give the -// grid no margin, so the paragraph after it sat close against the cards. +// Fumadocs' own Cards fix the title at 14px and give the grid no margin, so the paragraph after it sat close against the cards. export function Cards({ className, ...props }: ComponentProps<'div'>) { return ( diff --git a/src/components/code-tabs.tsx b/src/components/code-tabs.tsx index 35e4907..790b897 100644 --- a/src/components/code-tabs.tsx +++ b/src/components/code-tabs.tsx @@ -2,11 +2,8 @@ import { CodeBlockTabs as Base } from 'fumadocs-ui/components/codeblock'; import { Children, isValidElement, useLayoutEffect, useMemo, useState, type ComponentProps } from 'react'; import { InCodeTabs } from './code'; -// Fumadocs' code tabs with a remembered choice that only applies where it -// exists. Its own version shares one choice across every tab set in a group, so -// choosing CLI on one page left a page with only HTTP and TypeScript tabs -// showing an empty panel. Here a set takes the group's choice only when it has -// a tab of that name, and otherwise keeps its own first tab. +// Fumadocs' code tabs share one choice across every tab set in a group, so choosing CLI on one page left a page with only +// HTTP and TypeScript tabs showing an empty panel. Here a set takes the group's choice only when it has a tab of that name. const EVENT = 'docs-kit-tab-group'; @@ -25,7 +22,7 @@ function write(groupId: string, value: string) { sessionStorage.setItem(groupId, value); localStorage.setItem(groupId, value); } catch { - // Storage can be blocked; the choice then lasts only for this page. + // Storage can be blocked. } } diff --git a/src/components/code.tsx b/src/components/code.tsx index 706cfc4..0bcee12 100644 --- a/src/components/code.tsx +++ b/src/components/code.tsx @@ -16,7 +16,7 @@ import { import { cn } from '../lib/cn'; import { statusLabel, statusTone } from '../lib/http-status'; -/** A code block, or a terminal body, taller than this folds to its first lines, with a button to show the rest. */ +/** Lines above which a code block or terminal body folds to its first lines. */ export const FOLD_AT = 24; /** True inside a code tab set, where the tabs are the block's header row. */ @@ -24,11 +24,7 @@ export const InCodeTabs = createContext(false); type Props = { className?: string; children?: ReactNode }; -/** - * The number of lines in a highlighted block. Shiki writes each line as a - * `span.line` inside the block's `code`, so this works the same on the server - * and in the browser, before anything is measured. - */ +/** The lines in a highlighted block, counted from Shiki's `span.line`s, so it works on the server before anything is measured. */ export function countLines(pre: ReactNode): number { if (!isValidElement(pre)) return 0; const code = Children.toArray(pre.props.children).find(isValidElement) as ReactElement | undefined; @@ -37,7 +33,6 @@ export function countLines(pre: ReactNode): number { ).length; } -/** What a fenced block's meta adds to the header: `title="Response" note="Server-sent events" status="200"`. */ type BlockProps = Omit, 'title'> & { title?: string; note?: string; @@ -46,7 +41,6 @@ type BlockProps = Omit, 'title'> & { icon?: unknown; }; -/** Stands in for an absent title when a note or status gives the header row something to hold. */ const NO_TITLE = <>; function Status({ code }: { code: string }) { @@ -58,12 +52,8 @@ function Status({ code }: { code: string }) { ); } -/** - * Copy, with the two-squares icon the page's Copy Markdown button uses; - * Fumadocs draws a clipboard. It reads the block's first `pre`, as Fumadocs - * does, so a terminal's output is left out, and writes `.nd-copy-ignore` - * spans as line breaks. - */ +// Reads the block's first `pre`, as Fumadocs does, so a terminal's output is left out, and writes `.nd-copy-ignore` spans as line breaks. + function CopyCode() { const button = useRef(null); const [checked, onClick] = useCopyButton(() => { @@ -91,12 +81,8 @@ function CopyCode() { ); } -/** - * The header's right-hand side: an optional note or status chip, then Copy. - * Fumadocs calls this where it draws its Copy button, so the extras sit - * in the same row without a header of our own. It also stands in for the - * button itself, which it draws when Fumadocs would have drawn its own. - */ +// Fumadocs calls this where it draws its Copy button, so the extras share the row, and it stands in for the button itself. + function actions(note: string | undefined, status: string | undefined) { return function Actions({ className, children }: ComponentProps<'div'>) { return ( @@ -109,13 +95,7 @@ function actions(note: string | undefined, status: string | undefined) { }; } -/** - * The `pre` of every Markdown code block: Fumadocs' code block under one - * header row, folded to its first lines when it is long, so a page doesn't - * open on a wall of code. The fold hides lines from view only; Copy and the - * Markdown copy take them all. In a code tab set the tabs are the header row - * and the stylesheet moves Copy into it. - */ +/** The `pre` of every Markdown code block, folded past `FOLD_AT` lines. The fold hides lines from view only: Copy and the Markdown copy take them all. */ export function FoldingCodeBlock({ title, note, status, icon: _icon, ...props }: BlockProps) { return ( | undefined { if (!isValidElement<{ children?: ReactNode }>(node)) return undefined; if (node.type === FoldingCodeBlock) return node as ReactElement; @@ -193,12 +172,7 @@ function findBlock(node: ReactNode): ReactElement | undefined { return undefined; } -/** - * A command and what it prints, as one block under a "Terminal" header: the - * command, then its output in muted text, and Copy takes the command only. - * Written in MDX as two fenced blocks inside ``. The whole body folds - * like any block, by its total number of lines. - */ +/** A command and its output as one block, written in MDX as two fenced blocks inside ``. Copy takes the command only. */ export function Terminal({ children }: { children: ReactNode }) { const [command, output] = Children.toArray(children).filter(isValidElement); const first = findBlock(command); diff --git a/src/components/docs-error.tsx b/src/components/docs-error.tsx index 66c7d48..e6f210d 100644 --- a/src/components/docs-error.tsx +++ b/src/components/docs-error.tsx @@ -17,10 +17,7 @@ export function DocsError({ primaryHref?: string; primaryLabel?: string; }) { - // The message is for whoever is debugging, and the console is where they - // will look. It does not belong in the response body. if (typeof console !== 'undefined') console.error(error); - // And to error tracking, which is the half nobody is watching. reportError(error); return ( diff --git a/src/components/docs-header.test.tsx b/src/components/docs-header.test.tsx index 3c43808..8073419 100644 --- a/src/components/docs-header.test.tsx +++ b/src/components/docs-header.test.tsx @@ -8,9 +8,7 @@ declare global { } globalThis.IS_REACT_ACT_ENVIRONMENT = true; -// The sidebar's state, trigger and drawer as Fumadocs draws them: the trigger -// is a button named for the state, and the open drawer holds a close button of -// its own that controls the same drawer, which the stylesheet hides. +// The open drawer holds a close button of its own, which the stylesheet hides. let setOpen: (open: boolean) => void = () => {}; let isOpen = false; vi.mock('fumadocs-ui/layouts/notebook', () => ({ diff --git a/src/components/docs-header.tsx b/src/components/docs-header.tsx index 81aa3cc..3457729 100644 --- a/src/components/docs-header.tsx +++ b/src/components/docs-header.tsx @@ -8,7 +8,6 @@ import { sidebarWithSections } from './sidebar-sections'; import { HeaderBar, IconLink, SearchButton, iconButton } from './site-header'; import { ThemeSwitch } from './theme-switch'; -/** An icon button in the top bar that links out of the site. */ export type HeaderLink = { label: string; href: string; icon: ReactNode }; /** What a site puts in its top bar. */ @@ -29,13 +28,6 @@ export type DocsHeaderSite = { extra?: ReactNode; }; -// The docs top bar, given to the notebook layout as its `header` slot. Owning -// it fixes the order and size of every control in one place, where the stock -// header placed the search box, the tab row and the theme switch itself and -// left them to be moved and hidden from CSS. -// -// The icon row drops what the screen can't hold: the links below 1024px, the -// appearance control below 768px, where the phone menu carries both. export function DocsHeader({ site, ...props }: ComponentProps<'header'> & { site: DocsHeaderSite }) { const { slots } = useNotebookLayout(); const sidebar = slots.sidebar; @@ -50,8 +42,7 @@ export function DocsHeader({ site, ...props }: ComponentProps<'header'> & { site {...props} className={cn( 'sticky top-(--fd-docs-row-1) z-10 bg-fd-background/80 backdrop-blur-sm [grid-area:header] layout:[--fd-header-height:--spacing(14)]', - // The open drawer starts under the bar and the bar stays, as on a landing page, so it rises above the drawer - // and its overlay (z-40) but stays under the search dialog (z-50), which opens from the bar's own button. + // Above the drawer and its overlay (z-40), under the search dialog (z-50) that the bar's own button opens. open && 'max-md:z-[45]', props.className, )} @@ -65,8 +56,7 @@ export function DocsHeader({ site, ...props }: ComponentProps<'header'> & { site actions={ {sidebar ? ( - // The drawer opens under the bar, so this button stays where it is and closes it. The drawer's own - // close button is hidden by `styles.css`, which leaves one control to announce. + // `styles.css` hides the drawer's own close button, which leaves one control to announce. {open ? : } @@ -80,11 +70,7 @@ export function DocsHeader({ site, ...props }: ComponentProps<'header'> & { site const DRAWER = '#nd-sidebar-mobile'; -// Focus follows the drawer, as it does in the landing menu: into it when it -// opens, to the current page or else the first link, and back to the menu -// button when it closes with focus still inside it or lost. The drawer mounts a -// frame after `open` changes, so the link is looked up then. Escape closes it -// from anywhere on the page; Fumadocs' own handler also closing it is harmless. +// The drawer mounts a frame after `open` changes, so the link is looked up then. Fumadocs' own Escape handler also closing it is harmless. function useDrawerFocus(open: boolean, toggle: RefObject, close: () => void) { const opened = useRef(false); const closeRef = useRef(close); @@ -115,8 +101,6 @@ function useDrawerFocus(open: boolean, toggle: RefObject @@ -133,8 +117,6 @@ export function DocsActions({ site, children }: { site: DocsHeaderSite; children ); } -// The same bar for a page outside the notebook layout, such as the 404 or a -// landing page. With no sidebar to carry the sections, its menu button does. export function DocsHomeHeader({ site, ...props }: ComponentProps<'header'> & { site: DocsHeaderSite }) { return (
& { } /** - * The header slots for one site, so a layout can take them as they are: - * `slots={{ ...layout.slots, header: DocsHeader }}`. Call it once, at module - * scope, so each slot keeps one identity. - * - * `sidebar` is the notebook layout's sidebar slot with the site's sections at - * the top of the phone drawer (and of the desktop sidebar below 1024px), where - * the top bar's pills are hidden. It is undefined for a site with no sections. - * Pass it as `slots.sidebar` and set `tabs={false}` on the layout, so the - * drawer lists the sections and not Fumadocs's tab dropdown as well. + * The header slots for one site: `slots={{ ...layout.slots, header: DocsHeader }}`. Call it once, at module scope, so each slot keeps one identity. + * `sidebar` is undefined for a site with no sections. Pass it as `slots.sidebar` and set `tabs={false}`, or the drawer also shows Fumadocs's tab dropdown. */ export function createDocsHeaders(site: DocsHeaderSite) { return { diff --git a/src/components/error-page.tsx b/src/components/error-page.tsx index 86bdb55..6c8f1b5 100644 --- a/src/components/error-page.tsx +++ b/src/components/error-page.tsx @@ -1,10 +1,5 @@ /** - * What a reader sees when a route throws. - * - * Without an `errorComponent` configured, TanStack Router renders its own, - * which prints the thrown message verbatim under a "Something went wrong!" - * heading. That can publish an internal name on a public page, which is neither - * useful to a reader nor ours to hand out. + * What a reader sees when a route throws. Without an `errorComponent`, TanStack Router prints the thrown message verbatim, which can publish an internal name. */ export function ErrorPage({ title = 'Something went wrong', @@ -29,12 +24,7 @@ export function ErrorPage({

{message}

- {/* - Real navigations rather than a reload handler. This component renders - inside a boundary that may itself have failed to hydrate, and an - anchor works with no JavaScript running at all. The primary action - comes first, and both are the size of a site's main buttons. - */} + {/* Anchors, not a reload handler: this renders inside a boundary that may have failed to hydrate. */} state.location.pathname }); @@ -26,9 +18,7 @@ export function HomeMenu({ site }: { site: DocsHeaderSite }) { useEffect(() => setOpen(false), [pathname]); - // Focus goes into the panel when it opens, and back to the button when it - // closes with focus still inside the panel or lost. A close that leaves - // focus somewhere else the person chose does not take it. + // A close that leaves focus somewhere the person chose does not take it back. const opened = useRef(false); useEffect(() => { if (open) { @@ -63,8 +53,7 @@ export function HomeMenu({ site }: { site: DocsHeaderSite }) { {open ? : } {open ? ( - // Absolute under the bar, not fixed: the header's backdrop blur makes it the containing block for fixed - // children, which would size the panel to the bar. + // Not fixed: the header's backdrop blur is the containing block for fixed children, which would size the panel to the bar.
{ - // The map is typed as an MDX map, where any entry may be missing or nested; a page uses these as components. const { Tabs, Tab, Steps, Step, TypeTable, Accordions, Accordion, Files, Folder, File, Terminal, table: Table, pre: Pre } = getDocsKitMDXComponents() as Record>; - // A fenced block as rehype-code hands it to `pre`: a `code` of `span.line`s. const block = (...lines: string[]) => (
       
diff --git a/src/components/mdx-components.tsx b/src/components/mdx-components.tsx
index 3581d05..801c672 100644
--- a/src/components/mdx-components.tsx
+++ b/src/components/mdx-components.tsx
@@ -12,14 +12,11 @@ import { FoldingCodeBlock, Terminal } from './code';
 import { CodeBlockTabs } from './code-tabs';
 import { Step, Steps } from './steps';
 
-// Fumadocs draws a file tree with a control's corner; this gives it the
-// container corner and spacing that Cards, Callout and paged steps use.
 function Files({ className, ...props }: ComponentProps) {
   return ;
 }
 
-// Fumadocs' table wrapper, named so the stylesheet can ask how wide the column
-// is, not the screen, when it decides to stack a table into entries.
+// Named so the stylesheet can ask how wide the column is, not the screen, when it stacks a table into entries.
 function Table(props: ComponentProps<'table'>) {
   return (
     
@@ -29,8 +26,7 @@ function Table(props: ComponentProps<'table'>) { } /** - * The components an MDX page can use without importing them. A site extends the - * map with its own, which win over the kit's of the same name: + * The components an MDX page can use without importing them. A site's own win over the kit's of the same name: * * ```tsx * export const getMDXComponents = (components?: MDXComponents) => diff --git a/src/components/not-found.tsx b/src/components/not-found.tsx index c68978c..c162d88 100644 --- a/src/components/not-found.tsx +++ b/src/components/not-found.tsx @@ -3,7 +3,6 @@ import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'; import type { ComponentProps, FC } from 'react'; import { ErrorPage } from './error-page'; -/** The layout an error page sits in: the site's base options and its header. */ export type ErrorLayout = { layout: BaseLayoutProps; header: FC>; @@ -11,8 +10,6 @@ export type ErrorLayout = { type NotFoundProps = ErrorLayout & Partial, 'title' | 'message' | 'primaryHref' | 'primaryLabel' | 'secondaryHref' | 'secondaryLabel'>>; -// The site's bar over a short message, in place of Fumadocs' default page, -// whose header placed its controls differently from every other page. export function NotFound({ layout, header, diff --git a/src/components/page-actions.tsx b/src/components/page-actions.tsx index 526daaa..f3fac3d 100644 --- a/src/components/page-actions.tsx +++ b/src/components/page-actions.tsx @@ -3,15 +3,8 @@ import { ViewOptionsPopover, } from 'fumadocs-ui/layouts/notebook/page'; -// A single split-button. The main part, "Copy Markdown", copies the page's -// Markdown; the attached chevron opens the same "open in…" / view-as-markdown -// options the standalone "Open" button used to carry. Passing an empty string -// as the popover's children strips its default "Open" label, leaving just the -// chevron. The button keeps its own label, which Fumadocs swaps to "Copied -// Markdown" inside a polite live region, so every width announces the result. -// On a phone the label is clipped out of sight, not removed: the button is as -// wide as its icon, the wide gap pushes the text past the clipped edge, and the -// text stays for screen readers. The title attribute names the icon on hover. +// An empty string as the popover's children strips its default "Open" label. On a phone the label is clipped out of sight, +// not removed, so it stays for screen readers. Fumadocs swaps the label to "Copied Markdown" inside a polite live region. export function PageActions({ markdownUrl, githubUrl, @@ -20,10 +13,7 @@ export function PageActions({ githubUrl?: string; }) { return ( - // One outline control, the console's: a hairline border, the control - // radius and a 32px height. No `overflow-hidden` on the wrapper, which - // would clip the halves' focus rings, so each half rounds its own outer - // corners, a pixel inside the border. + // No `overflow-hidden`, which would clip the halves' focus rings, so each half rounds its own outer corners.
; const trimSlash = (path: string) => path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path; -// The tree names a page by its `sidebar_label`, which is a name for the -// sidebar. The card names the page it leads to, so it shows the full title -// (`titles`, from `fullTitles`). A description is Markdown, and the card prints -// it as text, so this also renders its inline code. The card's own lookup of -// the previous and next page stays. +// The tree names a page by its `sidebar_label`; the card shows the full title (`titles`, from `fullTitles`). A description is Markdown, so its inline code is rendered here. function forCard(item: FooterItem | undefined, titles: Record): FooterItem | undefined { if (!item) return item; const name = titles[item.url] ?? item.name; @@ -33,8 +29,6 @@ export function PageFooter({ titles = {}, ...props }: ComponentProps void }) { const items = useTOCItems(); const [current] = useActiveAnchors(); diff --git a/src/components/pointer-focus.tsx b/src/components/pointer-focus.tsx index 6d8e204..87058bc 100644 --- a/src/components/pointer-focus.tsx +++ b/src/components/pointer-focus.tsx @@ -1,13 +1,7 @@ import { useEffect } from 'react'; -// Records how the reader last moved focus, on the root element, so the focus -// ring in src/styles/app.css shows only after Tab. A browser matches -// :focus-visible on an element the reader clicked as soon as any key is -// pressed, so the ring cannot be left to :focus-visible alone. -// -// `data-input="pointer"` on any press of the mouse, pen or finger; -// `data-input="keyboard"` on Tab or Shift+Tab. Arrow keys, space and typing -// change nothing. Before either, there is no attribute and the ring may show. +// Sets `data-input` on the root to `pointer` or `keyboard` (Tab), so the focus ring shows only after Tab: +// a browser matches :focus-visible on a clicked element once any key is pressed. export function PointerFocus() { useEffect(() => { const root = document.documentElement; diff --git a/src/components/search-dialog.tsx b/src/components/search-dialog.tsx index 6f675c4..8d606f4 100644 --- a/src/components/search-dialog.tsx +++ b/src/components/search-dialog.tsx @@ -15,18 +15,13 @@ import type { SearchLink, SharedProps } from 'fumadocs-ui/contexts/search'; import { useMemo } from 'react'; export type SearchDialogProps = SharedProps & { - /** The pages the box lists before anything is typed, as Fumadocs's `links` option gives them: `[name, url]`. */ + /** The pages listed before anything is typed, as `[name, url]`. */ links?: SearchLink[]; /** The search route. Defaults to `/api/search`. */ api?: string; }; -/** - * The search box, for ``. It asks the - * route that `createSearch` answers and shows what it gets on one line each: - * the page's title, then at most three matches under it. Before anything is - * typed it lists the pages in `links`, or says what to type. - */ +/** The search box, for ``. It asks the route that `createSearch` answers. */ export function SearchDialog({ links = [], api, ...props }: SearchDialogProps) { const { search, setSearch, query } = useDocsSearch({ client: fetchClient({ api }) }); const pages = useMemo( @@ -34,8 +29,7 @@ export function SearchDialog({ links = [], api, ...props }: SearchDialogProps) { [links], ); const typed = search.trim() !== ''; - // While the first answer for a typed query is on its way, show nothing: an - // empty list would flash "No results found". + // Nothing while the first answer is on its way, or "No results found" would flash. const items = query.data !== 'empty' ? query.data : typed ? null : pages; return ( @@ -45,7 +39,7 @@ export function SearchDialog({ links = [], api, ...props }: SearchDialogProps) { - {/* A phone has no Escape key, so there the chip is a plain word. "Close" is part of the button's name, "Close search". */} + ESC Close diff --git a/src/components/section-nav.tsx b/src/components/section-nav.tsx index 17f7649..3a00604 100644 --- a/src/components/section-nav.tsx +++ b/src/components/section-nav.tsx @@ -2,27 +2,16 @@ import Link from 'fumadocs-core/link'; import { useRouterState } from '@tanstack/react-router'; import { cn } from '../lib/cn'; -/** - * A top-level section of a site, drawn as a pill in the top bar. `href` is the - * first page in the section's sidebar. The notebook layout's own tabs are not - * drawn, since the header slot replaces them, but they still scope the sidebar - * by URL; these pills are the visible switcher. - */ +/** A top-level section of a site, drawn as a pill in the top bar. `href` is the first page in its sidebar. */ export type Section = { label: string; href: string; matches: (pathname: string) => boolean }; -/** - * A section as a site writes it. A section with a `prefix` holds the pages - * whose path is that prefix or sits under it. One with no `prefix` is the - * root's: it holds every page no other section claims, so a page at the top - * of the site needs no prefix of its own. - */ +/** A section as a site writes it. One with no `prefix` is the root's: it holds every page no other section claims. */ export type SectionSpec = { label: string; href: string; prefix?: string }; function isUnder(pathname: string, prefix: string) { return pathname === prefix || pathname.startsWith(`${prefix}/`); } -/** Turns what a site writes into sections that know their pages. */ export function createSections(specs: SectionSpec[]): Section[] { const prefixes = specs.flatMap((spec) => (spec.prefix ? [spec.prefix] : [])); return specs.map(({ label, href, prefix }) => ({ @@ -34,10 +23,7 @@ export function createSections(specs: SectionSpec[]): Section[] { })); } -/** - * The label of the section that holds a path, or `undefined` when none does: a - * landing page or a 404 sits outside every section, and none shows as current. - */ +/** The label of the section that holds a path, or `undefined` for a landing page or a 404. */ export function sectionFor(sections: Section[], pathname: string): string | undefined { return sections.find((section) => section.matches(pathname))?.label; } @@ -65,12 +51,8 @@ export function SectionNav({ sections }: { sections: Section[] }) { ); } -/** - * The sections as a column of large rows, for a phone menu or a drawer. It - * marks the current one with `aria-current` and a darker, heavier label and no - * fill: the drawer's current page keeps the filled row, so the two are not - * both "selected" in one look. - */ +// No fill on the current row: the drawer's current page keeps the filled row, so the two do not both look selected. + export function SectionList({ sections, className }: { sections: Section[]; className?: string }) { const pathname = useRouterState({ select: (s) => s.location.pathname }); const current = sectionFor(sections, pathname); diff --git a/src/components/sidebar-sections.test.tsx b/src/components/sidebar-sections.test.tsx index b1c0e8f..9916633 100644 --- a/src/components/sidebar-sections.test.tsx +++ b/src/components/sidebar-sections.test.tsx @@ -14,7 +14,6 @@ vi.mock('@tanstack/react-router', () => ({ useRouterState: ({ select }: { select: (state: { location: { pathname: string } }) => unknown }) => select({ location: { pathname } }), })); -// Fumadocs's Sidebar draws the banner inside its header, beside the drawer's close button. vi.mock('fumadocs-ui/layouts/notebook/slots/sidebar', () => ({ Sidebar: ({ banner }: { banner?: ReactNode }) => (