fix(dashboard): improve performance with OnPush change detection (#440)

* fix(dashboard): improve performance with OnPush change detection

* fix(dashboard): refactor book card component for improved readability and performance

* fix(tests): mock matchMedia for improved test compatibility

* fix(tests): matchMedia mock for better CI compatibility and support

* fix(dashboard): add clearAll method to BookBrowserScrollService and update tests

* fix(dashboard): improve performance with content visibility and refactor styles

* fix(dashboard): improve scroll performance with estimated total height and refactor layout

* fix(tests): add mock for getCurrentUser in userService for improved test coverage

* fix(dashboard): implement infinite scroll for book loading and scroll restoration

* fix(tests): fix lint error

* fix(tests): mock ResizeObserver and IntersectionObserver

* fix(tests): mock ResizeObserver and IntersectionObserver (again)

* fix(dashboard): improve accessibility and performance by updating aria attributes and optimizing animations

* fix(dashboard): improve submenu accessibility and optimize virtual scroller performance

* fix(dashboard): clean up imports and improve component structure

* fix(dashboard): correct mobile check in author browser component

* fix(dashboard): add OnDestroy lifecycle hook to BookBrowserComponent
This commit is contained in:
brios
2026-04-22 17:27:11 -04:00
committed by Zach Yale
parent a779de8f57
commit 85e8d235b6
140 changed files with 1546 additions and 1233 deletions
@@ -14,7 +14,7 @@ function createRoute(path: string, params: Record<string, string> = {}): Activat
}
describe('CustomReuseStrategy', () => {
const handle = {componentRef: {} as never} as DetachedRouteHandle;
const handle = {componentRef: {destroy: vi.fn()} as never} as DetachedRouteHandle;
let strategy: CustomReuseStrategy;
let scrollService: BookBrowserScrollService;
@@ -122,4 +122,72 @@ describe('CustomReuseStrategy', () => {
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);
});
});
+34 -1
View File
@@ -1,13 +1,26 @@
import {inject, Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
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';
/**
* 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;
@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);
@@ -40,8 +53,28 @@ export class CustomReuseStrategy implements RouteReuseStrategy {
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);
}
}
}
}
+21 -1
View File
@@ -1,4 +1,4 @@
import {signal, type EnvironmentProviders, type Provider, type WritableSignal} from '@angular/core';
import {ApplicationRef, provideZonelessChangeDetection, signal, type EnvironmentProviders, type Provider, type WritableSignal} from '@angular/core';
import {provideHttpClient} from '@angular/common/http';
import {provideHttpClientTesting} from '@angular/common/http/testing';
import {TestBed} from '@angular/core/testing';
@@ -28,6 +28,7 @@ export function createQueryClientHarness(): QueryClientHarness {
return {
queryClient,
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideHttpClientTesting(),
provideTanStackQuery(queryClient),
@@ -38,3 +39,22 @@ export function createQueryClientHarness(): QueryClientHarness {
export function flushSignalAndQueryEffects(): void {
TestBed.flushEffects();
}
/**
* Asynchronously flushes Angular effects and query state across multiple rounds.
* Use this for tests involving async operations like HTTP requests or timers.
* For synchronous signal/effect flushing, use `flushSignalAndQueryEffects()` instead.
*
* @param rounds Number of cycles to await macrotask and microtask resolutions. Defaults to 5.
*/
export async function flushQueryAsync(rounds = 5): Promise<void> {
const appRef = TestBed.inject(ApplicationRef);
for (let i = 0; i < rounds; i++) {
TestBed.flushEffects();
appRef.tick();
await Promise.resolve();
await new Promise(resolve => setTimeout(resolve, 0));
}
TestBed.flushEffects();
appRef.tick();
}