Skip to content

Commit

Permalink
Update src/app/components/table-of-content/table-of-content.component.ts
Browse files Browse the repository at this point in the history
Co-authored-by: Robinson Zimmermann <[email protected]>
  • Loading branch information
a1exymoroz and robinsonzimmermann committed Feb 13, 2024
1 parent 0dd96d6 commit b406ef6
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/app/components/table-of-content/table-of-content.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class TableOfContentComponent implements AfterViewInit {
this.dataSource.data = headers;
this.treeControl.expandAll();
if (headers.length) {
this.createOffsets(headers);
this.offsetHeaders = this.createOffsets(headers);
this.checkFirstHeader();
}
}
Expand All @@ -50,20 +50,30 @@ export class TableOfContentComponent implements AfterViewInit {
const fullHeight =
this.document.body.scrollHeight - this.document.body.clientHeight;

if (scroll === fullHeight) {
this.activeHeader = this.offsetHeaders[this.offsetHeaders.length - 1];
return;
}

const firstElementOffset = this.document.getElementById(this.offsetHeaders[0])?.offsetTop;

if (scroll < Number(firstElementOffset)) {
this.activeHeader = this.offsetHeaders[0]
return
}

this.activeHeader = this.offsetHeaders.find((element, i, offsetHeaders) => {

const nextElement = offsetHeaders[i + 1];

const offset = this.document.getElementById(element)?.offsetTop;
const nextOffset = nextElement
? this.document.getElementById(nextElement)?.offsetTop
: fullHeightWithScroll;

if (fullHeight === scroll && i === offsetHeaders.length) {
return true;
}

return scroll >= Number(offset) && scroll < Number(nextOffset);
});

}
}

Expand Down Expand Up @@ -121,16 +131,14 @@ export class TableOfContentComponent implements AfterViewInit {
}

if (!this.activeHeader) {
this.activeHeader = this.offsetHeaders[0]
this.activeHeader = this.offsetHeaders[0];
}

const offset = (
this.document.getElementById(this.activeHeader) as HTMLElement
).offsetTop;
if (this.offsetHeaders.includes(this.activeHeader) && offset) {
this.document.documentElement.scrollTo(0, offset);
} else {
this.activeHeader = this.offsetHeaders[this.offsetHeaders.length];
}
}
}

0 comments on commit b406ef6

Please sign in to comment.