Skip to content

Commit 475a9cc

Browse files
gaearonclaude
andcommitted
Match the Pages Router table of contents
- Only collect top-level headings (run the extractor before the MaxWidth wrapper). Headings nested in <Note> etc. were never in the TOC before. - Compile TOC entries from the already-processed mdast heading children instead of re-parsing the heading source. Re-parsing dropped smartypants (straight quotes on 43 pages) and turned headings like "1. Install" into an <ol> inside the TOC link. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 856856a commit 475a9cc

2 files changed

Lines changed: 42 additions & 28 deletions

File tree

‎src/utils/compileMDX.tsx‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@
77

88
import {Fragment} from 'react';
99
import type {ReactNode} from 'react';
10-
import {compile, run} from '@mdx-js/mdx';
10+
import {compile, createProcessor, run} from '@mdx-js/mdx';
1111
import * as runtime from 'react/jsx-runtime';
1212
import matter from 'gray-matter';
1313
import remarkGfm from 'remark-gfm';
1414
import remarkFrontmatter from 'remark-frontmatter';
15+
import type {Root} from 'mdast';
1516
import {remarkPlugins} from '../../plugins/markdownToHtml';
1617
import {createMDXComponents} from 'components/MDX/MDXComponents';
1718
import type {LanguageItem} from 'components/MDX/LanguagesContext';
@@ -43,24 +44,31 @@ function compileOptions() {
4344
...remarkPlugins,
4445
remarkGfm,
4546
remarkFrontmatter,
46-
MaxWidthWrapperPlugin,
47+
// Must run before MaxWidthWrapperPlugin; see TOCExtractorPlugin.
4748
TOCExtractorPlugin,
49+
MaxWidthWrapperPlugin,
4850
],
4951
rehypePlugins: [MetaAttributesPlugin],
5052
outputFormat: 'function-body' as const,
5153
};
5254
}
5355

56+
// Compiles the processed heading mdast rather than re-parsing its source,
57+
// which would e.g. turn "1. Install" into a list and lose smartypants.
58+
const tocProcessor = createProcessor({outputFormat: 'function-body'});
59+
5460
async function compileToc(toc: ExtractedTocItem[]) {
5561
return Promise.all(
56-
toc.map(async ({source, ...item}): Promise<CompiledTocItem> => {
57-
if (!source) {
62+
toc.map(async ({children, ...item}): Promise<CompiledTocItem> => {
63+
if (!children) {
5864
return item;
5965
}
60-
const code = await compile(source, {
61-
remarkPlugins: [remarkGfm],
62-
outputFormat: 'function-body',
63-
});
66+
const tree: Root = {
67+
type: 'root',
68+
children: [{type: 'paragraph', children}],
69+
};
70+
const transformed = await tocProcessor.run(tree);
71+
const code = tocProcessor.stringify(transformed as any);
6472
return {...item, code: String(code)};
6573
})
6674
);

‎src/utils/mdx/TOCExtractorPlugin.ts‎

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,51 @@
1-
import type {Root} from 'mdast';
1+
import type {PhrasingContent, Root} from 'mdast';
22
import type {VFile} from 'vfile';
3-
import visit from 'unist-util-visit';
43

54
export interface ExtractedTocItem {
65
url: string;
76
depth: number;
8-
source?: string;
7+
children?: PhrasingContent[];
98
text?: string;
109
}
1110

12-
function sourceForChildren(
13-
source: string,
14-
children: Array<{
15-
position?: {start: {offset?: number}; end: {offset?: number}};
16-
}>
17-
) {
18-
const start = children[0]?.position?.start.offset;
19-
const end = children.at(-1)?.position?.end.offset;
20-
return start == null || end == null ? '' : source.slice(start, end).trim();
11+
// Drops the trailing {/*custom-id*/} expression.
12+
function headingContent(children: PhrasingContent[]): PhrasingContent[] {
13+
const content = [...children];
14+
const last = content[content.length - 1] as {type: string} | undefined;
15+
if (last?.type === 'mdxTextExpression') {
16+
content.pop();
17+
}
18+
const lastText = content[content.length - 1];
19+
if (lastText?.type === 'text') {
20+
content[content.length - 1] = {
21+
...lastText,
22+
value: lastText.value.replace(/\s+$/, ''),
23+
};
24+
}
25+
return content;
2126
}
2227

28+
// Only top-level headings go into the TOC, so this must run before
29+
// MaxWidthWrapperPlugin moves them into <MaxWidth> wrappers.
2330
export function TOCExtractorPlugin({maxDepth = 3} = {}) {
2431
return (tree: Root, file: VFile) => {
2532
const toc: ExtractedTocItem[] = [];
26-
const source = String(file.value);
2733

28-
visit(tree, (node: any) => {
29-
if (node.type === 'heading' && node.depth <= maxDepth) {
34+
for (const node of tree.children as any[]) {
35+
if (node.type === 'heading') {
3036
const id = node.data?.hProperties?.id;
31-
if (id) {
37+
if (node.depth <= maxDepth && id) {
3238
toc.push({
3339
url: `#${id}`,
3440
depth: node.depth,
35-
source: sourceForChildren(source, node.children),
41+
children: headingContent(node.children),
3642
});
3743
}
38-
return;
44+
continue;
3945
}
4046

4147
if (node.type !== 'mdxJsxFlowElement') {
42-
return;
48+
continue;
4349
}
4450

4551
if (node.name === 'Challenges' || node.name === 'Recap') {
@@ -59,7 +65,7 @@ export function TOCExtractorPlugin({maxDepth = 3} = {}) {
5965
const permalink = String(attributes.get('permalink') ?? 'team-member');
6066
toc.push({url: `#${permalink}`, depth: 3, text: name});
6167
}
62-
});
68+
}
6369

6470
if (toc.length > 0) {
6571
toc.unshift({url: '#', depth: 2, text: 'Overview'});

0 commit comments

Comments
 (0)