From f6637da274697dcfd35840b2f7ff007f9133c2de Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Wed, 19 Feb 2025 14:02:20 +0500 Subject: [PATCH] editor: fix toc level mapping --- packages/editor/src/utils/toc.ts | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) 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; }