editor: fix toc level mapping

This commit is contained in:
Abdullah Atta
2025-02-19 14:02:20 +05:00
committed by Ammar Ahmed
parent fa37d6cc25
commit a7c8cef69c

View File

@@ -24,16 +24,35 @@ export type TOCItem = {
top: number;
};
const levelsMap: Record<string, number> = {
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<HTMLHeadingElement>(
"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;
}