From d19401373fc14bf91200bd10f1c2b9e49b8ab36d Mon Sep 17 00:00:00 2001 From: hypercross Date: Thu, 19 Mar 2026 11:22:12 +0800 Subject: [PATCH] fix: slugging --- src/App.tsx | 2 +- src/components/FileTree.tsx | 2 +- src/data-loader/toc.ts | 8 +++++++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index bbf8c97..75df916 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -43,7 +43,7 @@ const App: Component = () => {
-
+
); diff --git a/src/components/FileTree.tsx b/src/components/FileTree.tsx index 11e20c3..4b51e28 100644 --- a/src/components/FileTree.tsx +++ b/src/components/FileTree.tsx @@ -81,7 +81,7 @@ export const HeadingNode: Component<{ depth: number; }> = (props) => { const navigate = useNavigate(); - const anchor = props.node.title.toLowerCase().replace(/\s+/g, "-"); + const anchor = props.node.id || ""; const href = `${props.basePath}#${anchor}`; const handleClick = (e: MouseEvent) => { diff --git a/src/data-loader/toc.ts b/src/data-loader/toc.ts index 4227dc4..06826cc 100644 --- a/src/data-loader/toc.ts +++ b/src/data-loader/toc.ts @@ -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) {