Skip to content

Commit

Permalink
Fix restore scroll for fixed layout
Browse files Browse the repository at this point in the history
  • Loading branch information
gsans committed Oct 14, 2023
1 parent c560b0a commit 08c5284
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
4 changes: 2 additions & 2 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { ReadComponent } from './read/read.component';
import { CustomRouteReuseStrategy } from './reuse-strategy.routing';

const routes: Routes = [
{ path: 'chat', component: CustomChatComponent, data: { title: 'Chat', scroll: true } },
{ path: 'text', component: TextComponent, data: { title: 'Text', scroll: true } },
{ path: 'chat', component: CustomChatComponent, data: { title: 'Chat', scroll: true, viewportSelector: '.messages' } },
{ path: 'text', component: TextComponent, data: { title: 'Text' } },
{ path: 'voice', component: ReadComponent, data: { title: 'Voice' } },
{ path: '', redirectTo: '/chat', pathMatch: 'full' }
];
Expand Down
26 changes: 18 additions & 8 deletions src/app/router-scroll.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Subscription } from "rxjs";
export class RouterScrollService {

private routerSubscription: Subscription | null;
private scrollPositions: { [route: string]: any } = {};
private scrollTopArray: { [route: string]: any } = {};
private customViewport: HTMLElement | null = null;

constructor(
Expand All @@ -21,15 +21,25 @@ export class RouterScrollService {
if (event instanceof NavigationStart) {
// Save scroll position for current route. Eg: { path: 'chat', data: { scroll: true } }
if (this.activatedRoute.firstChild?.routeConfig?.data?.['scroll']) {
this.scrollPositions[this.router.url] = this.viewportScroller.getScrollPosition();
const viewportSelector = this.activatedRoute.firstChild?.routeConfig?.data?.['viewportSelector'];
if (viewportSelector) {
document.querySelectorAll(viewportSelector).forEach(elem => {
this.scrollTopArray[this.router.url] = elem.scrollTop;
})
}
}
} else if (event instanceof NavigationEnd) {
// Restore scroll position if available
const scrollPosition = this.scrollPositions[event.url];
if (scrollPosition) {
setTimeout(() => { // run during next tick
this.viewportScroller.scrollToPosition(scrollPosition);
}, 0);
const viewportSelector = this.activatedRoute.firstChild?.routeConfig?.data?.['viewportSelector'];
if (viewportSelector) {
// Restore scroll position if available
const scrollTop = this.scrollTopArray[event.url];
if (scrollTop) {
setTimeout(() => { // run during next tick
document.querySelectorAll(viewportSelector).forEach(elem => {
elem.scrollTop = scrollTop;
})
});
}
}
}
});
Expand Down

0 comments on commit 08c5284

Please sign in to comment.