fix: slugging

This commit is contained in:
2026-03-19 11:26:59 +08:00
parent 71ab7523da
commit d19401373f
3 changed files with 9 additions and 3 deletions
+7 -1
View File
@@ -1,8 +1,11 @@
import Slugger from "github-slugger";
/**
* 目录树节点
*/
export interface TocNode {
title: string;
id?: string;
path?: string;
level: number;
children?: TocNode[];
@@ -24,6 +27,7 @@ export function extractHeadings(content: string): TocNode[] {
const headings: TocNode[] = [];
const lines = content.split("\n");
const stack: { node: TocNode; level: number }[] = [];
const slugger = new Slugger();
for (const line of lines) {
const match = line.match(/^(#{1,6})\s+(.+)$/);
@@ -31,7 +35,9 @@ export function extractHeadings(content: string): TocNode[] {
const level = match[1].length;
const title = match[2].trim();
const node: TocNode = { title, level };
// 使用 github-slugger 生成 ID,与 marked-gfm-heading-id 保持一致
const id = slugger.slug(title.toLowerCase());
const node: TocNode = { title, id, level };
// 找到合适的父节点
while (stack.length > 0 && stack[stack.length - 1].level >= level) {