Skip to content

Commit

Permalink
fix the last heading is not selected in side bar when scrolling below it
Browse files Browse the repository at this point in the history
  • Loading branch information
rhysd committed Aug 30, 2024
1 parent e511a85 commit 1330593
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion v2/web/components/Article.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,30 @@ function getTitle(elem: HTMLElement): string {

function collectHeadings(root: HTMLElement): Heading[] {
const headings: Heading[] = [];
for (const elem of root.querySelectorAll('article > h1,h2,h3,h4,h5,h6') as NodeListOf<HTMLHeadingElement>) {
for (const elem of root.querySelectorAll<HTMLHeadingElement>('article > h1,h2,h3,h4,h5,h6')) {
const level = parseInt(elem.tagName.slice(1), 10);
const text = getTitle(elem);
headings.push({ level, text, elem });
}

const scrollTop = root.scrollTop;
const scrollBottom = scrollTop + root.clientHeight;
let found = false;
for (let i = 0; i < headings.length; i++) {
const top = headings[i].elem.offsetTop;
if (top >= scrollTop) {
const j = top >= scrollBottom && i > 0 ? i - 1 : i;
headings[j].current = true;
found = true;
break;
}
}

// Current scroll position is below the last heading.
if (!found && headings.length > 0) {
headings[headings.length - 1].current = true;
}

return headings;
}

Expand Down

0 comments on commit 1330593

Please sign in to comment.