refactor(ui): unify author/series/book browsers using tanstack virtual (#941)
This commit is contained in:
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user