diff --git a/packages/editor/src/utils/toc.ts b/packages/editor/src/utils/toc.ts index 62d5ca859..272f2a5e0 100644 --- a/packages/editor/src/utils/toc.ts +++ b/packages/editor/src/utils/toc.ts @@ -24,16 +24,35 @@ export type TOCItem = { top: number; }; +const levelsMap: Record = { + H1: 1, + H2: 2, + H3: 3, + H4: 4, + H5: 5, + H6: 6 +}; + export function getTableOfContents(content: HTMLElement) { const tableOfContents: TOCItem[] = []; - + let level = -1; + let prevHeading = 0; for (const heading of content.querySelectorAll( "h1, h2, h3, h4, h5, h6" )) { - const level = parseInt(heading.tagName[1]); const title = heading.textContent; const id = heading.dataset.blockId; if (!id || !title) continue; + const nodeName = heading.nodeName; + const currentHeading = levelsMap[nodeName]; + + level = + prevHeading < currentHeading + ? level + 1 + : prevHeading > currentHeading + ? level - (prevHeading - currentHeading) + : level; + prevHeading = currentHeading; tableOfContents.push({ level, @@ -42,7 +61,6 @@ export function getTableOfContents(content: HTMLElement) { top: (heading as HTMLElement).offsetTop }); } - return tableOfContents; }