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
@@ -0,0 +1,17 @@
<div
class="browser-grid-options"
role="group"
[attr.aria-label]="'common.cardSizeControls' | transloco">
<button
type="button"
class="browser-grid-option-btn"
[attr.aria-label]="'common.decreaseCardSize' | transloco"
[title]="'common.decreaseCardSize' | transloco"
(click)="densityChange.emit('smaller')">−</button>
<button
type="button"
class="browser-grid-option-btn"
[attr.aria-label]="'common.increaseCardSize' | transloco"
[title]="'common.increaseCardSize' | transloco"
(click)="densityChange.emit('larger')">+</button>
</div>
@@ -0,0 +1,14 @@
import {Component, output} from '@angular/core';
import {TranslocoPipe} from '@jsverse/transloco';
export type GridDensityDirection = 'smaller' | 'larger';
@Component({
selector: 'app-grid-density-buttons',
standalone: true,
imports: [TranslocoPipe],
templateUrl: './grid-density-buttons.component.html',
})
export class GridDensityButtonsComponent {
readonly densityChange = output<GridDensityDirection>();
}
@@ -0,0 +1,62 @@
import {TestBed} from '@angular/core/testing';
import {ActivatedRoute, provideRouter} from '@angular/router';
import {beforeEach, describe, expect, it} from 'vitest';
import {RouteScrollPositionService} from './route-scroll-position.service';
describe('RouteScrollPositionService', () => {
let service: RouteScrollPositionService;
beforeEach(() => {
TestBed.configureTestingModule({providers: [provideRouter([])]});
service = TestBed.inject(RouteScrollPositionService);
});
it('stores and retrieves scroll positions by key', () => {
expect(service.getPosition('books')).toBeUndefined();
service.savePosition('books', 144);
service.savePosition('books:library', 288);
expect(service.getPosition('books')).toBe(144);
expect(service.getPosition('books:library')).toBe(288);
});
it('keeps recently used scroll positions when the cache reaches its limit', () => {
Array.from({length: 100}, (_, index) => service.savePosition(`route-${index}`, index));
expect(service.getPosition('route-0')).toBe(0);
service.savePosition('route-100', 100);
expect(service.getPosition('route-0')).toBe(0);
expect(service.getPosition('route-99')).toBe(99);
expect(service.getPosition('route-1')).toBeUndefined();
expect(service.getPosition('route-100')).toBe(100);
});
it('creates stable route keys regardless of parameter order', () => {
expect(service.createKey('/books', {libraryId: '1', shelfId: '2'})).toBe('/books:libraryId=1;shelfId=2');
expect(service.createKey('/books', {shelfId: '2', libraryId: '1'})).toBe('/books:libraryId=1;shelfId=2');
});
it('creates route keys from the full matched path', () => {
const route = {
snapshot: {
pathFromRoot: [
{url: []},
{url: [{path: 'authors'}]},
{url: [{path: '42'}]},
],
params: {id: '42'},
},
} as unknown as ActivatedRoute;
expect(service.keyFor(route)).toBe('authors/42:id=42');
});
it('encodes route key values and falls back to the path when params are empty', () => {
expect(service.createKey('/books', {slug: 'one-two', type: 'magic&shelf'})).toBe('/books:slug=one-two;type=magic%26shelf');
expect(service.createKey('/books', {})).toBe('/books');
});
});
@@ -0,0 +1,78 @@
import {DestroyRef, ElementRef, Injectable, Signal, inject} from '@angular/core';
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {filter} from 'rxjs/operators';
interface TrackRouteOptions {
scrollElement: Signal<ElementRef<HTMLElement> | undefined>;
route: ActivatedRoute;
destroyRef: DestroyRef;
dismissOverlaysBeforeSave?: boolean;
beforeSave?: () => void;
}
@Injectable({
providedIn: 'root'
})
export class RouteScrollPositionService {
private readonly MAX_SCROLL_POSITIONS = 100;
private readonly router = inject(Router);
private scrollPositions = new Map<string, number>();
savePosition(key: string, position: number): void {
this.scrollPositions.delete(key);
this.scrollPositions.set(key, position);
if (this.scrollPositions.size > this.MAX_SCROLL_POSITIONS) {
const oldestKey = this.scrollPositions.keys().next().value;
if (oldestKey !== undefined) {
this.scrollPositions.delete(oldestKey);
}
}
}
getPosition(key: string): number | undefined {
const position = this.scrollPositions.get(key);
if (position !== undefined) {
this.scrollPositions.delete(key);
this.scrollPositions.set(key, position);
}
return position;
}
createKey(path: string, params: Record<string, string>): string {
const paramPairs = Object.keys(params)
.sort((a, b) => a.localeCompare(b))
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join(';');
return paramPairs ? `${path}:${paramPairs}` : path;
}
keyFor(route: ActivatedRoute): string {
const path = route.snapshot.pathFromRoot
.flatMap(snapshot => snapshot.url)
.map(segment => segment.path)
.filter(Boolean)
.join('/');
return this.createKey(path, route.snapshot.params);
}
dismissBodyOverlays(): void {
document.querySelectorAll('.p-tieredmenu-overlay').forEach(el => el.remove());
}
trackRoute(options: TrackRouteOptions): void {
this.router.events.pipe(
filter((event): event is NavigationStart => event instanceof NavigationStart),
takeUntilDestroyed(options.destroyRef),
).subscribe(() => {
if (options.dismissOverlaysBeforeSave) {
this.dismissBodyOverlays();
}
options.beforeSave?.();
const element = options.scrollElement()?.nativeElement;
if (element) {
this.savePosition(this.keyFor(options.route), element.scrollTop);
}
});
}
}
@@ -1,36 +0,0 @@
import { describe, it, expect } from 'vitest';
import { chunk } from './array.util';
describe('ArrayUtils', () => {
describe('chunk', () => {
it('should split an array into chunks of the specified size', () => {
const input = [1, 2, 3, 4, 5];
const result = chunk(input, 2);
expect(result).toEqual([[1, 2], [3, 4], [5]]);
});
it('should return an empty array if the input array is empty', () => {
const input: number[] = [];
const result = chunk(input, 2);
expect(result).toEqual([]);
});
it('should return the original array in a single chunk if the size is larger than the array length', () => {
const input = [1, 2, 3];
const result = chunk(input, 5);
expect(result).toEqual([[1, 2, 3]]);
});
it('should handle a chunk size of 1', () => {
const input = [1, 2, 3];
const result = chunk(input, 1);
expect(result).toEqual([[1], [2], [3]]);
});
it('should return the entire array in a single chunk if the size is 0 or negative', () => {
const input = [1, 2, 3];
expect(chunk(input, 0)).toEqual([[1, 2, 3]]);
expect(chunk(input, -1)).toEqual([[1, 2, 3]]);
});
});
});
@@ -1,18 +0,0 @@
/**
* Splits an array into chunks of a given size.
*
* @param array The array to split.
* @param size The size of each chunk.
* @returns An array of chunks.
*/
export function chunk<T>(array: T[], size: number): T[][] {
if (size <= 0) {
return array.length > 0 ? [[...array]] : [];
}
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
@@ -0,0 +1,62 @@
import {Signal, WritableSignal, signal} from '@angular/core';
import {LocalStorageService} from '../service/local-storage.service';
interface ScalePreferenceConfig {
storageKey: string;
minScale: number;
maxScale: number;
defaultScale?: number;
}
export class ScalePreference {
private readonly _scaleFactor: WritableSignal<number>;
readonly scaleFactor: Signal<number>;
private lastPersistedScale: number;
constructor(
private readonly localStorageService: LocalStorageService,
private readonly config: ScalePreferenceConfig
) {
const initialScale = this.loadScalePreference();
this._scaleFactor = signal(initialScale);
this.scaleFactor = this._scaleFactor.asReadonly();
this.lastPersistedScale = initialScale;
}
setScale(scale: number): void {
const normalizedScale = this.clampScale(scale);
this._scaleFactor.set(normalizedScale);
if (normalizedScale === this.lastPersistedScale) {
return;
}
this.saveScalePreference(normalizedScale);
}
private loadScalePreference(): number {
const saved = this.localStorageService.get<number>(this.config.storageKey);
if (typeof saved === 'number' && !Number.isNaN(saved)) {
const clamped = this.clampScale(saved);
if (clamped !== saved) {
this.localStorageService.set(this.config.storageKey, clamped);
}
return clamped;
}
return this.defaultScale;
}
private saveScalePreference(scale: number): void {
this.localStorageService.set(this.config.storageKey, scale);
this.lastPersistedScale = scale;
}
private clampScale(scale: number): number {
if (Number.isNaN(scale)) {
return this.defaultScale;
}
return Math.min(this.config.maxScale, Math.max(this.config.minScale, scale));
}
private get defaultScale(): number {
return this.config.defaultScale ?? 1.0;
}
}
@@ -1,6 +0,0 @@
export function computeGridColumns(containerWidth: number, minColumnWidth: number, gap: number = 21): number {
if (containerWidth <= 0 || minColumnWidth <= 0) {
return 1;
}
return Math.max(1, Math.floor((containerWidth + gap) / (minColumnWidth + gap)));
}
@@ -0,0 +1,174 @@
import {ElementRef, Signal, computed, effect, signal} from '@angular/core';
import {injectVirtualizer} from '@tanstack/angular-virtual';
import {observeElementRect, type VirtualItem} from '@tanstack/virtual-core';
const DEFAULT_OVERSCAN_ROWS = 2;
const DEFAULT_ITEM_SIZE = 1;
export interface VirtualGridOptions {
items: Signal<readonly unknown[]>;
scrollElement: Signal<ElementRef<HTMLElement> | undefined>;
minItemWidth: Signal<number>;
estimateItemHeight: (itemWidth: number) => number;
gap: number | Signal<number>;
overscan?: number;
count?: Signal<number>;
columns?: Signal<number | undefined>;
initialOffset?: () => number;
fillItemWidth?: boolean;
enabled?: Signal<boolean>;
}
function getScrollContentWidth(element: HTMLElement | null): number {
if (!element) {
return 0;
}
const style = getComputedStyle(element);
const horizontalPadding = parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
return Math.max(0, element.clientWidth - horizontalPadding);
}
function computeGridColumns(containerWidth: number, minColumnWidth: number, gap: number): number {
if (containerWidth <= 0 || minColumnWidth <= 0) {
return 1;
}
return toSafeInteger((containerWidth + gap) / (minColumnWidth + gap), 1);
}
function toSafeInteger(value: number | undefined, fallback = 0): number {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
}
function toSafeSize(value: number | undefined, fallback: number): number {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
}
export function scaleForGridColumns(
viewportWidth: number,
gap: number,
columns: number,
baseWidth: number,
minScale: number,
maxScale: number
): number {
const targetColumns = Math.max(1, Math.round(columns));
// scaleForGridColumns uses +0.5 so computeGridColumns' floor settles on targetColumns.
const targetWidth = ((viewportWidth + gap) / (targetColumns + 0.5)) - gap;
const scale = targetWidth / baseWidth;
return Math.min(maxScale, Math.max(minScale, scale));
}
/**
* Creates a TanStack virtual grid inside Angular's injection context.
*
* Because this calls injectVirtualizer() and effect(), call it from a field
* initializer, constructor, or runInInjectionContext(); lifecycle hooks such as
* ngOnInit will throw NG0203 unless wrapped in runInInjectionContext().
*/
export function createVirtualGrid(options: VirtualGridOptions) {
const viewportWidth = signal(0);
const gap = computed(() => typeof options.gap === 'number' ? options.gap : options.gap());
const gridColumns = computed(() => {
const columns = options.columns?.();
const safeColumns = toSafeInteger(columns);
if (safeColumns > 0) {
return safeColumns;
}
return computeGridColumns(viewportWidth(), options.minItemWidth(), gap());
});
const itemWidth = computed(() => {
if (!options.fillItemWidth) {
return options.minItemWidth();
}
const columns = gridColumns();
const availableWidth = viewportWidth();
if (columns <= 0 || availableWidth <= 0) {
return options.minItemWidth();
}
const totalGap = (columns - 1) * gap();
return Math.max(options.minItemWidth(), (availableWidth - totalGap) / columns);
});
const itemHeight = computed(() => options.estimateItemHeight(itemWidth()));
const enabled = computed(() => !!options.scrollElement() && (options.enabled?.() ?? true));
const columnGap = computed(() => {
if (options.fillItemWidth) {
return gap();
}
const columns = gridColumns();
if (columns <= 1) {
return gap();
}
const remainingWidth = viewportWidth() - (columns * itemWidth());
return Math.max(gap(), remainingWidth / (columns - 1));
});
const virtualizer = injectVirtualizer<HTMLElement, HTMLElement>(() => ({
scrollElement: options.scrollElement(),
count: toSafeInteger(options.count?.() ?? options.items().length),
estimateSize: () => toSafeSize(itemHeight(), DEFAULT_ITEM_SIZE),
overscan: toSafeInteger(options.overscan ?? gridColumns() * DEFAULT_OVERSCAN_ROWS, DEFAULT_OVERSCAN_ROWS),
gap: toSafeSize(columnGap(), DEFAULT_ITEM_SIZE),
lanes: toSafeInteger(gridColumns(), 1),
enabled: enabled(),
initialOffset: () => options.initialOffset?.() ?? 0,
observeElementRect: (instance, callback) => observeElementRect(instance, rect => {
callback(rect);
viewportWidth.set(Math.round(getScrollContentWidth(instance.scrollElement)));
}),
}));
// Reset measured sizes when geometry changes; otherwise density toggles flash.
effect(() => {
itemHeight();
gridColumns();
columnGap();
if (enabled()) {
queueMicrotask(() => virtualizer.measure());
}
});
const updatePreservingScrollPosition = (update: () => void): void => {
const scrollElement = options.scrollElement()?.nativeElement;
if (!scrollElement) {
update();
return;
}
const scrollTop = scrollElement.scrollTop;
const maxScrollTop = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
const scrollRatio = maxScrollTop > 0 ? scrollTop / maxScrollTop : 0;
update();
const restoreScrollPosition = (): void => {
virtualizer.measure();
const nextMaxScrollTop = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
virtualizer.scrollToOffset(nextMaxScrollTop * scrollRatio);
};
queueMicrotask(() => {
requestAnimationFrame(() => {
restoreScrollPosition();
requestAnimationFrame(restoreScrollPosition);
});
});
};
return {
viewportWidth,
gridColumns,
itemWidth,
itemHeight,
itemTransform: (item: VirtualItem) =>
`translateX(${item.lane * (itemWidth() + columnGap())}px) translateY(${item.start}px)`,
updatePreservingScrollPosition,
virtualizer,
};
}