mirror of
https://github.com/streetwriters/notesnook.git
synced 2026-02-24 12:12:54 +01:00
editor: fix toc level mapping
This commit is contained in:
committed by
Ammar Ahmed
parent
fa37d6cc25
commit
a7c8cef69c
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user