From b406ef695199f34f6f1bde7ac6399b277c20e3f1 Mon Sep 17 00:00:00 2001 From: Aleksei Morozov Date: Tue, 13 Feb 2024 12:26:11 +0100 Subject: [PATCH] Update src/app/components/table-of-content/table-of-content.component.ts Co-authored-by: Robinson Zimmermann <16561945+robinsonzimmermann@users.noreply.github.com> --- .../table-of-content.component.ts | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/app/components/table-of-content/table-of-content.component.ts b/src/app/components/table-of-content/table-of-content.component.ts index 8eaaee38..b8a6c33e 100644 --- a/src/app/components/table-of-content/table-of-content.component.ts +++ b/src/app/components/table-of-content/table-of-content.component.ts @@ -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(); } } @@ -50,7 +50,20 @@ 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; @@ -58,12 +71,9 @@ export class TableOfContentComponent implements AfterViewInit { ? this.document.getElementById(nextElement)?.offsetTop : fullHeightWithScroll; - if (fullHeight === scroll && i === offsetHeaders.length) { - return true; - } - return scroll >= Number(offset) && scroll < Number(nextOffset); }); + } } @@ -121,7 +131,7 @@ export class TableOfContentComponent implements AfterViewInit { } if (!this.activeHeader) { - this.activeHeader = this.offsetHeaders[0] + this.activeHeader = this.offsetHeaders[0]; } const offset = ( @@ -129,8 +139,6 @@ export class TableOfContentComponent implements AfterViewInit { ).offsetTop; if (this.offsetHeaders.includes(this.activeHeader) && offset) { this.document.documentElement.scrollTo(0, offset); - } else { - this.activeHeader = this.offsetHeaders[this.offsetHeaders.length]; } } }