diff --git a/frontend/src/app/app.component.ts b/frontend/src/app/app.component.ts index d5e84d5..9daddd9 100644 --- a/frontend/src/app/app.component.ts +++ b/frontend/src/app/app.component.ts @@ -1,5 +1,5 @@ import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core'; -import { NavigationEnd, Router } from '@angular/router'; +import { NavigationEnd, NavigationStart, Router } from '@angular/router'; import { filter } from 'rxjs'; import PerfectScrollbar from 'perfect-scrollbar'; @@ -11,19 +11,50 @@ import PerfectScrollbar from 'perfect-scrollbar'; }) export class AppComponent implements AfterViewInit { title = 'Showy'; - + @ViewChild('scrollContainer', { static: true }) scrollContainer!: ElementRef; private ps!: PerfectScrollbar; + private scrollPositions = new Map(); + private isBackNavigation = ''; constructor(private router: Router) {} ngAfterViewInit() { this.ps = new PerfectScrollbar(this.scrollContainer.nativeElement); + // this.router.events + // .pipe(filter(event => event instanceof NavigationEnd)) + // .subscribe(() => { + // this.scrollToTop(); + // }); + + // Save scroll position before navigation this.router.events - .pipe(filter(event => event instanceof NavigationEnd)) + .pipe(filter((event) => event instanceof NavigationStart)) + .subscribe((e) => { + if (e instanceof NavigationStart) { + this.isBackNavigation = e.navigationTrigger?.toString()!; + const currentUrl = this.router.url; + const scrollTop = this.scrollContainer.nativeElement.scrollTop; + this.scrollPositions.set(currentUrl, scrollTop); // Save current scroll position + } + }); + + // Restore scroll position after navigation + this.router.events + .pipe(filter((event) => event instanceof NavigationEnd)) .subscribe(() => { - this.scrollToTop(); + // ? case of backward / forward + if (this.isBackNavigation == 'popstate') { + const currentUrl = this.router.url; + const savedScrollTop = this.scrollPositions.get(currentUrl) || 0; + this.scrollContainer.nativeElement.scrollTop = savedScrollTop; // Restore scroll position + this.ps.update(); + } else if (this.isBackNavigation == 'imperative') { + // ? case of visiting page + this.scrollContainer.nativeElement.scrollTop = 0; // Scroll top + this.ps.update(); + } }); }