Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Docs Site] Support custom heading IDs with MDX comments #17551

Merged
merged 3 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 26 additions & 0 deletions astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import icon from "astro-icon";
import sitemap from "@astrojs/sitemap";
import react from "@astrojs/react";
import rehypeTitleFigure from "rehype-title-figure";
import { visit } from "unist-util-visit";

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

Expand Down Expand Up @@ -70,6 +71,30 @@ const autolinkConfig: rehypeAutolinkHeadingsOptions = {
content: () => [AnchorLinkIcon],
};

// # foo {/*bar*/} = <a id="bar">foo</a>
function rehypeCustomHeadingId() {
return function (tree: any) {
visit(tree, "element", function (element: any) {
if (/^h[1-6]$/.test(element.tagName)) {
const last = element.children.at(-1);

if (
last.type === "mdxTextExpression" &&
last.value.startsWith("/*") &&
last.value.endsWith("*/")
) {
const id = last.value.slice(2, -2).trim();
element.properties.id = id;

const text = element.children.at(-2);
text.value = text.value.trimEnd();
element.children.with(-2, text);
}
}
});
};
}

// https://astro.build/config
export default defineConfig({
site: "https://developers.cloudflare.com",
Expand All @@ -95,6 +120,7 @@ export default defineConfig({
rel: ["noopener"],
},
],
rehypeCustomHeadingId,
rehypeSlug,
[rehypeAutolinkHeadings, autolinkConfig],
// @ts-expect-error TODO: fix types
Expand Down
2 changes: 2 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"tippy.js": "^6.3.7",
"tsx": "^4.19.1",
"typescript": "^5.5.4",
"unist-util-visit": "^5.0.0",
"vitest": "2.0.5",
"wrangler": "^3.78.10",
"yaml": "^2.5.1"
Expand Down
Loading