optimized route-scroll behaviour
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { NavigationEnd, NavigationStart, Router } from '@angular/router';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
|
||||
const STORAGE_PREFIX = 'inse.scroll.';
|
||||
const STATE_KEY = 'sgScrollId';
|
||||
|
||||
/**
|
||||
* Restores the scroll position of the app's inner scroll container.
|
||||
*
|
||||
* Rules:
|
||||
* - a path change starts at the top,
|
||||
* - back/forward restores the position of that history entry,
|
||||
* - a query-only change on the same page keeps the current position, so
|
||||
* selection, filter and pagination updates do not make the page jump.
|
||||
*
|
||||
* The app scrolls inside `main.content` (not the window), so Angular's
|
||||
* built-in `withInMemoryScrolling` cannot handle it.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class RouteScrollService {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
private scroller: HTMLElement | null = null;
|
||||
private currentScrollId: string | null = null;
|
||||
private scrollFrame: number | null = null;
|
||||
private nextNavigationIsPopstate = false;
|
||||
private currentPath = '';
|
||||
|
||||
constructor() {
|
||||
if ('scrollRestoration' in history) {
|
||||
history.scrollRestoration = 'manual';
|
||||
}
|
||||
|
||||
this.currentPath = this.pathOf(this.router.url);
|
||||
|
||||
this.router.events.pipe(takeUntilDestroyed()).subscribe((event) => {
|
||||
if (event instanceof NavigationStart) {
|
||||
this.persistCurrent();
|
||||
this.nextNavigationIsPopstate = event.navigationTrigger === 'popstate';
|
||||
return;
|
||||
}
|
||||
|
||||
if (event instanceof NavigationEnd) {
|
||||
this.handleNavigationEnd(event, this.nextNavigationIsPopstate);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Connects the persistent scroll container of the app shell. */
|
||||
attach(scroller: HTMLElement): void {
|
||||
if (this.scroller === scroller) return;
|
||||
|
||||
this.scroller?.removeEventListener('scroll', this.onScroll);
|
||||
this.scroller = scroller;
|
||||
this.scroller.addEventListener('scroll', this.onScroll, { passive: true });
|
||||
|
||||
const storedId = this.readStateId();
|
||||
this.currentScrollId = storedId ?? this.writeStateId(this.createScrollId());
|
||||
|
||||
this.restore(this.currentScrollId);
|
||||
}
|
||||
|
||||
/** Connects the scroll container after the first render. */
|
||||
attachWhenReady(getScroller: () => HTMLElement | null | undefined): void {
|
||||
requestAnimationFrame(() => {
|
||||
const scroller = getScroller();
|
||||
if (scroller) this.attach(scroller);
|
||||
});
|
||||
}
|
||||
|
||||
private handleNavigationEnd(
|
||||
event: NavigationEnd,
|
||||
isBackForward: boolean,
|
||||
): void {
|
||||
const nextPath = this.pathOf(event.urlAfterRedirects);
|
||||
|
||||
if (isBackForward) {
|
||||
const id = this.readStateId() ?? this.writeStateId(this.createScrollId());
|
||||
this.currentScrollId = id;
|
||||
this.scheduleRestore(id);
|
||||
this.currentPath = nextPath;
|
||||
return;
|
||||
}
|
||||
|
||||
const isNewPage = nextPath !== this.currentPath;
|
||||
const previousPosition = this.scroller?.scrollTop ?? 0;
|
||||
|
||||
const id = this.writeStateId(this.createScrollId());
|
||||
this.currentScrollId = id;
|
||||
|
||||
if (isNewPage) {
|
||||
this.scheduleScrollTop();
|
||||
} else {
|
||||
// Query-only update on the same page: keep the user's position.
|
||||
this.writePosition(id, previousPosition);
|
||||
}
|
||||
|
||||
this.currentPath = nextPath;
|
||||
}
|
||||
|
||||
private scheduleRestore(scrollId: string): void {
|
||||
this.scheduleFrame(() => this.restore(scrollId));
|
||||
}
|
||||
|
||||
private scheduleScrollTop(): void {
|
||||
this.scheduleFrame(() => this.setScrollTop(0));
|
||||
}
|
||||
|
||||
private scheduleFrame(callback: () => void): void {
|
||||
// Two frames: one for the new component tree, one for its layout.
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(callback);
|
||||
});
|
||||
}
|
||||
|
||||
private restore(scrollId: string | null): void {
|
||||
if (!this.scroller || !scrollId) return;
|
||||
|
||||
const stored = this.readPosition(scrollId);
|
||||
this.setScrollTop(stored);
|
||||
}
|
||||
|
||||
private setScrollTop(value: number): void {
|
||||
if (!this.scroller) return;
|
||||
this.scroller.scrollTop = Math.max(0, value);
|
||||
}
|
||||
|
||||
private persistCurrent(): void {
|
||||
if (!this.scroller || !this.currentScrollId) return;
|
||||
this.writePosition(this.currentScrollId, this.scroller.scrollTop);
|
||||
}
|
||||
|
||||
private readonly onScroll = (): void => {
|
||||
if (this.scrollFrame !== null) return;
|
||||
|
||||
this.scrollFrame = requestAnimationFrame(() => {
|
||||
this.scrollFrame = null;
|
||||
this.persistCurrent();
|
||||
});
|
||||
};
|
||||
|
||||
private createScrollId(): string {
|
||||
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
private readStateId(): string | null {
|
||||
const state = history.state as Record<string, unknown> | null;
|
||||
const id = state?.[STATE_KEY];
|
||||
return typeof id === 'string' && id.length > 0 ? id : null;
|
||||
}
|
||||
|
||||
private writeStateId(id: string): string {
|
||||
const state = (history.state ?? {}) as Record<string, unknown>;
|
||||
history.replaceState({ ...state, [STATE_KEY]: id }, '');
|
||||
return id;
|
||||
}
|
||||
|
||||
private readPosition(scrollId: string): number {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(STORAGE_PREFIX + scrollId);
|
||||
const value = raw === null ? 0 : Number(raw);
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private writePosition(scrollId: string, position: number): void {
|
||||
try {
|
||||
sessionStorage.setItem(STORAGE_PREFIX + scrollId, String(position));
|
||||
} catch {
|
||||
// Storage can be unavailable (private mode/quota). Position restoration
|
||||
// is an enhancement, never a hard requirement.
|
||||
}
|
||||
}
|
||||
|
||||
private pathOf(url: string): string {
|
||||
return url.split('?')[0].split('#')[0] || '/';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user