Skip to content

Commit

Permalink
refactor: better scroll toc
Browse files Browse the repository at this point in the history
  • Loading branch information
zyrouge committed Apr 4, 2024
1 parent 14a3633 commit c9caabc
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions src/assets/scripts/article.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,30 @@ class ArticleState {
let onScrollEndInterval: ReturnType<typeof setTimeout> | null = null;
document.addEventListener("scroll", () => {
clearInterval(onScrollEndInterval ?? undefined);
onScrollEndInterval = setTimeout(() => this.emitOnScrollEnd(), 50);
const scrollingElement = document.scrollingElement;
if (scrollingElement) {
let visibleHeading = this.currentHeading;
for (const x of Object.values(this.headings)) {
if (scrollingElement.scrollTop < x.content.offsetTop) {
break;
}
visibleHeading = x;
if (!scrollingElement) return;
const visibleHeight = document.documentElement.clientHeight;
const scrollBottom = scrollingElement.scrollTop + visibleHeight;
if (scrollBottom === document.body.clientHeight) {
const headings = Object.values(this.headings);
const lastHeading =
headings[headings.length - 1] ?? this.currentHeading;
if (!lastHeading) return;
this.highlightTocHeading(lastHeading);
return;
}
let visibleHeading = this.currentHeading;
const scrollOffsetMid =
scrollingElement.scrollTop + visibleHeight / 3;
for (const x of Object.values(this.headings)) {
if (scrollOffsetMid < x.content.offsetTop) {
break;
}
if (!visibleHeading) return;
this.highlightTocHeading(visibleHeading);
visibleHeading = x;
}
onScrollEndInterval = setTimeout(() => this.emitOnScrollEnd(), 50);
if (!visibleHeading) return;
this.highlightTocHeading(visibleHeading);
});
}

Expand Down

0 comments on commit c9caabc

Please sign in to comment.