refactor(ui): unify author/series/book browsers using tanstack virtual (#941)

This commit is contained in:
Alex
2026-04-27 19:01:37 +01:00
committed by GitHub
parent 7da337754b
commit d256fbf389
60 changed files with 1124 additions and 1841 deletions
@@ -1,193 +1,30 @@
import {Injector, runInInjectionContext} from '@angular/core';
import {ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {ActivatedRouteSnapshot, Route} from '@angular/router';
import {describe, expect, it} from 'vitest';
import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service';
import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service';
import {CustomReuseStrategy} from './custom-reuse-strategy';
function createRoute(path: string, params: Record<string, string> = {}): ActivatedRouteSnapshot {
function createRoute(routeConfig: Route, params: Record<string, string> = {}): ActivatedRouteSnapshot {
return {
routeConfig: {path},
routeConfig,
params
} as ActivatedRouteSnapshot;
}
describe('CustomReuseStrategy', () => {
const handle = {componentRef: {destroy: vi.fn()} as never} as DetachedRouteHandle;
let strategy: CustomReuseStrategy;
let scrollService: BookBrowserScrollService;
let selectionService: BookSelectionService;
beforeEach(() => {
vi.restoreAllMocks();
scrollService = new BookBrowserScrollService();
selectionService = new BookSelectionService();
const injector = Injector.create({
providers: [
{provide: BookBrowserScrollService, useValue: scrollService},
{provide: BookSelectionService, useValue: selectionService},
]
});
strategy = runInInjectionContext(injector, () => new CustomReuseStrategy());
});
afterEach(() => {
vi.useRealTimers();
document.body.innerHTML = '';
});
it('stores and reattaches book browser routes with their saved scroll position', async () => {
vi.useFakeTimers();
const route = createRoute('all-books', {libraryId: '42'});
const scrollElement = document.createElement('div');
scrollElement.className = 'virtual-scroller';
const querySelectorSpy = vi.spyOn(document, 'querySelector').mockReturnValue(scrollElement);
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
scrollService.savePosition('all-books:42', 321);
strategy.store(route, handle);
expect(strategy.shouldDetach(route)).toBe(true);
expect(strategy.shouldAttach(route)).toBe(true);
expect(deselectSpy).toHaveBeenCalledTimes(1);
const restored = strategy.retrieve(route);
await vi.runAllTimersAsync();
expect(restored).toBe(handle);
expect(querySelectorSpy).toHaveBeenCalledWith('.virtual-scroller');
expect(scrollElement.scrollTop).toBe(321);
});
it('ignores non-book routes when storing or attaching', () => {
const route = createRoute('login');
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
strategy.store(route, handle);
expect(strategy.shouldDetach(route)).toBe(false);
expect(strategy.shouldAttach(route)).toBe(false);
expect(strategy.retrieve(route)).toBeNull();
expect(deselectSpy).not.toHaveBeenCalled();
});
it('ignores null handles for book browser routes', () => {
const route = createRoute('series', {seriesId: '77'});
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
strategy.store(route, null);
expect(strategy.shouldDetach(route)).toBe(true);
expect(strategy.shouldAttach(route)).toBe(false);
expect(strategy.retrieve(route)).toBeNull();
expect(deselectSpy).not.toHaveBeenCalled();
});
it('returns a stored handle without touching the DOM when no scroll position was saved', () => {
const route = createRoute('authors');
const querySelectorSpy = vi.spyOn(document, 'querySelector');
const deselectSpy = vi.spyOn(selectionService, 'deselectAll');
strategy.store(route, handle);
expect(deselectSpy).toHaveBeenCalledOnce();
expect(strategy.shouldAttach(route)).toBe(true);
expect(strategy.retrieve(route)).toBe(handle);
expect(querySelectorSpy).not.toHaveBeenCalled();
});
const strategy = new CustomReuseStrategy();
it('reuses routes only when the route config and params both match', () => {
const routeConfig = {path: 'series'};
const current = {
routeConfig,
params: {seriesId: '12'}
} as unknown as ActivatedRouteSnapshot;
const same = {
routeConfig,
params: {seriesId: '12'}
} as unknown as ActivatedRouteSnapshot;
const differentParams = {
routeConfig,
params: {seriesId: '99'}
} as unknown as ActivatedRouteSnapshot;
const differentConfig = {
routeConfig: {path: 'authors'},
params: {seriesId: '12'}
} as unknown as ActivatedRouteSnapshot;
const current = createRoute(routeConfig, {seriesId: '12'});
const same = createRoute(routeConfig, {seriesId: '12'});
const sameDifferentOrder = createRoute(routeConfig, {tab: 'books', seriesId: '12'});
const currentWithTab = createRoute(routeConfig, {seriesId: '12', tab: 'books'});
const differentParams = createRoute(routeConfig, {seriesId: '99'});
const differentConfig = createRoute({path: 'authors'}, {seriesId: '12'});
expect(strategy.shouldReuseRoute(same, current)).toBe(true);
expect(strategy.shouldReuseRoute(sameDifferentOrder, currentWithTab)).toBe(true);
expect(strategy.shouldReuseRoute(differentParams, current)).toBe(false);
expect(strategy.shouldReuseRoute(differentConfig, current)).toBe(false);
});
it('evicts the oldest route when storing more than MAX_STORED_ROUTES (3)', () => {
const route1 = createRoute('library/:libraryId/books', {libraryId: '1'});
const route2 = createRoute('library/:libraryId/books', {libraryId: '2'});
const route3 = createRoute('library/:libraryId/books', {libraryId: '3'});
const route4 = createRoute('library/:libraryId/books', {libraryId: '4'});
const handle1 = {componentRef: {id: 1, destroy: vi.fn()} as never} as DetachedRouteHandle;
const handle2 = {componentRef: {id: 2, destroy: vi.fn()} as never} as DetachedRouteHandle;
const handle3 = {componentRef: {id: 3, destroy: vi.fn()} as never} as DetachedRouteHandle;
const handle4 = {componentRef: {id: 4, destroy: vi.fn()} as never} as DetachedRouteHandle;
strategy.store(route1, handle1);
strategy.store(route2, handle2);
strategy.store(route3, handle3);
expect(strategy.shouldAttach(route1)).toBe(true);
expect(strategy.shouldAttach(route2)).toBe(true);
expect(strategy.shouldAttach(route3)).toBe(true);
strategy.store(route4, handle4);
expect(strategy.shouldAttach(route1)).toBe(false);
expect(strategy.shouldAttach(route2)).toBe(true);
expect(strategy.shouldAttach(route3)).toBe(true);
expect(strategy.shouldAttach(route4)).toBe(true);
});
it('clears scroll positions when evicting old routes', () => {
const clearSpy = vi.spyOn(scrollService, 'clearPosition');
const route1 = createRoute('library/:libraryId/books', {libraryId: '10'});
const route2 = createRoute('library/:libraryId/books', {libraryId: '20'});
const route3 = createRoute('library/:libraryId/books', {libraryId: '30'});
const route4 = createRoute('library/:libraryId/books', {libraryId: '40'});
scrollService.savePosition('library/:libraryId/books:10', 100);
strategy.store(route1, handle);
strategy.store(route2, handle);
strategy.store(route3, handle);
expect(clearSpy).not.toHaveBeenCalled();
strategy.store(route4, handle);
expect(clearSpy).toHaveBeenCalledWith('library/:libraryId/books:10');
});
it('re-storing an existing route refreshes its LRU position', () => {
const route1 = createRoute('library/:libraryId/books', {libraryId: '1'});
const route2 = createRoute('library/:libraryId/books', {libraryId: '2'});
const route3 = createRoute('library/:libraryId/books', {libraryId: '3'});
const route4 = createRoute('library/:libraryId/books', {libraryId: '4'});
strategy.store(route1, handle);
strategy.store(route2, handle);
strategy.store(route3, handle);
strategy.store(route1, handle);
strategy.store(route4, handle);
expect(strategy.shouldAttach(route1)).toBe(true);
expect(strategy.shouldAttach(route2)).toBe(false);
expect(strategy.shouldAttach(route3)).toBe(true);
expect(strategy.shouldAttach(route4)).toBe(true);
});
});
+10 -105
View File
@@ -1,112 +1,17 @@
import {inject, Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, DetachedRouteHandle, destroyDetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service';
import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service';
import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, BaseRouteReuseStrategy, Params} from '@angular/router';
/**
* Maximum number of detached BookBrowser routes kept in memory.
* Each cached route retains its full component tree (book cards, images,
* event listeners, virtual-scroller instance) so an unbounded cache leads
* to severe memory growth when the user switches between libraries.
*
* 3 slots is enough for productive back-navigation while keeping memory
* usage under control.
*/
const MAX_STORED_ROUTES = 3;
function paramsMatch(a: Params, b: Params): boolean {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
return aKeys.length === bKeys.length && aKeys.every(key => a[key] === b[key]);
}
@Injectable({
providedIn: 'root',
})
export class CustomReuseStrategy implements RouteReuseStrategy {
private storedRoutes = new Map<string, DetachedRouteHandle>();
/** Insertion-order queue so we can evict the oldest entry (LRU). */
private insertionOrder: string[] = [];
private scrollService = inject(BookBrowserScrollService);
private bookSelectionService = inject(BookSelectionService);
private readonly BOOK_BROWSER_PATHS = [
'all-books',
'unshelved-books',
'library/:libraryId/books',
'shelf/:shelfId/books',
'magic-shelf/:magicShelfId/books',
'authors',
'series'
];
private readonly BOOK_DETAILS_PATH = 'book/:bookId';
private getRouteKey(route: ActivatedRouteSnapshot): string {
const path = route.routeConfig?.path || '';
return this.scrollService.createKey(path, route.params);
}
private isBookBrowserRoute(route: ActivatedRouteSnapshot): boolean {
const path = route.routeConfig?.path;
return this.BOOK_BROWSER_PATHS.includes(path || '');
}
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return this.isBookBrowserRoute(route);
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
if (handle && this.isBookBrowserRoute(route)) {
const key = this.getRouteKey(route);
// If the key already exists, remove it from insertion order so it
// can be re-appended at the end (most-recently-used).
const existingIdx = this.insertionOrder.indexOf(key);
if (existingIdx !== -1) {
this.insertionOrder.splice(existingIdx, 1);
}
this.storedRoutes.set(key, handle);
this.insertionOrder.push(key);
this.bookSelectionService.deselectAll();
// Evict oldest routes when we exceed the budget.
while (this.insertionOrder.length > MAX_STORED_ROUTES) {
const evictKey = this.insertionOrder.shift()!;
const evictedHandle = this.storedRoutes.get(evictKey);
this.storedRoutes.delete(evictKey);
this.scrollService.clearPosition(evictKey);
if (evictedHandle) {
destroyDetachedRouteHandle(evictedHandle);
}
}
}
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
if (!this.isBookBrowserRoute(route)) {
return false;
}
const key = this.getRouteKey(route);
return this.storedRoutes.has(key);
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
const key = this.getRouteKey(route);
const handle = this.storedRoutes.get(key) || null;
if (handle) {
const savedPosition = this.scrollService.getPosition(key);
if (savedPosition !== undefined) {
setTimeout(() => {
const scrollElement = document.querySelector('.virtual-scroller');
if (scrollElement) {
(scrollElement as HTMLElement).scrollTop = savedPosition;
}
}, 0);
}
}
return handle;
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig &&
JSON.stringify(future.params) === JSON.stringify(curr.params);
export class CustomReuseStrategy extends BaseRouteReuseStrategy {
override shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig && paramsMatch(future.params, curr.params);
}
}