Core: Support code syntax in headings

This commit is contained in:
fuma-nama
2024-06-06 12:47:01 +08:00
parent 17a2a703fa
commit ba20694bd7
4 changed files with 30 additions and 12 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'fumadocs-core': patch
---
Remark Headings: Support code syntax in headings
+16 -12
View File
@@ -3,6 +3,7 @@ import type { Heading, Root } from 'mdast';
import type { Transformer } from 'unified';
import { visit } from 'unist-util-visit';
import type { TOCItemType } from '@/server/get-toc';
import { flattenNode } from '@/mdx-plugins/remark-utils';
const slugger = new Slugger();
@@ -40,33 +41,36 @@ export function remarkHeading({
slugger.reset();
visit(root, 'heading', (heading) => {
const node = heading.children.at(-1);
if (!node || node.type !== 'text') return;
heading.data ||= {};
heading.data.hProperties ||= {};
const lastNode = heading.children.at(-1);
let id = heading.data.hProperties.id;
if (!id && customId) {
const match = regex.exec(node.value);
if (
!heading.data.hProperties.id &&
lastNode?.type === 'text' &&
customId
) {
const match = regex.exec(lastNode.value);
if (match?.[1]) {
id = match[1];
node.value = node.value.slice(0, match.index);
heading.data.hProperties.id = match[1];
lastNode.value = lastNode.value.slice(0, match.index);
}
}
const value = flattenNode(heading);
let id = heading.data.hProperties.id;
if (!id) {
id = defaultSlug
? defaultSlug(root, heading, node.value)
: slugger.slug(node.value);
? defaultSlug(root, heading, value)
: slugger.slug(value);
}
heading.data.hProperties.id = id;
toc.push({
title: node.value,
title: value,
url: `#${id}`,
depth: heading.depth,
});
+4
View File
@@ -21,3 +21,7 @@ Some text here
### Custom heading id hello-world]
Some text here
### `code` here
hi
@@ -29,4 +29,9 @@
"title": "Custom heading id hello-world]",
"url": "#custom-heading-id-hello-world",
},
{
"depth": 3,
"title": "code here",
"url": "#code-here",
},
]