Skip to content

Commit 2a55f92

Browse files
committed
[Docs Site] Support custom heading IDs with MDX comments
1 parent 20c486f commit 2a55f92

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

astro.config.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import icon from "astro-icon";
1717
import sitemap from "@astrojs/sitemap";
1818
import react from "@astrojs/react";
1919
import rehypeTitleFigure from "rehype-title-figure";
20+
import { visit } from "unist-util-visit";
2021

2122
const runLinkCheck = process.env.RUN_LINK_CHECK || false;
2223

@@ -70,6 +71,30 @@ const autolinkConfig: rehypeAutolinkHeadingsOptions = {
7071
content: () => [AnchorLinkIcon],
7172
};
7273

74+
// # foo {/*bar*/} = <a id="bar">foo</a>
75+
function rehypeCustomHeadingId() {
76+
return function (tree: any) {
77+
visit(tree, "element", function (element: any) {
78+
if (/^h[1-6]$/.test(element.tagName)) {
79+
const last = element.children.at(-1);
80+
81+
if (
82+
last.type === "mdxTextExpression" &&
83+
last.value.startsWith("/*") &&
84+
last.value.endsWith("*/")
85+
) {
86+
const id = last.value.slice(2, -2).trim();
87+
element.properties.id = id;
88+
89+
const text = element.children.at(-2);
90+
text.value = text.value.trimEnd();
91+
element.children.with(-2, text);
92+
}
93+
}
94+
});
95+
};
96+
}
97+
7398
// https://astro.build/config
7499
export default defineConfig({
75100
site: "https://developers.cloudflare.com",
@@ -95,6 +120,7 @@ export default defineConfig({
95120
rel: ["noopener"],
96121
},
97122
],
123+
rehypeCustomHeadingId,
98124
rehypeSlug,
99125
[rehypeAutolinkHeadings, autolinkConfig],
100126
// @ts-expect-error TODO: fix types

package-lock.json

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
"tippy.js": "^6.3.7",
8282
"tsx": "^4.19.1",
8383
"typescript": "^5.5.4",
84+
"unist-util-visit": "^5.0.0",
8485
"vitest": "2.0.5",
8586
"wrangler": "^3.78.10",
8687
"yaml": "^2.5.1"

0 commit comments

Comments
 (0)