refactor(ui): unify author/series/book browsers using tanstack virtual (#941)
This commit is contained in:
@@ -24,7 +24,6 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular/animations": "^21.2.10",
|
"@angular/animations": "^21.2.10",
|
||||||
"@angular/cdk": "^21.2.8",
|
"@angular/cdk": "^21.2.8",
|
||||||
"@angular/cdk-experimental": "^21.2.8",
|
|
||||||
"@angular/common": "^21.2.10",
|
"@angular/common": "^21.2.10",
|
||||||
"@angular/compiler": "^21.2.10",
|
"@angular/compiler": "^21.2.10",
|
||||||
"@angular/core": "^21.2.10",
|
"@angular/core": "^21.2.10",
|
||||||
@@ -40,6 +39,7 @@
|
|||||||
"@stomp/rx-stomp": "^2.3.0",
|
"@stomp/rx-stomp": "^2.3.0",
|
||||||
"@stomp/stompjs": "^7.3.0",
|
"@stomp/stompjs": "^7.3.0",
|
||||||
"@tanstack/angular-query-experimental": "5.100.1",
|
"@tanstack/angular-query-experimental": "5.100.1",
|
||||||
|
"@tanstack/angular-virtual": "^4.0.13",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
"chartjs-chart-matrix": "^3.0.0",
|
"chartjs-chart-matrix": "^3.0.0",
|
||||||
"chartjs-plugin-datalabels": "^2.2.0",
|
"chartjs-plugin-datalabels": "^2.2.0",
|
||||||
|
|||||||
@@ -1,193 +1,30 @@
|
|||||||
import {Injector, runInInjectionContext} from '@angular/core';
|
import {ActivatedRouteSnapshot, Route} from '@angular/router';
|
||||||
import {ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';
|
import {describe, expect, it} from 'vitest';
|
||||||
import {afterEach, beforeEach, describe, expect, it, vi} 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';
|
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 {
|
return {
|
||||||
routeConfig: {path},
|
routeConfig,
|
||||||
params
|
params
|
||||||
} as ActivatedRouteSnapshot;
|
} as ActivatedRouteSnapshot;
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('CustomReuseStrategy', () => {
|
describe('CustomReuseStrategy', () => {
|
||||||
const handle = {componentRef: {destroy: vi.fn()} as never} as DetachedRouteHandle;
|
const strategy = new CustomReuseStrategy();
|
||||||
|
|
||||||
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();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reuses routes only when the route config and params both match', () => {
|
it('reuses routes only when the route config and params both match', () => {
|
||||||
const routeConfig = {path: 'series'};
|
const routeConfig = {path: 'series'};
|
||||||
const current = {
|
const current = createRoute(routeConfig, {seriesId: '12'});
|
||||||
routeConfig,
|
const same = createRoute(routeConfig, {seriesId: '12'});
|
||||||
params: {seriesId: '12'}
|
const sameDifferentOrder = createRoute(routeConfig, {tab: 'books', seriesId: '12'});
|
||||||
} as unknown as ActivatedRouteSnapshot;
|
const currentWithTab = createRoute(routeConfig, {seriesId: '12', tab: 'books'});
|
||||||
const same = {
|
const differentParams = createRoute(routeConfig, {seriesId: '99'});
|
||||||
routeConfig,
|
const differentConfig = createRoute({path: 'authors'}, {seriesId: '12'});
|
||||||
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;
|
|
||||||
|
|
||||||
expect(strategy.shouldReuseRoute(same, current)).toBe(true);
|
expect(strategy.shouldReuseRoute(same, current)).toBe(true);
|
||||||
|
expect(strategy.shouldReuseRoute(sameDifferentOrder, currentWithTab)).toBe(true);
|
||||||
expect(strategy.shouldReuseRoute(differentParams, current)).toBe(false);
|
expect(strategy.shouldReuseRoute(differentParams, current)).toBe(false);
|
||||||
expect(strategy.shouldReuseRoute(differentConfig, 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);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,112 +1,17 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {Injectable} from '@angular/core';
|
||||||
import {ActivatedRouteSnapshot, DetachedRouteHandle, destroyDetachedRouteHandle, RouteReuseStrategy} from '@angular/router';
|
import {ActivatedRouteSnapshot, BaseRouteReuseStrategy, Params} 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';
|
|
||||||
|
|
||||||
/**
|
function paramsMatch(a: Params, b: Params): boolean {
|
||||||
* Maximum number of detached BookBrowser routes kept in memory.
|
const aKeys = Object.keys(a);
|
||||||
* Each cached route retains its full component tree (book cards, images,
|
const bKeys = Object.keys(b);
|
||||||
* event listeners, virtual-scroller instance) so an unbounded cache leads
|
return aKeys.length === bKeys.length && aKeys.every(key => a[key] === b[key]);
|
||||||
* 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({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class CustomReuseStrategy implements RouteReuseStrategy {
|
export class CustomReuseStrategy extends BaseRouteReuseStrategy {
|
||||||
private storedRoutes = new Map<string, DetachedRouteHandle>();
|
override shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
|
||||||
/** Insertion-order queue so we can evict the oldest entry (LRU). */
|
return future.routeConfig === curr.routeConfig && paramsMatch(future.params, curr.params);
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+28
-39
@@ -54,17 +54,7 @@
|
|||||||
<p-popover #displaySettingsPopover>
|
<p-popover #displaySettingsPopover>
|
||||||
<div class="display-settings-content">
|
<div class="display-settings-content">
|
||||||
<span class="display-settings-label">{{ t('cardSize') }}</span>
|
<span class="display-settings-label">{{ t('cardSize') }}</span>
|
||||||
<p-slider
|
<app-grid-density-buttons (densityChange)="adjustDesktopGridDensity($event)"/>
|
||||||
[ngModel]="authorScaleService.scaleFactor()"
|
|
||||||
(ngModelChange)="authorScaleService.setScale($event)"
|
|
||||||
[min]="0.7"
|
|
||||||
[max]="1.3"
|
|
||||||
[step]="0.01"
|
|
||||||
[style]="{ width: '100%' }">
|
|
||||||
</p-slider>
|
|
||||||
<div class="scale-value-display">
|
|
||||||
{{ authorScaleService.scaleFactor().toFixed(2) }}x
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</p-popover>
|
</p-popover>
|
||||||
}
|
}
|
||||||
@@ -193,36 +183,35 @@
|
|||||||
<p>{{ t('noAuthorsFound') }}</p>
|
<p>{{ t('noAuthorsFound') }}</p>
|
||||||
</div>
|
</div>
|
||||||
} @else {
|
} @else {
|
||||||
<cdk-virtual-scroll-viewport autosize
|
<div #scrollElement class="virtual-scroller">
|
||||||
[minBufferPx]="600" [maxBufferPx]="1200"
|
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
|
||||||
#scroll
|
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
|
||||||
class="virtual-scroller">
|
@if (authorList[virtualItem.index]; as author) {
|
||||||
<div class="author-grid"
|
<div
|
||||||
*cdkVirtualFor="let row of authorRows(); let rowIndex = index"
|
class="virtual-cell"
|
||||||
[ngStyle]="{'grid-template-columns': 'repeat(' + gridColumns() + ', 1fr)'}">
|
[style.width.px]="virtualGrid.itemWidth()"
|
||||||
@for (author of row; track author.id; let colIdx = $index) {
|
[style.height.px]="virtualItem.size"
|
||||||
<div class="virtual-scroller-item"
|
[style.transform]="virtualGrid.itemTransform(virtualItem)">
|
||||||
[ngStyle]="{width: cardWidth() + 'px', height: cardHeight() + 'px'}"
|
<app-author-card
|
||||||
[style.--card-scale]="authorScaleService.scaleFactor()">
|
[author]="author"
|
||||||
<app-author-card
|
[index]="virtualItem.index"
|
||||||
[author]="author"
|
[cacheBuster]="thumbnailCacheBusters.get(author.id) || 0"
|
||||||
[index]="rowIndex * gridColumns() + colIdx"
|
[canQuickMatch]="canEditMetadata"
|
||||||
[cacheBuster]="thumbnailCacheBusters.get(author.id) || 0"
|
[canDelete]="canDeleteBook"
|
||||||
[canQuickMatch]="canEditMetadata"
|
[isCheckboxEnabled]="canEditMetadata || canDeleteBook"
|
||||||
[canDelete]="canDeleteBook"
|
[isSelected]="isAuthorSelected(author.id)"
|
||||||
[isCheckboxEnabled]="canEditMetadata || canDeleteBook"
|
(cardClick)="navigateToAuthor($event)"
|
||||||
[isSelected]="isAuthorSelected(author.id)"
|
(viewAuthor)="navigateToAuthor($event)"
|
||||||
(cardClick)="navigateToAuthor($event)"
|
(editAuthor)="navigateToAuthorEdit($event)"
|
||||||
(viewAuthor)="navigateToAuthor($event)"
|
(deleteAuthor)="deleteAuthor($event)"
|
||||||
(editAuthor)="navigateToAuthorEdit($event)"
|
(quickMatched)="onAuthorQuickMatched($event)"
|
||||||
(deleteAuthor)="deleteAuthor($event)"
|
(checkboxClick)="onCheckboxClicked($event)">
|
||||||
(quickMatched)="onAuthorQuickMatched($event)"
|
</app-author-card>
|
||||||
(checkboxClick)="onCheckboxClicked($event)">
|
</div>
|
||||||
</app-author-card>
|
}
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</cdk-virtual-scroll-viewport>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
-22
@@ -107,12 +107,6 @@
|
|||||||
color: #e2e8f0;
|
color: #e2e8f0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scale-value-display {
|
|
||||||
text-align: center;
|
|
||||||
font-size: 0.8rem;
|
|
||||||
color: #94a3b8;
|
|
||||||
}
|
|
||||||
|
|
||||||
.filter-popover-content {
|
.filter-popover-content {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -164,22 +158,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.author-grid {
|
|
||||||
display: grid;
|
|
||||||
gap: 1.25rem;
|
|
||||||
place-items: start center;
|
|
||||||
width: 100%;
|
|
||||||
padding-top: 1rem;
|
|
||||||
padding-right: 1rem;
|
|
||||||
padding-left: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.virtual-scroller-item {
|
|
||||||
position: relative;
|
|
||||||
overflow: visible;
|
|
||||||
transition: width 0.2s ease, height 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.empty-state {
|
.empty-state {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
+63
-86
@@ -1,33 +1,28 @@
|
|||||||
import {Component, computed, DestroyRef, effect, HostListener, inject, OnInit, signal, ViewChild} from '@angular/core';
|
import {Component, computed, DestroyRef, effect, ElementRef, HostListener, inject, OnInit, signal, viewChild} from '@angular/core';
|
||||||
import {computeGridColumns} from '../../../../shared/util/viewport.util';
|
|
||||||
import {NgStyle} from '@angular/common';
|
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
|
||||||
import {filter} from 'rxjs/operators';
|
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {InputText} from 'primeng/inputtext';
|
import {InputText} from 'primeng/inputtext';
|
||||||
import {Select} from 'primeng/select';
|
import {Select} from 'primeng/select';
|
||||||
import {Slider} from 'primeng/slider';
|
|
||||||
import {Popover} from 'primeng/popover';
|
import {Popover} from 'primeng/popover';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {Divider} from 'primeng/divider';
|
import {Divider} from 'primeng/divider';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
import {CdkVirtualScrollViewport, CdkVirtualForOf} from '@angular/cdk/scrolling';
|
import {RouteScrollPositionService} from '../../../../shared/service/route-scroll-position.service';
|
||||||
import {CdkAutoSizeVirtualScroll} from '@angular/cdk-experimental/scrolling';
|
|
||||||
import {BookBrowserScrollService} from '../../../book/components/book-browser/book-browser-scroll.service';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {AuthorService} from '../../service/author.service';
|
import {AuthorService} from '../../service/author.service';
|
||||||
import {AuthorSummary, EnrichedAuthor, AuthorFilters, DEFAULT_AUTHOR_FILTERS} from '../../model/author.model';
|
import {AuthorSummary, EnrichedAuthor, AuthorFilters, DEFAULT_AUTHOR_FILTERS} from '../../model/author.model';
|
||||||
import {AuthorCardComponent} from '../author-card/author-card.component';
|
import {AuthorCardComponent} from '../author-card/author-card.component';
|
||||||
import {chunk} from '../../../../shared/util/array.util';
|
|
||||||
import {AuthorScalePreferenceService} from '../../service/author-scale-preference.service';
|
|
||||||
import {AuthorSelectionService, AuthorCheckboxClickEvent} from '../../service/author-selection.service';
|
import {AuthorSelectionService, AuthorCheckboxClickEvent} from '../../service/author-selection.service';
|
||||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||||
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {BookService} from '../../../book/service/book.service';
|
import {BookService} from '../../../book/service/book.service';
|
||||||
import {Book, ReadStatus} from '../../../book/model/book.model';
|
import {Book, ReadStatus} from '../../../book/model/book.model';
|
||||||
|
import {createVirtualGrid, scaleForGridColumns} from '../../../../shared/util/virtual-grid.util';
|
||||||
|
import {GridDensityButtonsComponent} from '../../../../shared/components/grid-density-buttons/grid-density-buttons.component';
|
||||||
|
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||||
|
import {ScalePreference} from '../../../../shared/util/scale-preference.util';
|
||||||
|
|
||||||
type SortDirection = 'asc' | 'desc';
|
type SortDirection = 'asc' | 'desc';
|
||||||
|
|
||||||
@@ -59,21 +54,17 @@ const DEFAULT_SORT_DIRECTIONS: Record<string, SortDirection> = {
|
|||||||
templateUrl: './author-browser.component.html',
|
templateUrl: './author-browser.component.html',
|
||||||
styleUrls: ['./author-browser.component.scss'],
|
styleUrls: ['./author-browser.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
NgStyle,
|
|
||||||
FormsModule,
|
FormsModule,
|
||||||
ProgressSpinner,
|
ProgressSpinner,
|
||||||
InputText,
|
InputText,
|
||||||
Select,
|
Select,
|
||||||
Slider,
|
|
||||||
Popover,
|
Popover,
|
||||||
Button,
|
Button,
|
||||||
Divider,
|
Divider,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
TranslocoDirective,
|
TranslocoDirective,
|
||||||
|
GridDensityButtonsComponent,
|
||||||
AuthorCardComponent,
|
AuthorCardComponent,
|
||||||
CdkVirtualScrollViewport,
|
|
||||||
CdkVirtualForOf,
|
|
||||||
CdkAutoSizeVirtualScroll,
|
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
export class AuthorBrowserComponent implements OnInit {
|
export class AuthorBrowserComponent implements OnInit {
|
||||||
@@ -82,39 +73,32 @@ export class AuthorBrowserComponent implements OnInit {
|
|||||||
private static readonly BASE_HEIGHT = 290;
|
private static readonly BASE_HEIGHT = 290;
|
||||||
private static readonly MOBILE_BASE_WIDTH = 140;
|
private static readonly MOBILE_BASE_WIDTH = 140;
|
||||||
private static readonly MOBILE_BASE_HEIGHT = 250;
|
private static readonly MOBILE_BASE_HEIGHT = 250;
|
||||||
|
private static readonly SCALE_STORAGE_KEY = 'authorScalePreference';
|
||||||
|
private static readonly MIN_SCALE = 0.7;
|
||||||
|
private static readonly MAX_SCALE = 1.3;
|
||||||
|
|
||||||
private authorService = inject(AuthorService);
|
private authorService = inject(AuthorService);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private pageTitle = inject(PageTitleService);
|
private pageTitle = inject(PageTitleService);
|
||||||
private scrollService = inject(BookBrowserScrollService);
|
private scrollService = inject(RouteScrollPositionService);
|
||||||
private t = inject(TranslocoService);
|
private t = inject(TranslocoService);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private activatedRoute = inject(ActivatedRoute);
|
private activatedRoute = inject(ActivatedRoute);
|
||||||
private destroyRef = inject(DestroyRef);
|
private destroyRef = inject(DestroyRef);
|
||||||
|
private localStorageService = inject(LocalStorageService);
|
||||||
protected userService = inject(UserService);
|
protected userService = inject(UserService);
|
||||||
protected authorScaleService = inject(AuthorScalePreferenceService);
|
|
||||||
protected selectionService = inject(AuthorSelectionService);
|
protected selectionService = inject(AuthorSelectionService);
|
||||||
|
|
||||||
virtualScroller: CdkVirtualScrollViewport | undefined;
|
|
||||||
|
|
||||||
@ViewChild('scroll')
|
|
||||||
set scrollViewport(vp: CdkVirtualScrollViewport | undefined) {
|
|
||||||
this.virtualScroller = vp;
|
|
||||||
this.viewportResizeObserver?.disconnect();
|
|
||||||
if (vp) {
|
|
||||||
const el = vp.elementRef.nativeElement as HTMLElement;
|
|
||||||
this.viewportWidth.set(el.clientWidth);
|
|
||||||
this.viewportResizeObserver = new ResizeObserver(entries => {
|
|
||||||
this.viewportWidth.set(entries[0]?.contentRect.width ?? el.clientWidth);
|
|
||||||
});
|
|
||||||
this.viewportResizeObserver.observe(el);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly GRID_GAP = 20;
|
private static readonly GRID_GAP = 20;
|
||||||
private readonly viewportWidth = signal(0);
|
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
|
||||||
private viewportResizeObserver: ResizeObserver | undefined;
|
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute)) ?? 0;
|
||||||
|
private readonly scalePreference = new ScalePreference(this.localStorageService, {
|
||||||
|
storageKey: AuthorBrowserComponent.SCALE_STORAGE_KEY,
|
||||||
|
minScale: AuthorBrowserComponent.MIN_SCALE,
|
||||||
|
maxScale: AuthorBrowserComponent.MAX_SCALE,
|
||||||
|
});
|
||||||
|
private readonly scaleFactor = this.scalePreference.scaleFactor;
|
||||||
|
|
||||||
readonly screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
|
readonly screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
|
||||||
thumbnailCacheBusters = new Map<number, number>();
|
thumbnailCacheBusters = new Map<number, number>();
|
||||||
@@ -204,29 +188,25 @@ export class AuthorBrowserComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
readonly isMobile = computed(() => this.screenWidth() <= 767);
|
readonly isMobile = computed(() => this.screenWidth() <= 767);
|
||||||
|
private readonly baseCardWidth = computed(() => this.isMobile()
|
||||||
readonly cardWidth = computed(() => {
|
? AuthorBrowserComponent.MOBILE_BASE_WIDTH
|
||||||
const base = this.isMobile()
|
: AuthorBrowserComponent.BASE_WIDTH
|
||||||
? AuthorBrowserComponent.MOBILE_BASE_WIDTH
|
);
|
||||||
: AuthorBrowserComponent.BASE_WIDTH;
|
private readonly cardAspectRatio = computed(() => {
|
||||||
return Math.round(base * this.authorScaleService.scaleFactor());
|
const baseHeight = this.isMobile()
|
||||||
});
|
|
||||||
|
|
||||||
readonly cardHeight = computed(() => {
|
|
||||||
const base = this.isMobile()
|
|
||||||
? AuthorBrowserComponent.MOBILE_BASE_HEIGHT
|
? AuthorBrowserComponent.MOBILE_BASE_HEIGHT
|
||||||
: AuthorBrowserComponent.BASE_HEIGHT;
|
: AuthorBrowserComponent.BASE_HEIGHT;
|
||||||
return Math.round(base * this.authorScaleService.scaleFactor());
|
return baseHeight / this.baseCardWidth();
|
||||||
});
|
});
|
||||||
|
private readonly minCardWidth = computed(() => Math.round(this.baseCardWidth() * this.scaleFactor()));
|
||||||
readonly gridColumnMinWidth = computed(() => `${this.cardWidth()}px`);
|
readonly virtualGrid = createVirtualGrid({
|
||||||
|
items: this.filteredAuthors,
|
||||||
readonly gridColumns = computed(() => {
|
scrollElement: this.scrollElement,
|
||||||
return computeGridColumns(this.viewportWidth(), this.cardWidth() || 165, AuthorBrowserComponent.GRID_GAP);
|
minItemWidth: this.minCardWidth,
|
||||||
});
|
gap: AuthorBrowserComponent.GRID_GAP,
|
||||||
|
initialOffset: this.initialScrollOffset,
|
||||||
readonly authorRows = computed(() => {
|
fillItemWidth: true,
|
||||||
return chunk(this.filteredAuthors(), this.gridColumns());
|
estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()),
|
||||||
});
|
});
|
||||||
|
|
||||||
sortOptions: SortOption[] = [];
|
sortOptions: SortOption[] = [];
|
||||||
@@ -238,7 +218,6 @@ export class AuthorBrowserComponent implements OnInit {
|
|||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.pageTitle.setPageTitle(this.t.translate('authorBrowser.pageTitle'));
|
this.pageTitle.setPageTitle(this.t.translate('authorBrowser.pageTitle'));
|
||||||
this.destroyRef.onDestroy(() => this.viewportResizeObserver?.disconnect());
|
|
||||||
|
|
||||||
this.sortOptions = [
|
this.sortOptions = [
|
||||||
{label: this.t.translate('authorBrowser.sort.name'), value: 'name'},
|
{label: this.t.translate('authorBrowser.sort.name'), value: 'name'},
|
||||||
@@ -259,11 +238,36 @@ export class AuthorBrowserComponent implements OnInit {
|
|||||||
this.sortDirection.set(dirParam === 'asc' || dirParam === 'desc' ? dirParam : DEFAULT_SORT_DIRECTIONS[sortParam]);
|
this.sortDirection.set(dirParam === 'asc' || dirParam === 'desc' ? dirParam : DEFAULT_SORT_DIRECTIONS[sortParam]);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.setupScrollPositionTracking();
|
this.scrollService.trackRoute({
|
||||||
|
scrollElement: this.scrollElement,
|
||||||
|
route: this.activatedRoute,
|
||||||
|
destroyRef: this.destroyRef,
|
||||||
|
dismissOverlaysBeforeSave: true,
|
||||||
|
});
|
||||||
this.destroyRef.onDestroy(() => this.selectionService.deselectAll());
|
this.destroyRef.onDestroy(() => this.selectionService.deselectAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
adjustDesktopGridDensity(direction: 'smaller' | 'larger'): void {
|
||||||
|
const currentColumns = this.virtualGrid.gridColumns();
|
||||||
|
const columns = Math.max(1, direction === 'smaller'
|
||||||
|
? currentColumns + 1
|
||||||
|
: currentColumns - 1);
|
||||||
|
const viewportWidth = this.virtualGrid.viewportWidth() || this.screenWidth();
|
||||||
|
this.virtualGrid.updatePreservingScrollPosition(() => {
|
||||||
|
this.setScale(scaleForGridColumns(
|
||||||
|
viewportWidth,
|
||||||
|
AuthorBrowserComponent.GRID_GAP,
|
||||||
|
columns,
|
||||||
|
this.baseCardWidth(),
|
||||||
|
AuthorBrowserComponent.MIN_SCALE,
|
||||||
|
AuthorBrowserComponent.MAX_SCALE
|
||||||
|
));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private setScale(scale: number): void {
|
||||||
|
this.scalePreference.setScale(scale);
|
||||||
|
}
|
||||||
|
|
||||||
onSearchChange(value: string): void {
|
onSearchChange(value: string): void {
|
||||||
this.searchTerm.set(value);
|
this.searchTerm.set(value);
|
||||||
@@ -524,33 +528,6 @@ export class AuthorBrowserComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private getScrollPositionKey(): string {
|
|
||||||
const path = this.activatedRoute.snapshot.routeConfig?.path ?? '';
|
|
||||||
return this.scrollService.createKey(path, this.activatedRoute.snapshot.params);
|
|
||||||
}
|
|
||||||
|
|
||||||
private setupScrollPositionTracking(): void {
|
|
||||||
this.router.events.pipe(
|
|
||||||
filter(event => event instanceof NavigationStart),
|
|
||||||
takeUntilDestroyed(this.destroyRef)
|
|
||||||
).subscribe(() => {
|
|
||||||
this.dismissBodyMenus();
|
|
||||||
this.saveScrollPosition();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private dismissBodyMenus(): void {
|
|
||||||
document.querySelectorAll('.p-tieredmenu-overlay').forEach(el => el.remove());
|
|
||||||
}
|
|
||||||
|
|
||||||
private saveScrollPosition(): void {
|
|
||||||
if (this.virtualScroller) {
|
|
||||||
const key = this.getScrollPositionKey();
|
|
||||||
const position = this.virtualScroller.measureScrollOffset('top') ?? 0;
|
|
||||||
this.scrollService.savePosition(key, position);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private removeAuthorsFromList(ids: number[]): void {
|
private removeAuthorsFromList(ids: number[]): void {
|
||||||
const idSet = new Set(ids);
|
const idSet = new Set(ids);
|
||||||
this.allAuthorsState.update(current => (current ?? []).filter(author => !idSet.has(author.id)));
|
this.allAuthorsState.update(current => (current ?? []).filter(author => !idSet.has(author.id)));
|
||||||
|
|||||||
+22
-14
@@ -104,22 +104,30 @@
|
|||||||
<p>{{ t('noBooksFound') }}</p>
|
<p>{{ t('noBooksFound') }}</p>
|
||||||
</div>
|
</div>
|
||||||
} @else {
|
} @else {
|
||||||
<cdk-virtual-scroll-viewport autosize [minBufferPx]="600" [maxBufferPx]="1200" class="books-virtual-scroller">
|
<div #scrollElement class="author-books-scroller virtual-scroller">
|
||||||
<div *cdkVirtualFor="let row of bookRows(); let rowIdx = index" class="books-grid"
|
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
|
||||||
[ngStyle]="{'grid-template-columns': 'repeat(' + gridColumns() + ', 1fr)'}">
|
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
|
||||||
@for (book of row; let j = $index; track book.id) {
|
@if (books[virtualItem.index]; as book) {
|
||||||
<div class="virtual-scroller-item"
|
<div
|
||||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
class="virtual-cell"
|
||||||
<app-book-card
|
[style.width.px]="virtualGrid.itemWidth()"
|
||||||
[index]="rowIdx * gridColumns() + j"
|
[style.height.px]="virtualItem.size"
|
||||||
[book]="book"
|
[style.transform]="virtualGrid.itemTransform(virtualItem)">
|
||||||
[isSeriesCollapsed]="false"
|
<div class="virtual-scroller-item"
|
||||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
[style.width.px]="currentCardSize.width"
|
||||||
</app-book-card>
|
[style.height.px]="currentCardSize.height">
|
||||||
</div>
|
<app-book-card
|
||||||
|
[index]="virtualItem.index"
|
||||||
|
[book]="book"
|
||||||
|
[isSeriesCollapsed]="false"
|
||||||
|
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||||
|
</app-book-card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</cdk-virtual-scroll-viewport>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-13
@@ -157,10 +157,11 @@
|
|||||||
color: #e2e8f0;
|
color: #e2e8f0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.books-virtual-scroller {
|
.author-books-scroller {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: calc(100dvh - 22rem);
|
height: calc(100dvh - 22rem);
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
overflow-y: auto;
|
||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
scrollbar-color: var(--primary-color) rgb(20 20 30 / 50%);
|
scrollbar-color: var(--primary-color) rgb(20 20 30 / 50%);
|
||||||
|
|
||||||
@@ -174,18 +175,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.books-grid {
|
|
||||||
display: grid;
|
|
||||||
gap: 1.3rem;
|
|
||||||
place-items: start center;
|
|
||||||
width: 100%;
|
|
||||||
padding: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.virtual-scroller-item {
|
|
||||||
position: relative;
|
|
||||||
overflow: visible;
|
|
||||||
}
|
|
||||||
|
|
||||||
.empty-books {
|
.empty-books {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
+11
-20
@@ -1,4 +1,4 @@
|
|||||||
import {ElementRef, signal} from '@angular/core';
|
import {signal} from '@angular/core';
|
||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
@@ -99,8 +99,7 @@ describe('AuthorDetailComponent', () => {
|
|||||||
{
|
{
|
||||||
provide: CoverScalePreferenceService,
|
provide: CoverScalePreferenceService,
|
||||||
useValue: {
|
useValue: {
|
||||||
currentCardSize: vi.fn(() => 'medium'),
|
currentCardSize: vi.fn(() => ({width: 135, height: 220})),
|
||||||
gridColumnMinWidth: vi.fn(() => '12rem'),
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -182,29 +181,21 @@ describe('AuthorDetailComponent', () => {
|
|||||||
expect(component.canEditMetadata).toBe(true);
|
expect(component.canEditMetadata).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('detects description overflow from the assigned element ref only while collapsed', () => {
|
it('detects description overflow from element dimensions only while collapsed', () => {
|
||||||
const component = createComponent();
|
const component = createComponent();
|
||||||
|
|
||||||
component.descriptionContentRef = {
|
component.updateDescriptionOverflow({
|
||||||
nativeElement: {
|
scrollHeight: 120,
|
||||||
scrollHeight: 120,
|
clientHeight: 60,
|
||||||
clientHeight: 60,
|
});
|
||||||
},
|
|
||||||
} as unknown as ElementRef<HTMLElement>;
|
|
||||||
|
|
||||||
component.ngAfterViewChecked();
|
|
||||||
|
|
||||||
expect(component.isOverflowing).toBe(true);
|
expect(component.isOverflowing).toBe(true);
|
||||||
|
|
||||||
component.isExpanded = true;
|
component.isExpanded = true;
|
||||||
component.descriptionContentRef = {
|
component.updateDescriptionOverflow({
|
||||||
nativeElement: {
|
scrollHeight: 20,
|
||||||
scrollHeight: 20,
|
clientHeight: 80,
|
||||||
clientHeight: 80,
|
});
|
||||||
},
|
|
||||||
} as unknown as ElementRef<HTMLElement>;
|
|
||||||
|
|
||||||
component.ngAfterViewChecked();
|
|
||||||
|
|
||||||
expect(component.isOverflowing).toBe(true);
|
expect(component.isOverflowing).toBe(true);
|
||||||
});
|
});
|
||||||
|
|||||||
+18
-46
@@ -1,14 +1,11 @@
|
|||||||
import { AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, OnInit, signal, ViewChild } from '@angular/core';
|
import { AfterViewChecked, Component, computed, ElementRef, inject, OnInit, signal, viewChild } from '@angular/core';
|
||||||
import { computeGridColumns } from '../../../../shared/util/viewport.util';
|
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { NgClass, NgStyle } from '@angular/common';
|
import { NgClass } from '@angular/common';
|
||||||
import { Tab, TabList, TabPanel, TabPanels, Tabs } from 'primeng/tabs';
|
import { Tab, TabList, TabPanel, TabPanels, Tabs } from 'primeng/tabs';
|
||||||
import { ProgressSpinner } from 'primeng/progressspinner';
|
import { ProgressSpinner } from 'primeng/progressspinner';
|
||||||
import { Button } from 'primeng/button';
|
import { Button } from 'primeng/button';
|
||||||
import { Tag } from 'primeng/tag';
|
import { Tag } from 'primeng/tag';
|
||||||
import { TranslocoDirective, TranslocoService } from '@jsverse/transloco';
|
import { TranslocoDirective, TranslocoService } from '@jsverse/transloco';
|
||||||
import { CdkVirtualScrollViewport, CdkVirtualForOf } from '@angular/cdk/scrolling';
|
|
||||||
import { CdkAutoSizeVirtualScroll } from '@angular/cdk-experimental/scrolling';
|
|
||||||
import { MessageService } from 'primeng/api';
|
import { MessageService } from 'primeng/api';
|
||||||
import { Tooltip } from 'primeng/tooltip';
|
import { Tooltip } from 'primeng/tooltip';
|
||||||
import { AuthorService } from '../../service/author.service';
|
import { AuthorService } from '../../service/author.service';
|
||||||
@@ -21,7 +18,7 @@ import { UserService } from '../../../settings/user-management/user.service';
|
|||||||
import { AuthorMatchComponent } from '../author-match/author-match.component';
|
import { AuthorMatchComponent } from '../author-match/author-match.component';
|
||||||
import { AuthorEditorComponent } from '../author-editor/author-editor.component';
|
import { AuthorEditorComponent } from '../author-editor/author-editor.component';
|
||||||
import { PageTitleService } from '../../../../shared/service/page-title.service';
|
import { PageTitleService } from '../../../../shared/service/page-title.service';
|
||||||
import { chunk } from '../../../../shared/util/array.util';
|
import { createVirtualGrid } from '../../../../shared/util/virtual-grid.util';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-author-detail',
|
selector: 'app-author-detail',
|
||||||
@@ -30,7 +27,6 @@ import { chunk } from '../../../../shared/util/array.util';
|
|||||||
styleUrls: ['./author-detail.component.scss'],
|
styleUrls: ['./author-detail.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
NgClass,
|
NgClass,
|
||||||
NgStyle,
|
|
||||||
Tabs,
|
Tabs,
|
||||||
TabList,
|
TabList,
|
||||||
Tab,
|
Tab,
|
||||||
@@ -41,9 +37,6 @@ import { chunk } from '../../../../shared/util/array.util';
|
|||||||
Tag,
|
Tag,
|
||||||
TranslocoDirective,
|
TranslocoDirective,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
CdkVirtualScrollViewport,
|
|
||||||
CdkVirtualForOf,
|
|
||||||
CdkAutoSizeVirtualScroll,
|
|
||||||
BookCardComponent,
|
BookCardComponent,
|
||||||
AuthorMatchComponent,
|
AuthorMatchComponent,
|
||||||
AuthorEditorComponent
|
AuthorEditorComponent
|
||||||
@@ -63,27 +56,9 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
protected userService = inject(UserService);
|
protected userService = inject(UserService);
|
||||||
private pageTitle = inject(PageTitleService);
|
private pageTitle = inject(PageTitleService);
|
||||||
private t = inject(TranslocoService);
|
private t = inject(TranslocoService);
|
||||||
private destroyRef = inject(DestroyRef);
|
|
||||||
|
|
||||||
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
readonly descriptionContentRef = viewChild<ElementRef<HTMLElement>>('descriptionContent');
|
||||||
virtualScroller?: CdkVirtualScrollViewport;
|
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
|
||||||
|
|
||||||
@ViewChild(CdkVirtualScrollViewport)
|
|
||||||
set scrollViewport(vp: CdkVirtualScrollViewport | undefined) {
|
|
||||||
this.virtualScroller = vp;
|
|
||||||
this.viewportResizeObserver?.disconnect();
|
|
||||||
if (vp) {
|
|
||||||
const el = vp.elementRef.nativeElement as HTMLElement;
|
|
||||||
this.viewportWidth.set(el.clientWidth);
|
|
||||||
this.viewportResizeObserver = new ResizeObserver(entries => {
|
|
||||||
this.viewportWidth.set(entries[0]?.contentRect.width ?? el.clientWidth);
|
|
||||||
});
|
|
||||||
this.viewportResizeObserver.observe(el);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private readonly viewportWidth = signal(0);
|
|
||||||
private viewportResizeObserver: ResizeObserver | undefined;
|
|
||||||
|
|
||||||
loading = signal(true);
|
loading = signal(true);
|
||||||
tab = 'books';
|
tab = 'books';
|
||||||
@@ -109,16 +84,12 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
return this.coverScalePreferenceService.currentCardSize();
|
return this.coverScalePreferenceService.currentCardSize();
|
||||||
}
|
}
|
||||||
|
|
||||||
get gridColumnMinWidth(): string {
|
readonly virtualGrid = createVirtualGrid({
|
||||||
return this.coverScalePreferenceService.gridColumnMinWidth();
|
items: this.authorBooks,
|
||||||
}
|
scrollElement: this.scrollElement,
|
||||||
|
minItemWidth: computed(() => this.currentCardSize.width),
|
||||||
readonly gridColumns = computed(() => {
|
estimateItemHeight: () => this.currentCardSize.height,
|
||||||
return computeGridColumns(this.viewportWidth(), parseInt(this.gridColumnMinWidth, 10) || 180, AuthorDetailComponent.GRID_GAP);
|
gap: AuthorDetailComponent.GRID_GAP,
|
||||||
});
|
|
||||||
|
|
||||||
readonly bookRows = computed(() => {
|
|
||||||
return chunk(this.authorBooks(), this.gridColumns());
|
|
||||||
});
|
});
|
||||||
|
|
||||||
get photoUrl(): string {
|
get photoUrl(): string {
|
||||||
@@ -139,15 +110,16 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
|
|||||||
this.tab = tabParam;
|
this.tab = tabParam;
|
||||||
}
|
}
|
||||||
this.loadAuthor(authorId);
|
this.loadAuthor(authorId);
|
||||||
this.destroyRef.onDestroy(() => this.viewportResizeObserver?.disconnect());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
ngAfterViewChecked(): void {
|
ngAfterViewChecked(): void {
|
||||||
if (!this.isExpanded && this.descriptionContentRef) {
|
const descriptionContent = this.descriptionContentRef();
|
||||||
const el = this.descriptionContentRef.nativeElement;
|
this.updateDescriptionOverflow(descriptionContent?.nativeElement);
|
||||||
this.isOverflowing = el.scrollHeight > el.clientHeight;
|
}
|
||||||
|
|
||||||
|
updateDescriptionOverflow(element?: Pick<HTMLElement, 'scrollHeight' | 'clientHeight'>): void {
|
||||||
|
if (!this.isExpanded && element) {
|
||||||
|
this.isOverflowing = element.scrollHeight > element.clientHeight;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
-66
@@ -1,66 +0,0 @@
|
|||||||
import {TestBed} from '@angular/core/testing';
|
|
||||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
|
||||||
|
|
||||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
|
||||||
import {AuthorScalePreferenceService} from './author-scale-preference.service';
|
|
||||||
|
|
||||||
describe('AuthorScalePreferenceService', () => {
|
|
||||||
const localStorageService = {
|
|
||||||
get: vi.fn(),
|
|
||||||
set: vi.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
localStorageService.get.mockReset();
|
|
||||||
localStorageService.set.mockReset();
|
|
||||||
localStorageService.get.mockReturnValue(1.5);
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
providers: [
|
|
||||||
AuthorScalePreferenceService,
|
|
||||||
{provide: LocalStorageService, useValue: localStorageService},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.useRealTimers();
|
|
||||||
TestBed.resetTestingModule();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('loads the persisted scale and does not persist unchanged values', () => {
|
|
||||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
|
||||||
|
|
||||||
expect(service.scaleFactor()).toBe(1.5);
|
|
||||||
|
|
||||||
service.setScale(1.5);
|
|
||||||
vi.runAllTimers();
|
|
||||||
|
|
||||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('debounces and persists the most recent scale value', () => {
|
|
||||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
|
||||||
|
|
||||||
service.setScale(1.2);
|
|
||||||
service.setScale(1.4);
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(999);
|
|
||||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(1);
|
|
||||||
|
|
||||||
expect(localStorageService.set).toHaveBeenCalledOnce();
|
|
||||||
expect(localStorageService.set).toHaveBeenCalledWith('authorScalePreference', 1.4);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to the default scale when storage contains an invalid value', () => {
|
|
||||||
localStorageService.get.mockReturnValue(Number.NaN);
|
|
||||||
|
|
||||||
const service = TestBed.inject(AuthorScalePreferenceService);
|
|
||||||
|
|
||||||
expect(service.scaleFactor()).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
import {inject, Injectable, signal} from '@angular/core';
|
|
||||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
|
||||||
|
|
||||||
@Injectable({
|
|
||||||
providedIn: 'root'
|
|
||||||
})
|
|
||||||
export class AuthorScalePreferenceService {
|
|
||||||
|
|
||||||
private readonly DEBOUNCE_MS = 1000;
|
|
||||||
private readonly STORAGE_KEY = 'authorScalePreference';
|
|
||||||
|
|
||||||
private readonly localStorageService = inject(LocalStorageService);
|
|
||||||
|
|
||||||
private readonly _scaleFactor = signal(1.0);
|
|
||||||
readonly scaleFactor = this._scaleFactor.asReadonly();
|
|
||||||
|
|
||||||
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
private lastPersistedScale = 1.0;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
const initialScale = this.loadScaleFromStorage();
|
|
||||||
this._scaleFactor.set(initialScale);
|
|
||||||
this.lastPersistedScale = initialScale;
|
|
||||||
}
|
|
||||||
|
|
||||||
setScale(scale: number): void {
|
|
||||||
this._scaleFactor.set(scale);
|
|
||||||
if (scale === this.lastPersistedScale) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.scheduleSave(scale);
|
|
||||||
}
|
|
||||||
|
|
||||||
private scheduleSave(scale: number): void {
|
|
||||||
if (this.saveTimeout) {
|
|
||||||
clearTimeout(this.saveTimeout);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.saveTimeout = setTimeout(() => {
|
|
||||||
this.saveScalePreference(scale);
|
|
||||||
}, this.DEBOUNCE_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private saveScalePreference(scale: number): void {
|
|
||||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
|
||||||
this.lastPersistedScale = scale;
|
|
||||||
}
|
|
||||||
|
|
||||||
private loadScaleFromStorage(): number {
|
|
||||||
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
|
||||||
if (saved !== null && !isNaN(saved)) {
|
|
||||||
return saved;
|
|
||||||
}
|
|
||||||
return 1.0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-33
@@ -1,33 +0,0 @@
|
|||||||
import {describe, expect, it} from 'vitest';
|
|
||||||
|
|
||||||
import {BookBrowserScrollService} from './book-browser-scroll.service';
|
|
||||||
|
|
||||||
describe('BookBrowserScrollService', () => {
|
|
||||||
const service = new BookBrowserScrollService();
|
|
||||||
|
|
||||||
it('stores, retrieves, clears, and creates stable keys', () => {
|
|
||||||
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);
|
|
||||||
expect(service.createKey('/books', {libraryId: '1', shelfId: '2'})).toBe('/books:1-2');
|
|
||||||
expect(service.createKey('/books', {})).toBe('/books');
|
|
||||||
|
|
||||||
service.clearPosition('books');
|
|
||||||
expect(service.getPosition('books')).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('clearAll removes all stored positions', () => {
|
|
||||||
const fresh = new BookBrowserScrollService();
|
|
||||||
fresh.savePosition('a', 10);
|
|
||||||
fresh.savePosition('b', 20);
|
|
||||||
|
|
||||||
fresh.clearAll();
|
|
||||||
|
|
||||||
expect(fresh.getPosition('a')).toBeUndefined();
|
|
||||||
expect(fresh.getPosition('b')).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
import {Injectable} from '@angular/core';
|
|
||||||
|
|
||||||
@Injectable({
|
|
||||||
providedIn: 'root'
|
|
||||||
})
|
|
||||||
export class BookBrowserScrollService {
|
|
||||||
private scrollPositions = new Map<string, number>();
|
|
||||||
|
|
||||||
savePosition(key: string, position: number): void {
|
|
||||||
this.scrollPositions.set(key, position);
|
|
||||||
}
|
|
||||||
|
|
||||||
getPosition(key: string): number | undefined {
|
|
||||||
return this.scrollPositions.get(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
clearPosition(key: string): void {
|
|
||||||
this.scrollPositions.delete(key);
|
|
||||||
}
|
|
||||||
|
|
||||||
clearAll(): void {
|
|
||||||
this.scrollPositions.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
createKey(path: string, params: Record<string, string>): string {
|
|
||||||
const paramValues = Object.values(params).join('-');
|
|
||||||
return paramValues ? `${path}:${paramValues}` : path;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+68
-76
@@ -124,20 +124,20 @@
|
|||||||
@if (isMobile()) {
|
@if (isMobile()) {
|
||||||
<div class="display-settings-section">
|
<div class="display-settings-section">
|
||||||
<span class="display-settings-label">{{ t('labels.gridColumns') }}</span>
|
<span class="display-settings-label">{{ t('labels.gridColumns') }}</span>
|
||||||
<div class="column-options">
|
<div class="browser-grid-options">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="column-option-btn"
|
class="browser-grid-option-btn"
|
||||||
[class.active]="mobileColumnCount() === 2"
|
[class.active]="mobileColumnCount() === 2"
|
||||||
(click)="setMobileColumns(2)">2</button>
|
(click)="setMobileColumns(2)">2</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="column-option-btn"
|
class="browser-grid-option-btn"
|
||||||
[class.active]="mobileColumnCount() === 3"
|
[class.active]="mobileColumnCount() === 3"
|
||||||
(click)="setMobileColumns(3)">3</button>
|
(click)="setMobileColumns(3)">3</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="column-option-btn"
|
class="browser-grid-option-btn"
|
||||||
[class.active]="mobileColumnCount() === 4"
|
[class.active]="mobileColumnCount() === 4"
|
||||||
(click)="setMobileColumns(4)">4</button>
|
(click)="setMobileColumns(4)">4</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -145,17 +145,7 @@
|
|||||||
} @else {
|
} @else {
|
||||||
<div class="display-settings-section">
|
<div class="display-settings-section">
|
||||||
<span class="display-settings-label">{{ t('labels.gridItemSize') }}</span>
|
<span class="display-settings-label">{{ t('labels.gridItemSize') }}</span>
|
||||||
<p-slider
|
<app-grid-density-buttons (densityChange)="adjustDesktopGridDensity($event)"/>
|
||||||
[ngModel]="coverScalePreferenceService.scaleFactor()"
|
|
||||||
(ngModelChange)="coverScalePreferenceService.setScale($event)"
|
|
||||||
[min]="0.5"
|
|
||||||
[max]="1.5"
|
|
||||||
[step]="0.01"
|
|
||||||
[style]="{ width: '100%' }">
|
|
||||||
</p-slider>
|
|
||||||
<div class="scale-value-display">
|
|
||||||
{{ coverScalePreferenceService.scaleFactor().toFixed(2) }}x
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="display-settings-section">
|
<div class="display-settings-section">
|
||||||
@@ -280,13 +270,16 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
} @else if (showGridLoadingPlaceholder()) {
|
} @else if (showGridLoadingPlaceholder()) {
|
||||||
<div class="skeleton-grid"
|
<div #scrollElement class="virtual-scroller">
|
||||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth() + ', 1fr))'}">
|
<div class="skeleton-grid"
|
||||||
@for (item of skeletonSlots; track item) {
|
[style.grid-template-columns]="'repeat(auto-fill, minmax(' + skeletonMinCardWidth() + ', 1fr))'">
|
||||||
<div class="skeleton-card"
|
@for (item of skeletonSlots; track item) {
|
||||||
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
|
<div class="skeleton-card"
|
||||||
</div>
|
[style.width.px]="currentCardSize().width"
|
||||||
}
|
[style.height.px]="currentCardSize().height">
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
} @else if (booksError()) {
|
} @else if (booksError()) {
|
||||||
<div class="no-books-container">
|
<div class="no-books-container">
|
||||||
@@ -294,59 +287,60 @@
|
|||||||
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
|
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
} @else if (books(); as books) {
|
} @else {
|
||||||
<div class="book-state-wrapper">
|
@let visibleBooks = books();
|
||||||
<div
|
@if (visibleBooks.length === 0 && !isBooksLoading()) {
|
||||||
class="book-state-content"
|
<div class="no-books-container">
|
||||||
[attr.aria-busy]="isBooksRefreshing() ? 'true' : 'false'"
|
<p class="no-books-text">
|
||||||
[class.book-state-content-refreshing]="isBooksRefreshing()"
|
{{ t('labels.noBooks') }}
|
||||||
[attr.inert]="isBooksRefreshing() ? '' : null">
|
</p>
|
||||||
@if (books.length === 0 && !isBooksLoading()) {
|
</div>
|
||||||
<div class="no-books-container">
|
}
|
||||||
<p class="no-books-text">
|
@if (currentViewMode() === 'table' && visibleBooks.length > 0) {
|
||||||
{{ t('labels.noBooks') }}
|
<app-book-table
|
||||||
</p>
|
[books]="visibleBooks"
|
||||||
</div>
|
[preselectedBookIds]="selectedBooks()"
|
||||||
}
|
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||||
@if (currentViewMode() === 'table' && books.length > 0) {
|
(selectAllRequested)="selectAllBooks()"
|
||||||
<app-book-table
|
[sortOption]="this.bookSorter.selectedSort!"
|
||||||
[books]="books"
|
[visibleColumns]="visibleColumns()"
|
||||||
[preselectedBookIds]="selectedBooks()"
|
></app-book-table>
|
||||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
}
|
||||||
(selectAllRequested)="selectAllBooks()"
|
@if (currentViewMode() === 'grid') {
|
||||||
[sortOption]="this.bookSorter.selectedSort!"
|
<div #scrollElement class="virtual-scroller">
|
||||||
[visibleColumns]="visibleColumns()"
|
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
|
||||||
></app-book-table>
|
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
|
||||||
}
|
@if (visibleBooks[virtualItem.index]; as book) {
|
||||||
@if (currentViewMode() === 'grid') {
|
<div
|
||||||
<div class="virtual-scroller" #scrollContainer>
|
class="virtual-cell"
|
||||||
<div class="scroll-height-anchor" [ngStyle]="{'min-height': estimatedTotalHeight() + 'px'}">
|
[style.width.px]="virtualGrid.itemWidth()"
|
||||||
<div class="book-grid"
|
[style.height.px]="virtualItem.size"
|
||||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth() + ', 1fr))'}">
|
[style.transform]="virtualGrid.itemTransform(virtualItem)">
|
||||||
@for (book of books; track book.id; let i = $index) {
|
<app-book-card
|
||||||
<div
|
[index]="virtualItem.index"
|
||||||
class="virtual-scroller-item"
|
[book]="book"
|
||||||
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
|
[isCheckboxEnabled]="true"
|
||||||
<app-book-card
|
[seriesViewEnabled]="seriesViewEnabled()"
|
||||||
[index]="i"
|
[onBookSelect]="onBookCardSelect"
|
||||||
[book]="book"
|
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||||
[isCheckboxEnabled]="true"
|
(checkboxClick)="onCheckboxClicked($event)"
|
||||||
[seriesViewEnabled]="seriesViewEnabled()"
|
[isSelected]="bookSelectionService.isBookSelected(book)"
|
||||||
[onBookSelect]="onBookCardSelect"
|
[useSquareCovers]="isAudiobookOnlyLibrary()"
|
||||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||||
(checkboxClick)="onCheckboxClicked($event)"
|
</app-book-card>
|
||||||
[isSelected]="bookSelectionService.isBookSelected(book)"
|
|
||||||
[useSquareCovers]="isAudiobookOnlyLibrary()"
|
|
||||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
|
||||||
</app-book-card>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
<div class="scroll-sentinel" #scrollSentinel></div>
|
} @else {
|
||||||
</div>
|
<div
|
||||||
</div>
|
class="virtual-cell virtual-loader-cell"
|
||||||
}
|
[style.width.px]="virtualGrid.itemWidth()"
|
||||||
@if (userService.currentUser(); as currentUser) {
|
[style.height.px]="virtualItem.size"
|
||||||
|
[style.transform]="virtualGrid.itemTransform(virtualItem)"></div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (userService.currentUser(); as currentUser) {
|
||||||
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
||||||
<div class="footer-content">
|
<div class="footer-content">
|
||||||
<div class="footer-left">
|
<div class="footer-left">
|
||||||
@@ -469,8 +463,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,11 @@
|
|||||||
// Skeleton loader — opacity animation runs on the compositor thread
|
|
||||||
// so it stays smooth while the main thread computes books.
|
|
||||||
.skeleton-grid {
|
.skeleton-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: 21px;
|
gap: 21px;
|
||||||
align-items: start;
|
place-items: start center;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
|
||||||
@media (width <= 767px) {
|
@media (width <= 767px) {
|
||||||
gap: 0.5rem 8px;
|
gap: 8px;
|
||||||
padding: 0 0.5rem;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,38 +218,6 @@
|
|||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scale-value-display {
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.column-options {
|
|
||||||
display: flex;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.column-option-btn {
|
|
||||||
flex: 1;
|
|
||||||
padding: 0.25rem 0.5rem;
|
|
||||||
border: 1px solid var(--p-content-border-color);
|
|
||||||
border-radius: 6px;
|
|
||||||
background-color: var(--card-background);
|
|
||||||
color: var(--text-color);
|
|
||||||
font-size: 1rem;
|
|
||||||
font-weight: 600;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.15s ease;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
border-color: var(--primary-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
&.active {
|
|
||||||
background-color: var(--primary-color);
|
|
||||||
border-color: var(--primary-color);
|
|
||||||
color: var(--primary-color-text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort button wrapper
|
// Sort button wrapper
|
||||||
.sort-button-wrapper {
|
.sort-button-wrapper {
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -437,41 +402,18 @@
|
|||||||
.virtual-scroller {
|
.virtual-scroller {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: calc(100dvh - 10.9rem);
|
height: calc(100dvh - 10.9rem);
|
||||||
padding: 1rem;
|
padding: 1rem 0;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
|
|
||||||
@media (width <= 768px) {
|
@media (width <= 768px) {
|
||||||
height: calc(100dvh - 9rem);
|
height: calc(100dvh - 9rem);
|
||||||
|
padding: 0.75rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.book-grid {
|
.virtual-loader-cell {
|
||||||
display: grid;
|
pointer-events: none;
|
||||||
gap: 21px;
|
|
||||||
align-items: start;
|
|
||||||
width: 100%;
|
|
||||||
|
|
||||||
@media (width <= 767px) {
|
|
||||||
gap: 0.5rem 8px;
|
|
||||||
padding: 0 0.5rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.scroll-sentinel {
|
|
||||||
height: 1px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.virtual-scroller-item {
|
|
||||||
position: relative;
|
|
||||||
margin-bottom: 21px;
|
|
||||||
contain: strict;
|
|
||||||
content-visibility: auto;
|
|
||||||
contain-intrinsic-size: auto var(--virtual-scroller-item-height, 220px);
|
|
||||||
|
|
||||||
@media (width <= 767px) {
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// No books state
|
// No books state
|
||||||
@@ -608,12 +550,3 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Book state container
|
|
||||||
.book-state-wrapper {
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
.book-state-content-refreshing {
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
|
|||||||
+60
-67
@@ -1,4 +1,4 @@
|
|||||||
import {computed, ElementRef, signal, WritableSignal} from '@angular/core';
|
import {computed, signal, WritableSignal} from '@angular/core';
|
||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
|
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
|
||||||
import {BehaviorSubject, Subject} from 'rxjs';
|
import {BehaviorSubject, Subject} from 'rxjs';
|
||||||
@@ -26,7 +26,7 @@ import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.s
|
|||||||
import {BookSelectionService} from './book-selection.service';
|
import {BookSelectionService} from './book-selection.service';
|
||||||
import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.service';
|
import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.service';
|
||||||
import {BookBrowserEntityService} from './book-browser-entity.service';
|
import {BookBrowserEntityService} from './book-browser-entity.service';
|
||||||
import {BookBrowserScrollService} from './book-browser-scroll.service';
|
import {RouteScrollPositionService} from '../../../../shared/service/route-scroll-position.service';
|
||||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||||
import {BookBrowserComponent, EntityType} from './book-browser.component';
|
import {BookBrowserComponent, EntityType} from './book-browser.component';
|
||||||
import {SortService} from '../../service/sort.service';
|
import {SortService} from '../../service/sort.service';
|
||||||
@@ -106,6 +106,7 @@ interface BookBrowserHarness {
|
|||||||
booksError: WritableSignal<string | null>;
|
booksError: WritableSignal<string | null>;
|
||||||
isBooksLoading: WritableSignal<boolean>;
|
isBooksLoading: WritableSignal<boolean>;
|
||||||
paramMap$: BehaviorSubject<ParamMap>;
|
paramMap$: BehaviorSubject<ParamMap>;
|
||||||
|
setHasNextPage: (value: boolean) => void;
|
||||||
queryParamsService: {
|
queryParamsService: {
|
||||||
shouldForceExpandSeries: ReturnType<typeof vi.fn>;
|
shouldForceExpandSeries: ReturnType<typeof vi.fn>;
|
||||||
updateViewMode: ReturnType<typeof vi.fn>;
|
updateViewMode: ReturnType<typeof vi.fn>;
|
||||||
@@ -125,6 +126,7 @@ interface BookBrowserHarness {
|
|||||||
|
|
||||||
function createHarness(options?: {
|
function createHarness(options?: {
|
||||||
books?: Book[];
|
books?: Book[];
|
||||||
|
totalElements?: number;
|
||||||
booksError?: string | null;
|
booksError?: string | null;
|
||||||
isBooksLoading?: boolean;
|
isBooksLoading?: boolean;
|
||||||
translate?: (key: string) => string;
|
translate?: (key: string) => string;
|
||||||
@@ -138,6 +140,7 @@ function createHarness(options?: {
|
|||||||
);
|
);
|
||||||
const booksError = signal<string | null>(options?.booksError ?? null);
|
const booksError = signal<string | null>(options?.booksError ?? null);
|
||||||
const isBooksLoading = signal<boolean>(options?.isBooksLoading ?? false);
|
const isBooksLoading = signal<boolean>(options?.isBooksLoading ?? false);
|
||||||
|
const hasNextPage = signal(false);
|
||||||
const currentUser = signal(makeCurrentUser());
|
const currentUser = signal(makeCurrentUser());
|
||||||
const showFilter = signal(false);
|
const showFilter = signal(false);
|
||||||
const seriesCollapsed = signal(false);
|
const seriesCollapsed = signal(false);
|
||||||
@@ -175,7 +178,6 @@ function createHarness(options?: {
|
|||||||
SortService,
|
SortService,
|
||||||
BookSelectionService,
|
BookSelectionService,
|
||||||
BookNavigationService,
|
BookNavigationService,
|
||||||
BookBrowserScrollService,
|
|
||||||
{
|
{
|
||||||
provide: UserService,
|
provide: UserService,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -187,9 +189,6 @@ function createHarness(options?: {
|
|||||||
{
|
{
|
||||||
provide: CoverScalePreferenceService,
|
provide: CoverScalePreferenceService,
|
||||||
useValue: {
|
useValue: {
|
||||||
currentCardSize: vi.fn(() => ({width: 120, height: 160})),
|
|
||||||
gridColumnMinWidth: vi.fn(() => '120px'),
|
|
||||||
getCardHeight: vi.fn(() => 160),
|
|
||||||
scaleFactor: vi.fn(() => 1),
|
scaleFactor: vi.fn(() => 1),
|
||||||
setScale: vi.fn(),
|
setScale: vi.fn(),
|
||||||
},
|
},
|
||||||
@@ -241,11 +240,13 @@ function createHarness(options?: {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
provide: BookBrowserScrollService,
|
provide: RouteScrollPositionService,
|
||||||
useValue: {
|
useValue: {
|
||||||
createKey: vi.fn(() => 'test-key'),
|
createKey: vi.fn(() => 'test-key'),
|
||||||
|
keyFor: vi.fn(() => 'test-key'),
|
||||||
savePosition: vi.fn(),
|
savePosition: vi.fn(),
|
||||||
getPosition: vi.fn(() => 0),
|
getPosition: vi.fn(() => 0),
|
||||||
|
trackRoute: vi.fn(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{provide: ConfirmationService, useValue: {confirm: vi.fn()}},
|
{provide: ConfirmationService, useValue: {confirm: vi.fn()}},
|
||||||
@@ -289,8 +290,6 @@ function createHarness(options?: {
|
|||||||
const _filters = signal<AppBookFilters>({});
|
const _filters = signal<AppBookFilters>({});
|
||||||
const _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
|
const _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
|
||||||
const _search = signal('');
|
const _search = signal('');
|
||||||
const _hasNextPage = signal(false);
|
|
||||||
|
|
||||||
const filteredSortedBooks = computed(() => {
|
const filteredSortedBooks = computed(() => {
|
||||||
let result = books();
|
let result = books();
|
||||||
const f = _filters();
|
const f = _filters();
|
||||||
@@ -307,12 +306,12 @@ function createHarness(options?: {
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
const totalElements = computed(() => options?.totalElements ?? filteredSortedBooks().length);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
books: filteredSortedBooks,
|
books: filteredSortedBooks,
|
||||||
totalElements: computed(() => filteredSortedBooks().length),
|
totalElements,
|
||||||
hasNextPage: _hasNextPage.asReadonly(),
|
hasNextPage: hasNextPage.asReadonly(),
|
||||||
setHasNextPage: (v: boolean) => _hasNextPage.set(v),
|
|
||||||
isLoading: isBooksLoading.asReadonly(),
|
isLoading: isBooksLoading.asReadonly(),
|
||||||
isFetchingNextPage: computed(() => false),
|
isFetchingNextPage: computed(() => false),
|
||||||
isError: computed(() => !!booksError()),
|
isError: computed(() => !!booksError()),
|
||||||
@@ -394,6 +393,7 @@ function createHarness(options?: {
|
|||||||
booksError,
|
booksError,
|
||||||
isBooksLoading,
|
isBooksLoading,
|
||||||
paramMap$,
|
paramMap$,
|
||||||
|
setHasNextPage: value => hasNextPage.set(value),
|
||||||
queryParamsService,
|
queryParamsService,
|
||||||
routeSnapshot,
|
routeSnapshot,
|
||||||
};
|
};
|
||||||
@@ -407,11 +407,6 @@ describe('BookBrowserComponent', () => {
|
|||||||
unobserve = vi.fn();
|
unobserve = vi.fn();
|
||||||
disconnect = vi.fn();
|
disconnect = vi.fn();
|
||||||
});
|
});
|
||||||
vi.stubGlobal('IntersectionObserver', class {
|
|
||||||
observe = vi.fn();
|
|
||||||
unobserve = vi.fn();
|
|
||||||
disconnect = vi.fn();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -428,48 +423,38 @@ describe('BookBrowserComponent', () => {
|
|||||||
|
|
||||||
component.onViewModeChange(VIEW_MODES.TABLE);
|
component.onViewModeChange(VIEW_MODES.TABLE);
|
||||||
|
|
||||||
expect((component as unknown as {currentViewMode: () => string}).currentViewMode()).toBe(VIEW_MODES.TABLE);
|
expect(component.currentViewMode()).toBe(VIEW_MODES.TABLE);
|
||||||
expect(queryParamsService.updateViewMode).toHaveBeenCalledWith(VIEW_MODES.TABLE);
|
expect(queryParamsService.updateViewMode).toHaveBeenCalledWith(VIEW_MODES.TABLE);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps rendered books visible during same-context refreshes', () => {
|
it('updates books when sorting changes', () => {
|
||||||
const {component} = createHarness();
|
const {component} = createHarness();
|
||||||
|
|
||||||
expect(component.books()).toBeUndefined();
|
TestBed.flushEffects();
|
||||||
|
|
||||||
vi.runOnlyPendingTimers();
|
expect(component.books().map(book => book.id)).toEqual([2, 1]);
|
||||||
|
|
||||||
expect(component.books()?.map(book => book.id)).toEqual([2, 1]);
|
|
||||||
expect(component.isBooksRefreshing()).toBe(false);
|
|
||||||
|
|
||||||
component.applySortCriteria([
|
component.applySortCriteria([
|
||||||
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
|
||||||
]);
|
]);
|
||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
|
|
||||||
expect(component.books()?.map(book => book.id)).toEqual([1, 2]);
|
expect(component.books().map(book => book.id)).toEqual([1, 2]);
|
||||||
expect((component as unknown as {hasRenderedBooks: () => boolean}).hasRenderedBooks()).toBe(true);
|
|
||||||
expect(component.isBooksRefreshing()).toBe(false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('clears rendered books until the deferred commit completes after a context change', () => {
|
it('updates books after a context change', () => {
|
||||||
const {component, paramMap$, routeSnapshot} = createHarness();
|
const {component, paramMap$, routeSnapshot} = createHarness();
|
||||||
|
|
||||||
vi.runOnlyPendingTimers();
|
TestBed.flushEffects();
|
||||||
expect(component.books()?.map(book => book.id)).toEqual([2, 1]);
|
|
||||||
|
expect(component.books().map(book => book.id)).toEqual([2, 1]);
|
||||||
|
|
||||||
routeSnapshot.paramMap = convertToParamMap({libraryId: '2'});
|
routeSnapshot.paramMap = convertToParamMap({libraryId: '2'});
|
||||||
routeSnapshot.params = {libraryId: '2'};
|
routeSnapshot.params = {libraryId: '2'};
|
||||||
paramMap$.next(routeSnapshot.paramMap);
|
paramMap$.next(routeSnapshot.paramMap);
|
||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
|
|
||||||
expect(component.books()).toBeUndefined();
|
expect(component.books().map(book => book.id)).toEqual([3]);
|
||||||
expect((component as unknown as {hasRenderedBooks: () => boolean}).hasRenderedBooks()).toBe(false);
|
|
||||||
|
|
||||||
vi.runOnlyPendingTimers();
|
|
||||||
|
|
||||||
expect(component.books()?.map(book => book.id)).toEqual([3]);
|
|
||||||
expect((component as unknown as {hasRenderedBooks: () => boolean}).hasRenderedBooks()).toBe(true);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('hides loading placeholders when the books query is in an error state', () => {
|
it('hides loading placeholders when the books query is in an error state', () => {
|
||||||
@@ -478,17 +463,12 @@ describe('BookBrowserComponent', () => {
|
|||||||
isBooksLoading: true,
|
isBooksLoading: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const comp = component as unknown as {
|
expect(component.showBooksLoadingPlaceholder()).toBe(false);
|
||||||
showBooksLoadingPlaceholder: () => boolean;
|
expect(component.showGridLoadingPlaceholder()).toBe(false);
|
||||||
showGridLoadingPlaceholder: () => boolean;
|
expect(component.showTableLoadingPlaceholder()).toBe(false);
|
||||||
showTableLoadingPlaceholder: () => boolean;
|
|
||||||
};
|
|
||||||
expect(comp.showBooksLoadingPlaceholder()).toBe(false);
|
|
||||||
expect(comp.showGridLoadingPlaceholder()).toBe(false);
|
|
||||||
expect(comp.showTableLoadingPlaceholder()).toBe(false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('calls SeriesCollapseFilter.collapseBooks when computing pipelineInputs', () => {
|
it('calls SeriesCollapseFilter.collapseBooks when computing books', () => {
|
||||||
createHarness();
|
createHarness();
|
||||||
const filter = TestBed.inject(SeriesCollapseFilter);
|
const filter = TestBed.inject(SeriesCollapseFilter);
|
||||||
const collapseBooksSpy = vi.spyOn(filter, 'collapseBooks');
|
const collapseBooksSpy = vi.spyOn(filter, 'collapseBooks');
|
||||||
@@ -499,35 +479,48 @@ describe('BookBrowserComponent', () => {
|
|||||||
expect(collapseBooksSpy).toHaveBeenCalled();
|
expect(collapseBooksSpy).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('triggers next page fetch when scrolled near the bottom of rendered content', async () => {
|
it('triggers next page fetch when the virtual grid reaches the loaded rows', () => {
|
||||||
const {component} = createHarness();
|
const {component, setHasNextPage} = createHarness();
|
||||||
const appBooksApi = TestBed.inject(AppBooksApiService);
|
const appBooksApi = TestBed.inject(AppBooksApiService);
|
||||||
|
|
||||||
// Initial load
|
|
||||||
vi.runOnlyPendingTimers();
|
vi.runOnlyPendingTimers();
|
||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
|
|
||||||
// Mock hasNextPage to be true
|
vi.spyOn(component.virtualGrid.virtualizer, 'getVirtualItems').mockReturnValue([
|
||||||
// @ts-expect-error test helper
|
{index: 2, key: 2, start: 0, end: 241, size: 241, lane: 0}
|
||||||
appBooksApi.setHasNextPage(true);
|
]);
|
||||||
|
|
||||||
|
component.currentViewMode.set(VIEW_MODES.TABLE);
|
||||||
|
TestBed.flushEffects();
|
||||||
|
|
||||||
|
setHasNextPage(true);
|
||||||
const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage');
|
const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage');
|
||||||
|
component.currentViewMode.set(VIEW_MODES.GRID);
|
||||||
// Mock scroll container
|
|
||||||
const mockElement = {
|
|
||||||
scrollTop: 2000,
|
|
||||||
clientHeight: 1000,
|
|
||||||
clientWidth: 1000,
|
|
||||||
scrollHeight: 5000,
|
|
||||||
addEventListener: vi.fn(),
|
|
||||||
removeEventListener: vi.fn(),
|
|
||||||
} as unknown as HTMLElement;
|
|
||||||
|
|
||||||
component.scrollContainerRef = {nativeElement: mockElement} as ElementRef<HTMLElement>;
|
|
||||||
|
|
||||||
// Trigger initial check
|
|
||||||
vi.runOnlyPendingTimers(); // For requestAnimationFrame
|
|
||||||
TestBed.flushEffects();
|
TestBed.flushEffects();
|
||||||
|
|
||||||
expect(fetchNextPageSpy).toHaveBeenCalled();
|
expect(fetchNextPageSpy).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('uses the known total book count for virtual grid size while more pages are available', () => {
|
||||||
|
const {component, setHasNextPage} = createHarness({totalElements: 100});
|
||||||
|
|
||||||
|
setHasNextPage(true);
|
||||||
|
|
||||||
|
vi.runOnlyPendingTimers();
|
||||||
|
TestBed.flushEffects();
|
||||||
|
|
||||||
|
expect(component.virtualGrid.virtualizer.options().count).toBe(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the rendered book count once pagination is exhausted', () => {
|
||||||
|
const {component} = createHarness({totalElements: 100});
|
||||||
|
const filter = TestBed.inject(SeriesCollapseFilter);
|
||||||
|
vi.mocked(filter.collapseBooks).mockImplementation((items: Book[]) => items.slice(0, 1));
|
||||||
|
|
||||||
|
vi.runOnlyPendingTimers();
|
||||||
|
TestBed.flushEffects();
|
||||||
|
|
||||||
|
expect(component.books()).toHaveLength(1);
|
||||||
|
expect(component.virtualGrid.virtualizer.options().count).toBe(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+144
-259
@@ -1,11 +1,11 @@
|
|||||||
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, computed, effect, inject, signal, untracked, ViewChild} from '@angular/core';
|
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, computed, effect, inject, signal, viewChild} from '@angular/core';
|
||||||
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
|
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||||
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
import {ActivatedRoute} from '@angular/router';
|
||||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||||
import {BookService} from '../../service/book.service';
|
import {BookService} from '../../service/book.service';
|
||||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||||
import {debounceTime, distinctUntilChanged, filter, map, take} from 'rxjs/operators';
|
import {debounceTime, distinctUntilChanged, filter, map, skip, take} from 'rxjs/operators';
|
||||||
import {combineLatest, finalize} from 'rxjs';
|
import {combineLatest, finalize} from 'rxjs';
|
||||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {Library} from '../../model/library.model';
|
import {Library} from '../../model/library.model';
|
||||||
@@ -13,9 +13,8 @@ import {SortDirection, SortOption} from '../../model/sort.model';
|
|||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
|
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
|
||||||
import {BookTableComponent} from './book-table/book-table.component';
|
import {BookTableComponent} from './book-table/book-table.component';
|
||||||
import {computeGridColumns} from '../../../../shared/util/viewport.util';
|
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {NgClass, NgStyle} from '@angular/common';
|
import {NgClass} from '@angular/common';
|
||||||
import {BookCardComponent} from './book-card/book-card.component';
|
import {BookCardComponent} from './book-card/book-card.component';
|
||||||
|
|
||||||
import {Menu} from 'primeng/menu';
|
import {Menu} from 'primeng/menu';
|
||||||
@@ -30,7 +29,6 @@ import {BookSorter} from './sorting/BookSorter';
|
|||||||
import {BookDialogHelperService} from './book-dialog-helper.service';
|
import {BookDialogHelperService} from './book-dialog-helper.service';
|
||||||
import {Checkbox} from 'primeng/checkbox';
|
import {Checkbox} from 'primeng/checkbox';
|
||||||
import {Popover} from 'primeng/popover';
|
import {Popover} from 'primeng/popover';
|
||||||
import {Slider} from 'primeng/slider';
|
|
||||||
import {Divider} from 'primeng/divider';
|
import {Divider} from 'primeng/divider';
|
||||||
import {MultiSelect} from 'primeng/multiselect';
|
import {MultiSelect} from 'primeng/multiselect';
|
||||||
import {TableColumnPreferenceService} from './table-column-preference.service';
|
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||||
@@ -48,15 +46,16 @@ import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.s
|
|||||||
import {BookSelectionService, CheckboxClickEvent} from './book-selection.service';
|
import {BookSelectionService, CheckboxClickEvent} from './book-selection.service';
|
||||||
import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.service';
|
import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.service';
|
||||||
import {BookBrowserEntityService, EntityInfo} from './book-browser-entity.service';
|
import {BookBrowserEntityService, EntityInfo} from './book-browser-entity.service';
|
||||||
import {BookBrowserScrollService} from './book-browser-scroll.service';
|
import {RouteScrollPositionService} from '../../../../shared/service/route-scroll-position.service';
|
||||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||||
import {MultiSortPopoverComponent} from './sorting/multi-sort-popover/multi-sort-popover.component';
|
import {MultiSortPopoverComponent} from './sorting/multi-sort-popover/multi-sort-popover.component';
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
import {DeferredRenderState} from './deferred-render-state';
|
|
||||||
|
|
||||||
import {SortService} from '../../service/sort.service';
|
import {SortService} from '../../service/sort.service';
|
||||||
import {AppBooksApiService} from '../../service/app-books-api.service';
|
import {AppBooksApiService} from '../../service/app-books-api.service';
|
||||||
import {AppBookFilters} from '../../model/app-book.model';
|
import {AppBookFilters} from '../../model/app-book.model';
|
||||||
|
import {createVirtualGrid, scaleForGridColumns} from '../../../../shared/util/virtual-grid.util';
|
||||||
|
import {GridDensityButtonsComponent} from '../../../../shared/components/grid-density-buttons/grid-density-buttons.component';
|
||||||
|
|
||||||
export enum EntityType {
|
export enum EntityType {
|
||||||
LIBRARY = 'Library',
|
LIBRARY = 'Library',
|
||||||
@@ -74,8 +73,8 @@ export enum EntityType {
|
|||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
imports: [
|
imports: [
|
||||||
Button, BookCardComponent, Menu, InputText, FormsModule,
|
Button, BookCardComponent, Menu, InputText, FormsModule,
|
||||||
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
|
BookTableComponent, BookFilterComponent, Tooltip, NgClass, Popover,
|
||||||
Checkbox, Slider, Divider, MultiSelect, TieredMenu, Badge, MultiSortPopoverComponent, TranslocoDirective,
|
Checkbox, Divider, MultiSelect, TieredMenu, Badge, MultiSortPopoverComponent, TranslocoDirective, GridDensityButtonsComponent,
|
||||||
],
|
],
|
||||||
providers: [SeriesCollapseFilter],
|
providers: [SeriesCollapseFilter],
|
||||||
})
|
})
|
||||||
@@ -93,7 +92,6 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
protected appSettingsService = inject(AppSettingsService);
|
protected appSettingsService = inject(AppSettingsService);
|
||||||
|
|
||||||
private activatedRoute = inject(ActivatedRoute);
|
private activatedRoute = inject(ActivatedRoute);
|
||||||
private router = inject(Router);
|
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private bookMetadataManageService = inject(BookMetadataManageService);
|
private bookMetadataManageService = inject(BookMetadataManageService);
|
||||||
@@ -108,7 +106,7 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
private sortService = inject(SortService);
|
private sortService = inject(SortService);
|
||||||
private appBooksApi = inject(AppBooksApiService);
|
private appBooksApi = inject(AppBooksApiService);
|
||||||
private localStorageService = inject(LocalStorageService);
|
private localStorageService = inject(LocalStorageService);
|
||||||
private scrollService = inject(BookBrowserScrollService);
|
private scrollService = inject(RouteScrollPositionService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
@@ -116,15 +114,13 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
this.loadMobileColumnsPreference();
|
this.loadMobileColumnsPreference();
|
||||||
this.setupRouteChangeHandlers();
|
this.setupRouteChangeHandlers();
|
||||||
this.setupQueryParamSubscription();
|
this.setupQueryParamSubscription();
|
||||||
this.setupScrollPositionTracking();
|
this.scrollService.trackRoute({
|
||||||
|
scrollElement: this.scrollElement,
|
||||||
this.destroyRef.onDestroy(() => {
|
route: this.activatedRoute,
|
||||||
if (this.scrollContainer) {
|
destroyRef: this.destroyRef,
|
||||||
this.scrollContainer.removeEventListener('scroll', this.onScroll);
|
dismissOverlaysBeforeSave: true,
|
||||||
}
|
|
||||||
this.containerResizeObserver?.disconnect();
|
|
||||||
this.sentinelObserver?.disconnect();
|
|
||||||
});
|
});
|
||||||
|
this.destroyRef.onDestroy(() => this.bookSelectionService.deselectAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly defaultSortCriteria: SortOption[] = [{
|
private readonly defaultSortCriteria: SortOption[] = [{
|
||||||
@@ -276,94 +272,63 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- Deferred render: lets skeleton/refresh indicator paint before committing ---
|
readonly books = computed(() => {
|
||||||
private readonly booksRenderState = new DeferredRenderState<Book[]>();
|
|
||||||
readonly books = this.booksRenderState.value;
|
|
||||||
readonly hasRenderedBooks = this.booksRenderState.hasValue;
|
|
||||||
readonly isBooksRefreshing = this.booksRenderState.isRefreshing;
|
|
||||||
|
|
||||||
private lastBooksContextKey: string | null = null;
|
|
||||||
private readonly booksContextKey = computed(() => {
|
|
||||||
const {entityId, entityType} = this.entityInfo();
|
|
||||||
return Number.isNaN(entityId) ? entityType : `${entityType}:${entityId}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
private readonly pipelineInputs = computed(() => {
|
|
||||||
const books = this.appBooksApi.books();
|
const books = this.appBooksApi.books();
|
||||||
return this.seriesCollapseFilter.collapseBooks(books, this.forceExpandSeries());
|
return this.seriesCollapseFilter.collapseBooks(books, this.forceExpandSeries());
|
||||||
});
|
});
|
||||||
|
|
||||||
private readonly renderBooksEffect = effect((onCleanup) => {
|
|
||||||
const contextKey = this.booksContextKey();
|
|
||||||
const books = this.pipelineInputs();
|
|
||||||
|
|
||||||
const shouldRefreshInPlace = untracked(() => this.hasRenderedBooks()) && contextKey === this.lastBooksContextKey;
|
|
||||||
this.lastBooksContextKey = contextKey;
|
|
||||||
|
|
||||||
if (shouldRefreshInPlace) {
|
|
||||||
this.booksRenderState.update(books);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestId = this.booksRenderState.begin('reset');
|
|
||||||
|
|
||||||
const timeout = globalThis.setTimeout(() => {
|
|
||||||
this.booksRenderState.commit(requestId, books);
|
|
||||||
});
|
|
||||||
|
|
||||||
onCleanup(() => {
|
|
||||||
clearTimeout(timeout);
|
|
||||||
this.booksRenderState.cancel(requestId);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
readonly isBooksLoading = computed(() => this.appBooksApi.isLoading());
|
readonly isBooksLoading = computed(() => this.appBooksApi.isLoading());
|
||||||
readonly booksError = this.appBooksApi.error;
|
readonly booksError = this.appBooksApi.error;
|
||||||
readonly bookIndexById = computed(() => {
|
|
||||||
const books = this.books();
|
|
||||||
if (!books) return new Map<number, number>();
|
|
||||||
const map = new Map<number, number>();
|
|
||||||
for (let i = 0; i < books.length; i++) {
|
|
||||||
map.set(books[i].id, i);
|
|
||||||
}
|
|
||||||
return map;
|
|
||||||
});
|
|
||||||
readonly compareBookItems = (a: Book, b: Book): boolean => a?.id === b?.id;
|
|
||||||
|
|
||||||
private readonly GRID_GAP = 21;
|
private readonly GRID_GAP = 21;
|
||||||
private readonly containerWidth = signal(0);
|
private readonly MOBILE_BREAKPOINT = 768;
|
||||||
private containerResizeObserver: ResizeObserver | undefined;
|
private readonly CARD_ASPECT_RATIO = 7 / 5;
|
||||||
|
private readonly MOBILE_GAP = 8;
|
||||||
readonly gridColumns = computed(() => {
|
private readonly MOBILE_PADDING = 48;
|
||||||
return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth(), 10) || 180, this.GRID_GAP);
|
private readonly MOBILE_TITLE_BAR_HEIGHT = 32;
|
||||||
|
private readonly MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference';
|
||||||
|
private readonly DESKTOP_CARD_BASE_WIDTH = 135;
|
||||||
|
private readonly DESKTOP_CARD_BASE_HEIGHT = 220;
|
||||||
|
private readonly DESKTOP_MIN_SCALE = 0.5;
|
||||||
|
private readonly DESKTOP_MAX_SCALE = 1.5;
|
||||||
|
private readonly AUDIOBOOK_TITLE_BAR_HEIGHT = 31;
|
||||||
|
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
|
||||||
|
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute)) ?? 0;
|
||||||
|
private readonly gridBooks = this.books;
|
||||||
|
private readonly desktopBaseCardWidth = computed(() =>
|
||||||
|
this.isAudiobookOnlyLibrary()
|
||||||
|
? this.DESKTOP_CARD_BASE_WIDTH * 1.1
|
||||||
|
: this.DESKTOP_CARD_BASE_WIDTH
|
||||||
|
);
|
||||||
|
private readonly minCardWidth = computed(() =>
|
||||||
|
this.isMobile()
|
||||||
|
? 1
|
||||||
|
: Math.round(this.desktopBaseCardWidth() * this.coverScalePreferenceService.scaleFactor())
|
||||||
|
);
|
||||||
|
private readonly virtualGridGap = computed(() => this.isMobile() ? this.MOBILE_GAP : this.GRID_GAP);
|
||||||
|
private readonly virtualGridColumns = computed(() => this.isMobile() ? this.mobileColumnCount() : undefined);
|
||||||
|
private readonly isGridView = computed(() => this.currentViewMode() === VIEW_MODES.GRID);
|
||||||
|
private readonly virtualBookCount = computed(() => {
|
||||||
|
const renderedBookCount = this.gridBooks().length;
|
||||||
|
return this.appBooksApi.hasNextPage()
|
||||||
|
? Math.max(this.appBooksApi.totalElements(), renderedBookCount)
|
||||||
|
: renderedBookCount;
|
||||||
});
|
});
|
||||||
|
readonly virtualGrid = createVirtualGrid({
|
||||||
/**
|
items: this.gridBooks,
|
||||||
* Estimated total content height based on totalElements from the first API page.
|
scrollElement: this.scrollElement,
|
||||||
* Used as min-height so the scrollbar reflects the full collection from the start.
|
minItemWidth: this.minCardWidth,
|
||||||
* Only grows, never shrinks — prevents scroll teleportation.
|
gap: this.virtualGridGap,
|
||||||
*/
|
columns: this.virtualGridColumns,
|
||||||
readonly estimatedTotalHeight = computed(() => {
|
count: this.virtualBookCount,
|
||||||
const total = this.appBooksApi.totalElements();
|
enabled: this.isGridView,
|
||||||
if (total === 0) return 0;
|
initialOffset: this.initialScrollOffset,
|
||||||
const cols = this.gridColumns();
|
fillItemWidth: true,
|
||||||
const rows = Math.ceil(total / cols);
|
estimateItemHeight: itemWidth => this.isMobile()
|
||||||
const rowHeight = this.currentCardSize().height + this.GRID_GAP;
|
? this.mobileCardSizeForWidth(itemWidth).height
|
||||||
return rows * rowHeight;
|
: this.cardSizeForWidth(itemWidth).height,
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* Total height of currently loaded books in grid view.
|
|
||||||
*/
|
|
||||||
readonly renderedHeight = computed(() => {
|
|
||||||
const books = this.books();
|
|
||||||
if (!books || books.length === 0) return 0;
|
|
||||||
const cols = this.gridColumns();
|
|
||||||
const rows = Math.ceil(books.length / cols);
|
|
||||||
const rowHeight = this.currentCardSize().height + this.GRID_GAP;
|
|
||||||
return rows * rowHeight;
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
skeletonSlots = Array.from({length: 24}, (_, index) => index);
|
skeletonSlots = Array.from({length: 24}, (_, index) => index);
|
||||||
readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index);
|
readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index);
|
||||||
readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
|
readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
|
||||||
@@ -407,13 +372,6 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
entityViewPreferences: EntityViewPreferences | undefined;
|
entityViewPreferences: EntityViewPreferences | undefined;
|
||||||
lastAppliedSortCriteria: SortOption[] = [];
|
lastAppliedSortCriteria: SortOption[] = [];
|
||||||
|
|
||||||
private readonly MOBILE_BREAKPOINT = 768;
|
|
||||||
private readonly CARD_ASPECT_RATIO = 7 / 5;
|
|
||||||
private readonly MOBILE_GAP = 8;
|
|
||||||
private readonly MOBILE_PADDING = 48;
|
|
||||||
private readonly MOBILE_TITLE_BAR_HEIGHT = 32;
|
|
||||||
private readonly MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference';
|
|
||||||
|
|
||||||
private settingFiltersFromUrl = false;
|
private settingFiltersFromUrl = false;
|
||||||
protected metadataMenuItems: MenuItem[] | undefined;
|
protected metadataMenuItems: MenuItem[] | undefined;
|
||||||
protected moreActionsMenuItems: MenuItem[] | undefined;
|
protected moreActionsMenuItems: MenuItem[] | undefined;
|
||||||
@@ -467,12 +425,6 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
});
|
});
|
||||||
private readonly syncBooksEffect = effect(() => {
|
private readonly syncBooksEffect = effect(() => {
|
||||||
const books = this.books();
|
const books = this.books();
|
||||||
if (!books) {
|
|
||||||
this.bookSelectionService.setCurrentBooks([]);
|
|
||||||
this.bookNavigationService.setAvailableBookIds([]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.bookSelectionService.setCurrentBooks(books);
|
this.bookSelectionService.setCurrentBooks(books);
|
||||||
this.bookNavigationService.setAvailableBookIds(books.map(book => book.id));
|
this.bookNavigationService.setAvailableBookIds(books.map(book => book.id));
|
||||||
});
|
});
|
||||||
@@ -483,61 +435,26 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
private readonly fetchNextPageEffect = effect(() => {
|
||||||
* Triggers sequential page loads if the current scroll position is beyond the loaded content.
|
if (this.currentViewMode() !== VIEW_MODES.GRID) return;
|
||||||
* This is critical for scroll restoration on page reload.
|
|
||||||
*/
|
const virtualItems = this.virtualGrid.virtualizer.getVirtualItems();
|
||||||
private readonly fillScrollGapEffect = effect(() => {
|
const loadedBookCount = this.gridBooks().length;
|
||||||
const books = this.books();
|
const lastItem = virtualItems.at(-1);
|
||||||
if (books && books.length > 0) {
|
|
||||||
this.checkAndFetchIfNeeded();
|
if (
|
||||||
|
lastItem &&
|
||||||
|
loadedBookCount > 0 &&
|
||||||
|
lastItem.index >= loadedBookCount - 1 &&
|
||||||
|
this.appBooksApi.hasNextPage() &&
|
||||||
|
!this.appBooksApi.isFetchingNextPage()
|
||||||
|
) {
|
||||||
|
this.appBooksApi.fetchNextPage();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ViewChild(BookTableComponent)
|
private readonly bookTableComponent = viewChild(BookTableComponent);
|
||||||
bookTableComponent!: BookTableComponent;
|
private readonly bookFilterComponent = viewChild(BookFilterComponent);
|
||||||
@ViewChild(BookFilterComponent, {static: true})
|
|
||||||
bookFilterComponent!: BookFilterComponent;
|
|
||||||
|
|
||||||
private scrollContainer: HTMLElement | undefined;
|
|
||||||
private sentinelObserver: IntersectionObserver | undefined;
|
|
||||||
|
|
||||||
@ViewChild('scrollContainer')
|
|
||||||
set scrollContainerRef(ref: ElementRef<HTMLElement> | undefined) {
|
|
||||||
this.containerResizeObserver?.disconnect();
|
|
||||||
if (this.scrollContainer) {
|
|
||||||
this.scrollContainer.removeEventListener('scroll', this.onScroll);
|
|
||||||
}
|
|
||||||
this.scrollContainer = ref?.nativeElement;
|
|
||||||
if (this.scrollContainer) {
|
|
||||||
const el = this.scrollContainer;
|
|
||||||
this.containerWidth.set(el.clientWidth);
|
|
||||||
this.containerResizeObserver = new ResizeObserver(entries => {
|
|
||||||
this.containerWidth.set(entries[0]?.contentRect.width ?? el.clientWidth);
|
|
||||||
});
|
|
||||||
this.containerResizeObserver.observe(el);
|
|
||||||
el.addEventListener('scroll', this.onScroll, {passive: true});
|
|
||||||
// Initial check in case we are already scrolled down
|
|
||||||
globalThis.requestAnimationFrame(() => this.checkAndFetchIfNeeded());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@ViewChild('scrollSentinel')
|
|
||||||
set scrollSentinelRef(ref: ElementRef<HTMLElement> | undefined) {
|
|
||||||
this.sentinelObserver?.disconnect();
|
|
||||||
const el = ref?.nativeElement;
|
|
||||||
if (el) {
|
|
||||||
this.sentinelObserver = new IntersectionObserver(
|
|
||||||
entries => {
|
|
||||||
if (entries[0]?.isIntersecting) {
|
|
||||||
this.checkAndFetchNextPage();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{root: this.scrollContainer, rootMargin: '600px'}
|
|
||||||
);
|
|
||||||
this.sentinelObserver.observe(el);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@HostListener('window:resize')
|
@HostListener('window:resize')
|
||||||
onResize(): void {
|
onResize(): void {
|
||||||
@@ -556,40 +473,41 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
return {width: cardWidth, height: cardHeight};
|
return {width: cardWidth, height: cardHeight};
|
||||||
});
|
});
|
||||||
|
|
||||||
readonly currentCardSize = computed(() => {
|
readonly currentCardSize = computed<{width: number; height: number}>(() => {
|
||||||
if (this.isMobile()) {
|
if (this.isMobile()) {
|
||||||
return this.mobileCardSize();
|
const width = this.virtualGrid.viewportWidth() > 0
|
||||||
|
? this.virtualGrid.itemWidth()
|
||||||
|
: this.mobileCardSize().width;
|
||||||
|
return this.mobileCardSizeForWidth(width);
|
||||||
}
|
}
|
||||||
const base = this.coverScalePreferenceService.currentCardSize();
|
return this.cardSizeForWidth(this.virtualGrid.itemWidth());
|
||||||
if (this.isAudiobookOnlyLibrary()) {
|
|
||||||
const squareSide = Math.round(base.width * 1.1);
|
|
||||||
return { width: squareSide, height: squareSide + 31 };
|
|
||||||
}
|
|
||||||
return base;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
readonly gridColumnMinWidth = computed(() => {
|
readonly skeletonMinCardWidth = computed(() =>
|
||||||
if (this.isMobile()) {
|
`${this.isMobile() ? this.mobileCardSize().width : this.minCardWidth()}px`
|
||||||
return `${this.mobileCardSize().width}px`;
|
);
|
||||||
}
|
|
||||||
if (this.isAudiobookOnlyLibrary()) {
|
|
||||||
return `${this.currentCardSize().width}px`;
|
|
||||||
}
|
|
||||||
return this.coverScalePreferenceService.gridColumnMinWidth();
|
|
||||||
});
|
|
||||||
|
|
||||||
getCardHeight(_book: Book): number {
|
private cardSizeForWidth(width: number): { width: number; height: number } {
|
||||||
if (this.isMobile()) {
|
const cardWidth = Math.round(width);
|
||||||
return this.mobileCardSize().height;
|
|
||||||
}
|
|
||||||
if (this.isAudiobookOnlyLibrary()) {
|
if (this.isAudiobookOnlyLibrary()) {
|
||||||
return this.currentCardSize().height;
|
return {width: cardWidth, height: cardWidth + this.AUDIOBOOK_TITLE_BAR_HEIGHT};
|
||||||
}
|
}
|
||||||
return this.coverScalePreferenceService.getCardHeight(_book);
|
return {
|
||||||
|
width: cardWidth,
|
||||||
|
height: Math.round(cardWidth * (this.DESKTOP_CARD_BASE_HEIGHT / this.DESKTOP_CARD_BASE_WIDTH)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private mobileCardSizeForWidth(width: number): { width: number; height: number } {
|
||||||
|
const cardWidth = Math.round(width);
|
||||||
|
const coverHeight = this.isAudiobookOnlyLibrary()
|
||||||
|
? cardWidth
|
||||||
|
: Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
|
||||||
|
return {width: cardWidth, height: coverHeight + this.MOBILE_TITLE_BAR_HEIGHT};
|
||||||
}
|
}
|
||||||
|
|
||||||
readonly showBooksLoadingPlaceholder = computed(() =>
|
readonly showBooksLoadingPlaceholder = computed(() =>
|
||||||
!this.booksError() && (this.isBooksLoading() || !this.hasRenderedBooks())
|
!this.booksError() && this.isBooksLoading() && this.books().length === 0
|
||||||
);
|
);
|
||||||
|
|
||||||
readonly showTableLoadingPlaceholder = computed(() =>
|
readonly showTableLoadingPlaceholder = computed(() =>
|
||||||
@@ -636,61 +554,18 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
readonly sortCriteriaCount = computed(() => this.bookSorter.selectedSortCriteria.length);
|
readonly sortCriteriaCount = computed(() => this.bookSorter.selectedSortCriteria.length);
|
||||||
|
|
||||||
ngAfterViewInit(): void {
|
ngAfterViewInit(): void {
|
||||||
if (this.bookFilterComponent) {
|
const bookFilterComponent = this.bookFilterComponent();
|
||||||
this.bookFilterComponent.setFilters(this.parsedFilters);
|
if (bookFilterComponent) {
|
||||||
this.bookFilterComponent.onFilterModeChange(this.selectedFilterMode());
|
bookFilterComponent.setFilters(this.parsedFilters);
|
||||||
}
|
bookFilterComponent.onFilterModeChange(this.selectedFilterMode());
|
||||||
}
|
|
||||||
|
|
||||||
private onScroll = (): void => {
|
|
||||||
this.checkAndFetchIfNeeded();
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if the current scroll position plus viewport exceeds the rendered height (with a buffer)
|
|
||||||
* and fetches the next page if necessary.
|
|
||||||
*/
|
|
||||||
private checkAndFetchIfNeeded(): void {
|
|
||||||
if (!this.scrollContainer || this.currentViewMode() !== VIEW_MODES.GRID) return;
|
|
||||||
|
|
||||||
const {scrollTop, clientHeight} = this.scrollContainer;
|
|
||||||
const buffer = 1000; // Large buffer to facilitate scroll restoration
|
|
||||||
const renderedHeight = untracked(() => this.renderedHeight());
|
|
||||||
|
|
||||||
if (scrollTop + clientHeight >= renderedHeight - buffer) {
|
|
||||||
untracked(() => this.checkAndFetchNextPage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private checkAndFetchNextPage(): void {
|
|
||||||
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
|
|
||||||
this.appBooksApi.fetchNextPage();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getScrollPositionKey(): string {
|
|
||||||
const path = this.activatedRoute.snapshot.routeConfig?.path ?? '';
|
|
||||||
return this.scrollService.createKey(path, this.activatedRoute.snapshot.params);
|
|
||||||
}
|
|
||||||
|
|
||||||
private setupScrollPositionTracking(): void {
|
|
||||||
this.router.events.pipe(
|
|
||||||
filter(event => event instanceof NavigationStart),
|
|
||||||
takeUntilDestroyed(this.destroyRef)
|
|
||||||
).subscribe(() => {
|
|
||||||
this.saveScrollPosition();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private saveScrollPosition(): void {
|
|
||||||
if (this.scrollContainer) {
|
|
||||||
const key = this.getScrollPositionKey();
|
|
||||||
this.scrollService.savePosition(key, this.scrollContainer.scrollTop);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupRouteChangeHandlers(): void {
|
private setupRouteChangeHandlers(): void {
|
||||||
this.activatedRoute.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
|
this.activatedRoute.paramMap.pipe(
|
||||||
|
skip(1),
|
||||||
|
takeUntilDestroyed(this.destroyRef)
|
||||||
|
).subscribe(() => {
|
||||||
this.searchTerm.set('');
|
this.searchTerm.set('');
|
||||||
this.bookTitle.set('');
|
this.bookTitle.set('');
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
@@ -700,12 +575,11 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private scrollToTop(): void {
|
private scrollToTop(): void {
|
||||||
if (this.scrollContainer) {
|
const scrollElement = this.scrollElement()?.nativeElement;
|
||||||
this.scrollContainer.scrollTop = 0;
|
if (scrollElement) {
|
||||||
}
|
scrollElement.scrollTop = 0;
|
||||||
if (this.bookTableComponent) {
|
|
||||||
this.bookTableComponent.scrollToTop();
|
|
||||||
}
|
}
|
||||||
|
this.bookTableComponent()?.scrollToTop();
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly syncMetadataMenuEffect = effect(() => {
|
private readonly syncMetadataMenuEffect = effect(() => {
|
||||||
@@ -740,12 +614,9 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
currentUser.userSettings?.filterMode ?? 'and'
|
currentUser.userSettings?.filterMode ?? 'and'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
if (parseResult.filterMode !== this.selectedFilterMode()) {
|
if (parseResult.filterMode !== this.selectedFilterMode()) {
|
||||||
this.selectedFilterMode.set(parseResult.filterMode);
|
this.selectedFilterMode.set(parseResult.filterMode);
|
||||||
if (this.bookFilterComponent) {
|
this.bookFilterComponent()?.onFilterModeChange(parseResult.filterMode);
|
||||||
this.bookFilterComponent.onFilterModeChange(parseResult.filterMode);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const filterParams = queryParamMap.get('filter');
|
const filterParams = queryParamMap.get('filter');
|
||||||
@@ -754,9 +625,7 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
this.settingFiltersFromUrl = true;
|
this.settingFiltersFromUrl = true;
|
||||||
this.selectedFilter.set(parseResult.filters);
|
this.selectedFilter.set(parseResult.filters);
|
||||||
|
|
||||||
if (this.bookFilterComponent) {
|
this.bookFilterComponent()?.setFilters?.(parseResult.filters);
|
||||||
this.bookFilterComponent.setFilters?.(parseResult.filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Object.keys(parseResult.filters).length > 0) {
|
if (Object.keys(parseResult.filters).length > 0) {
|
||||||
this.currentFilterLabel.set(this.computedFilterLabel());
|
this.currentFilterLabel.set(this.computedFilterLabel());
|
||||||
@@ -771,7 +640,6 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
|
|
||||||
this.parsedFilters = parseResult.filters;
|
this.parsedFilters = parseResult.filters;
|
||||||
|
|
||||||
|
|
||||||
this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences;
|
this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences;
|
||||||
this.columnPreferenceService.initPreferences(currentUser.userSettings?.tableColumnPreference);
|
this.columnPreferenceService.initPreferences(currentUser.userSettings?.tableColumnPreference);
|
||||||
this.visibleColumns.set(this.columnPreferenceService.visibleColumns);
|
this.visibleColumns.set(this.columnPreferenceService.visibleColumns);
|
||||||
@@ -780,7 +648,6 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
const sortOptionsByField = new Map(this.bookSorter.sortOptions.map(o => [o.field, o]));
|
const sortOptionsByField = new Map(this.bookSorter.sortOptions.map(o => [o.field, o]));
|
||||||
this.visibleSortOptions.set(visibleFields.map(f => sortOptionsByField.get(f)).filter((o): o is SortOption => !!o));
|
this.visibleSortOptions.set(visibleFields.map(f => sortOptionsByField.get(f)).filter((o): o is SortOption => !!o));
|
||||||
|
|
||||||
|
|
||||||
if (!this.areSortCriteriaEqual(this.bookSorter.selectedSortCriteria, parseResult.sortCriteria)) {
|
if (!this.areSortCriteriaEqual(this.bookSorter.selectedSortCriteria, parseResult.sortCriteria)) {
|
||||||
this.bookSorter.setSortCriteria(parseResult.sortCriteria);
|
this.bookSorter.setSortCriteria(parseResult.sortCriteria);
|
||||||
}
|
}
|
||||||
@@ -788,7 +655,6 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
|
|
||||||
this.applySortCriteria(this.bookSorter.selectedSortCriteria);
|
this.applySortCriteria(this.bookSorter.selectedSortCriteria);
|
||||||
|
|
||||||
|
|
||||||
this.queryParamsService.syncQueryParams(
|
this.queryParamsService.syncQueryParams(
|
||||||
this.currentViewMode()!,
|
this.currentViewMode()!,
|
||||||
this.selectedFilterMode(),
|
this.selectedFilterMode(),
|
||||||
@@ -829,7 +695,10 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
|
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
|
||||||
const allFields = this.bookTableComponent.allColumns.map(col => col.field);
|
const bookTableComponent = this.bookTableComponent();
|
||||||
|
if (!bookTableComponent) return;
|
||||||
|
|
||||||
|
const allFields = bookTableComponent.allColumns.map(col => col.field);
|
||||||
this.visibleColumns.set(selected.sort(
|
this.visibleColumns.set(selected.sort(
|
||||||
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
|
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
|
||||||
));
|
));
|
||||||
@@ -860,9 +729,7 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
|
|
||||||
deselectAllBooks(): void {
|
deselectAllBooks(): void {
|
||||||
this.bookSelectionService.deselectAll();
|
this.bookSelectionService.deselectAll();
|
||||||
if (this.bookTableComponent) {
|
this.bookTableComponent()?.clearSelectedBooks();
|
||||||
this.bookTableComponent.clearSelectedBooks();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
confirmDeleteBooks(): void {
|
confirmDeleteBooks(): void {
|
||||||
@@ -1010,7 +877,7 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
resetFilters(): void {
|
resetFilters(): void {
|
||||||
this.bookFilterComponent?.clearActiveFilter();
|
this.bookFilterComponent()?.clearActiveFilter();
|
||||||
}
|
}
|
||||||
|
|
||||||
clearFilter(): void {
|
clearFilter(): void {
|
||||||
@@ -1192,7 +1059,7 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
|
|
||||||
attachFilesToBook(): void {
|
attachFilesToBook(): void {
|
||||||
const selectedBookIds = Array.from(this.selectedBooks());
|
const selectedBookIds = Array.from(this.selectedBooks());
|
||||||
const sourceBooks = (this.books() ?? []).filter(book =>
|
const sourceBooks = this.books().filter(book =>
|
||||||
selectedBookIds.includes(book.id)
|
selectedBookIds.includes(book.id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1230,7 +1097,7 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
const selectedBookIds = Array.from(this.selectedBooks());
|
const selectedBookIds = Array.from(this.selectedBooks());
|
||||||
if (selectedBookIds.length === 0) return false;
|
if (selectedBookIds.length === 0) return false;
|
||||||
|
|
||||||
const selectedBooks = (this.books() ?? []).filter(book =>
|
const selectedBooks = this.books().filter(book =>
|
||||||
selectedBookIds.includes(book.id)
|
selectedBookIds.includes(book.id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1245,6 +1112,24 @@ export class BookBrowserComponent implements AfterViewInit {
|
|||||||
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
|
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
adjustDesktopGridDensity(direction: 'smaller' | 'larger'): void {
|
||||||
|
const currentColumns = this.virtualGrid.gridColumns();
|
||||||
|
const columns = Math.max(1, direction === 'smaller'
|
||||||
|
? currentColumns + 1
|
||||||
|
: currentColumns - 1);
|
||||||
|
const viewportWidth = this.virtualGrid.viewportWidth() || this.screenWidth();
|
||||||
|
this.virtualGrid.updatePreservingScrollPosition(() => {
|
||||||
|
this.coverScalePreferenceService.setScale(scaleForGridColumns(
|
||||||
|
viewportWidth,
|
||||||
|
this.GRID_GAP,
|
||||||
|
columns,
|
||||||
|
this.desktopBaseCardWidth(),
|
||||||
|
this.DESKTOP_MIN_SCALE,
|
||||||
|
this.DESKTOP_MAX_SCALE
|
||||||
|
));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private loadMobileColumnsPreference(): void {
|
private loadMobileColumnsPreference(): void {
|
||||||
const saved = this.localStorageService.get<number>(this.MOBILE_COLUMNS_STORAGE_KEY);
|
const saved = this.localStorageService.get<number>(this.MOBILE_COLUMNS_STORAGE_KEY);
|
||||||
if (saved !== null && [2, 3, 4].includes(saved)) {
|
if (saved !== null && [2, 3, 4].includes(saved)) {
|
||||||
|
|||||||
-7
@@ -110,13 +110,6 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
|||||||
this.selectedBookIds = new Set(this.preselectedBookIds);
|
this.selectedBookIds = new Set(this.preselectedBookIds);
|
||||||
this.syncSelectedBooks();
|
this.syncSelectedBooks();
|
||||||
}
|
}
|
||||||
|
|
||||||
const wrapperElements = this.elementRef.nativeElement.querySelectorAll('.p-virtualscroller');
|
|
||||||
wrapperElements.forEach((wrapperElement: Element) => {
|
|
||||||
if (wrapperElement instanceof HTMLElement) {
|
|
||||||
wrapperElement.style.height = 'calc(100dvh - 160px)';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private syncSelectedBooks(): void {
|
private syncSelectedBooks(): void {
|
||||||
|
|||||||
+17
-50
@@ -1,6 +1,4 @@
|
|||||||
import {TestBed} from '@angular/core/testing';
|
import {TestBed} from '@angular/core/testing';
|
||||||
import {MessageService} from 'primeng/api';
|
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
|
||||||
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
import {vi, describe, beforeEach, afterEach, expect, it} from 'vitest';
|
||||||
|
|
||||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||||
@@ -9,28 +7,15 @@ import {LocalStorageService} from '../../../../shared/service/local-storage.serv
|
|||||||
describe('CoverScalePreferenceService', () => {
|
describe('CoverScalePreferenceService', () => {
|
||||||
let service: CoverScalePreferenceService;
|
let service: CoverScalePreferenceService;
|
||||||
let localStorageService: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
|
let localStorageService: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
|
||||||
let messageService: { add: ReturnType<typeof vi.fn> };
|
|
||||||
let translocoService: { translate: ReturnType<typeof vi.fn> };
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.useFakeTimers();
|
|
||||||
localStorageService = {
|
localStorageService = {
|
||||||
get: vi.fn(),
|
get: vi.fn(),
|
||||||
set: vi.fn()
|
set: vi.fn()
|
||||||
};
|
};
|
||||||
messageService = {
|
|
||||||
add: vi.fn()
|
|
||||||
};
|
|
||||||
translocoService = {
|
|
||||||
translate: vi.fn((key: string, params?: Record<string, unknown>) =>
|
|
||||||
params ? `${key}:${JSON.stringify(params)}` : `t:${key}`
|
|
||||||
)
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.runOnlyPendingTimers();
|
|
||||||
vi.useRealTimers();
|
|
||||||
TestBed.resetTestingModule();
|
TestBed.resetTestingModule();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,8 +26,6 @@ describe('CoverScalePreferenceService', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
CoverScalePreferenceService,
|
CoverScalePreferenceService,
|
||||||
{provide: LocalStorageService, useValue: localStorageService},
|
{provide: LocalStorageService, useValue: localStorageService},
|
||||||
{provide: MessageService, useValue: messageService},
|
|
||||||
{provide: TranslocoService, useValue: translocoService}
|
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -50,8 +33,22 @@ describe('CoverScalePreferenceService', () => {
|
|||||||
|
|
||||||
expect(service.scaleFactor()).toBe(1.5);
|
expect(service.scaleFactor()).toBe(1.5);
|
||||||
expect(service.currentCardSize()).toEqual({width: 203, height: 330});
|
expect(service.currentCardSize()).toEqual({width: 203, height: 330});
|
||||||
expect(service.gridColumnMinWidth()).toBe('203px');
|
});
|
||||||
expect(service.getCardHeight({} as never)).toBe(330);
|
|
||||||
|
it('normalizes out-of-range saved scale values', () => {
|
||||||
|
localStorageService.get.mockReturnValue(3);
|
||||||
|
|
||||||
|
TestBed.configureTestingModule({
|
||||||
|
providers: [
|
||||||
|
CoverScalePreferenceService,
|
||||||
|
{provide: LocalStorageService, useValue: localStorageService},
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
service = TestBed.inject(CoverScalePreferenceService);
|
||||||
|
|
||||||
|
expect(service.scaleFactor()).toBe(1.5);
|
||||||
|
expect(localStorageService.set).toHaveBeenCalledWith('coverScalePreference', 1.5);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('falls back to the default scale and skips persistence when unchanged', () => {
|
it('falls back to the default scale and skips persistence when unchanged', () => {
|
||||||
@@ -61,60 +58,30 @@ describe('CoverScalePreferenceService', () => {
|
|||||||
providers: [
|
providers: [
|
||||||
CoverScalePreferenceService,
|
CoverScalePreferenceService,
|
||||||
{provide: LocalStorageService, useValue: localStorageService},
|
{provide: LocalStorageService, useValue: localStorageService},
|
||||||
{provide: MessageService, useValue: messageService},
|
|
||||||
{provide: TranslocoService, useValue: translocoService}
|
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(CoverScalePreferenceService);
|
service = TestBed.inject(CoverScalePreferenceService);
|
||||||
|
|
||||||
service.setScale(1.0);
|
service.setScale(1.0);
|
||||||
vi.runOnlyPendingTimers();
|
|
||||||
|
|
||||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
expect(localStorageService.set).not.toHaveBeenCalled();
|
||||||
expect(messageService.add).not.toHaveBeenCalled();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('persists updated scale after debounce and reports failures', () => {
|
it('persists updated scale immediately without showing a toast', () => {
|
||||||
localStorageService.get.mockReturnValue(1.0);
|
localStorageService.get.mockReturnValue(1.0);
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
TestBed.configureTestingModule({
|
||||||
providers: [
|
providers: [
|
||||||
CoverScalePreferenceService,
|
CoverScalePreferenceService,
|
||||||
{provide: LocalStorageService, useValue: localStorageService},
|
{provide: LocalStorageService, useValue: localStorageService},
|
||||||
{provide: MessageService, useValue: messageService},
|
|
||||||
{provide: TranslocoService, useValue: translocoService}
|
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
service = TestBed.inject(CoverScalePreferenceService);
|
service = TestBed.inject(CoverScalePreferenceService);
|
||||||
|
|
||||||
service.setScale(1.2);
|
service.setScale(1.2);
|
||||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(1000);
|
|
||||||
|
|
||||||
expect(localStorageService.set).toHaveBeenCalledWith('coverScalePreference', 1.2);
|
expect(localStorageService.set).toHaveBeenCalledWith('coverScalePreference', 1.2);
|
||||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
severity: 'success',
|
|
||||||
summary: 't:book.coverPref.toast.savedSummary',
|
|
||||||
detail: 'book.coverPref.toast.savedDetail:{"scale":"1.20"}',
|
|
||||||
life: 1500
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.clearAllMocks();
|
|
||||||
localStorageService.set.mockImplementation(() => {
|
|
||||||
throw new Error('storage unavailable');
|
|
||||||
});
|
|
||||||
|
|
||||||
service.setScale(1.3);
|
|
||||||
vi.advanceTimersByTime(1000);
|
|
||||||
|
|
||||||
expect(messageService.add).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
severity: 'error',
|
|
||||||
summary: 't:book.coverPref.toast.saveFailedSummary',
|
|
||||||
detail: 't:book.coverPref.toast.saveFailedDetail',
|
|
||||||
life: 3000
|
|
||||||
}));
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+11
-72
@@ -1,8 +1,6 @@
|
|||||||
import {computed, inject, Injectable, signal} from '@angular/core';
|
import {computed, inject, Injectable} from '@angular/core';
|
||||||
import {MessageService} from 'primeng/api';
|
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
|
||||||
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||||
import {Book} from '../../model/book.model';
|
import {ScalePreference} from '../../../../shared/util/scale-preference.util';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
@@ -11,83 +9,24 @@ export class CoverScalePreferenceService {
|
|||||||
|
|
||||||
private readonly BASE_WIDTH = 135;
|
private readonly BASE_WIDTH = 135;
|
||||||
private readonly BASE_HEIGHT = 220;
|
private readonly BASE_HEIGHT = 220;
|
||||||
private readonly TITLE_BAR_HEIGHT = 31;
|
|
||||||
private readonly DEBOUNCE_MS = 1000;
|
|
||||||
private readonly STORAGE_KEY = 'coverScalePreference';
|
private readonly STORAGE_KEY = 'coverScalePreference';
|
||||||
|
private readonly MIN_SCALE = 0.5;
|
||||||
|
private readonly MAX_SCALE = 1.5;
|
||||||
|
|
||||||
private readonly messageService = inject(MessageService);
|
|
||||||
private readonly t = inject(TranslocoService);
|
|
||||||
private readonly localStorageService = inject(LocalStorageService);
|
private readonly localStorageService = inject(LocalStorageService);
|
||||||
|
private readonly scalePreference = new ScalePreference(this.localStorageService, {
|
||||||
private readonly _scaleFactor = signal(1.0);
|
storageKey: this.STORAGE_KEY,
|
||||||
readonly scaleFactor = this._scaleFactor.asReadonly();
|
minScale: this.MIN_SCALE,
|
||||||
|
maxScale: this.MAX_SCALE,
|
||||||
|
});
|
||||||
|
readonly scaleFactor = this.scalePreference.scaleFactor;
|
||||||
|
|
||||||
readonly currentCardSize = computed(() => ({
|
readonly currentCardSize = computed(() => ({
|
||||||
width: Math.round(this.BASE_WIDTH * this.scaleFactor()),
|
width: Math.round(this.BASE_WIDTH * this.scaleFactor()),
|
||||||
height: Math.round(this.BASE_HEIGHT * this.scaleFactor()),
|
height: Math.round(this.BASE_HEIGHT * this.scaleFactor()),
|
||||||
}));
|
}));
|
||||||
readonly gridColumnMinWidth = computed(() => `${this.currentCardSize().width}px`);
|
|
||||||
|
|
||||||
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
private lastPersistedScale = 1.0;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
const initialScale = this.loadScaleFromStorage();
|
|
||||||
this._scaleFactor.set(initialScale);
|
|
||||||
this.lastPersistedScale = initialScale;
|
|
||||||
}
|
|
||||||
|
|
||||||
setScale(scale: number): void {
|
setScale(scale: number): void {
|
||||||
this._scaleFactor.set(scale);
|
this.scalePreference.setScale(scale);
|
||||||
if (scale === this.lastPersistedScale) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.scheduleSave(scale);
|
|
||||||
}
|
|
||||||
|
|
||||||
getCardHeight(_book: Book): number {
|
|
||||||
void _book;
|
|
||||||
// Use uniform height for all book types to ensure smooth virtual scrolling.
|
|
||||||
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
|
|
||||||
// cannot accurately estimate positions when item heights vary.
|
|
||||||
return this.currentCardSize().height;
|
|
||||||
}
|
|
||||||
|
|
||||||
private scheduleSave(scale: number): void {
|
|
||||||
if (this.saveTimeout) {
|
|
||||||
clearTimeout(this.saveTimeout);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.saveTimeout = setTimeout(() => {
|
|
||||||
this.saveScalePreference(scale);
|
|
||||||
}, this.DEBOUNCE_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private saveScalePreference(scale: number): void {
|
|
||||||
try {
|
|
||||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
|
||||||
this.lastPersistedScale = scale;
|
|
||||||
this.messageService.add({
|
|
||||||
severity: 'success',
|
|
||||||
summary: this.t.translate('book.coverPref.toast.savedSummary'),
|
|
||||||
detail: this.t.translate('book.coverPref.toast.savedDetail', {scale: scale.toFixed(2)}),
|
|
||||||
life: 1500
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
this.messageService.add({
|
|
||||||
severity: 'error',
|
|
||||||
summary: this.t.translate('book.coverPref.toast.saveFailedSummary'),
|
|
||||||
detail: this.t.translate('book.coverPref.toast.saveFailedDetail'),
|
|
||||||
life: 3000
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private loadScaleFromStorage(): number {
|
|
||||||
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
|
||||||
if (saved !== null && !isNaN(saved)) {
|
|
||||||
return saved;
|
|
||||||
}
|
|
||||||
return 1.0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
import {describe, expect, it} from 'vitest';
|
|
||||||
|
|
||||||
import {DeferredRenderState} from './deferred-render-state';
|
|
||||||
|
|
||||||
describe('DeferredRenderState', () => {
|
|
||||||
it('clears the current value for reset runs', () => {
|
|
||||||
const state = new DeferredRenderState<number[]>();
|
|
||||||
|
|
||||||
const initialRequest = state.begin('reset');
|
|
||||||
state.commit(initialRequest, [1, 2, 3]);
|
|
||||||
|
|
||||||
expect(state.value()).toEqual([1, 2, 3]);
|
|
||||||
expect(state.hasValue()).toBe(true);
|
|
||||||
|
|
||||||
state.begin('reset');
|
|
||||||
|
|
||||||
expect(state.value()).toBeUndefined();
|
|
||||||
expect(state.hasValue()).toBe(false);
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps the current value visible during refresh runs', () => {
|
|
||||||
const state = new DeferredRenderState<number[]>();
|
|
||||||
|
|
||||||
const initialRequest = state.begin('reset');
|
|
||||||
state.commit(initialRequest, [1, 2, 3]);
|
|
||||||
|
|
||||||
const refreshRequest = state.begin('refresh');
|
|
||||||
|
|
||||||
expect(state.value()).toEqual([1, 2, 3]);
|
|
||||||
expect(state.isRefreshing()).toBe(true);
|
|
||||||
|
|
||||||
state.commit(refreshRequest, [4, 5]);
|
|
||||||
|
|
||||||
expect(state.value()).toEqual([4, 5]);
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ignores stale commits from older requests', () => {
|
|
||||||
const state = new DeferredRenderState<number[]>();
|
|
||||||
|
|
||||||
const initialRequest = state.begin('reset');
|
|
||||||
state.commit(initialRequest, [1]);
|
|
||||||
|
|
||||||
const staleRefresh = state.begin('refresh');
|
|
||||||
const latestRefresh = state.begin('refresh');
|
|
||||||
|
|
||||||
expect(state.commit(staleRefresh, [2])).toBe(false);
|
|
||||||
expect(state.value()).toEqual([1]);
|
|
||||||
expect(state.isRefreshing()).toBe(true);
|
|
||||||
|
|
||||||
expect(state.commit(latestRefresh, [3])).toBe(true);
|
|
||||||
expect(state.value()).toEqual([3]);
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ignores cancel with a stale request id', () => {
|
|
||||||
const state = new DeferredRenderState<number[]>();
|
|
||||||
|
|
||||||
const first = state.begin('reset');
|
|
||||||
state.commit(first, [1]);
|
|
||||||
|
|
||||||
const stale = state.begin('refresh');
|
|
||||||
const current = state.begin('refresh');
|
|
||||||
|
|
||||||
state.cancel(stale);
|
|
||||||
|
|
||||||
// Cancel was a no-op — isRefreshing still true from the current request
|
|
||||||
expect(state.isRefreshing()).toBe(true);
|
|
||||||
expect(state.value()).toEqual([1]);
|
|
||||||
|
|
||||||
state.commit(current, [2]);
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
expect(state.value()).toEqual([2]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('cancel during a reset leaves value undefined', () => {
|
|
||||||
const state = new DeferredRenderState<number[]>();
|
|
||||||
|
|
||||||
const request = state.begin('reset');
|
|
||||||
|
|
||||||
expect(state.value()).toBeUndefined();
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
|
|
||||||
state.cancel(request);
|
|
||||||
|
|
||||||
expect(state.value()).toBeUndefined();
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not set isRefreshing when no value exists yet', () => {
|
|
||||||
const state = new DeferredRenderState<number[]>();
|
|
||||||
|
|
||||||
const request = state.begin('refresh');
|
|
||||||
|
|
||||||
// No prior value, so nothing to "refresh" — isRefreshing stays false
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
expect(state.value()).toBeUndefined();
|
|
||||||
expect(state.hasValue()).toBe(false);
|
|
||||||
|
|
||||||
state.commit(request, [1]);
|
|
||||||
expect(state.value()).toEqual([1]);
|
|
||||||
expect(state.isRefreshing()).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import {computed, signal} from '@angular/core';
|
|
||||||
|
|
||||||
export type DeferredRenderMode = 'reset' | 'refresh';
|
|
||||||
|
|
||||||
export class DeferredRenderState<T> {
|
|
||||||
private readonly _value = signal<T | undefined>(undefined);
|
|
||||||
readonly value = this._value.asReadonly();
|
|
||||||
|
|
||||||
private readonly _isRefreshing = signal(false);
|
|
||||||
readonly isRefreshing = this._isRefreshing.asReadonly();
|
|
||||||
|
|
||||||
readonly hasValue = computed(() => this._value() !== undefined);
|
|
||||||
|
|
||||||
private activeRequestId = 0;
|
|
||||||
|
|
||||||
begin(mode: DeferredRenderMode): number {
|
|
||||||
this.activeRequestId += 1;
|
|
||||||
|
|
||||||
if (mode === 'reset') {
|
|
||||||
this._value.set(undefined);
|
|
||||||
this._isRefreshing.set(false);
|
|
||||||
} else {
|
|
||||||
this._isRefreshing.set(this._value() !== undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.activeRequestId;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Direct update without refresh animation used for in-place data swaps. */
|
|
||||||
update(value: T): void {
|
|
||||||
this._value.set(value);
|
|
||||||
this._isRefreshing.set(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
commit(requestId: number, value: T): boolean {
|
|
||||||
if (requestId !== this.activeRequestId) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._value.set(value);
|
|
||||||
this._isRefreshing.set(false);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
cancel(requestId: number): void {
|
|
||||||
if (requestId !== this.activeRequestId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._isRefreshing.set(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -279,11 +279,13 @@
|
|||||||
<i class="pi pi-objects-column"></i>
|
<i class="pi pi-objects-column"></i>
|
||||||
{{ t('booksInSeries') }}
|
{{ t('booksInSeries') }}
|
||||||
</h3>
|
</h3>
|
||||||
|
@let cardSize = currentCardSize;
|
||||||
<div class="series-items-grid" #Container
|
<div class="series-items-grid" #Container
|
||||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
[style.grid-template-columns]="'repeat(auto-fill, minmax(' + cardSize.width + 'px, 1fr))'">
|
||||||
@for (book of books; track book; let i = $index) {
|
@for (book of books; track book; let i = $index) {
|
||||||
<div class="grid-item"
|
<div class="grid-item"
|
||||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
[style.width.px]="cardSize.width"
|
||||||
|
[style.height.px]="cardSize.height">
|
||||||
<app-book-card
|
<app-book-card
|
||||||
[index]="i"
|
[index]="i"
|
||||||
[book]="book"
|
[book]="book"
|
||||||
|
|||||||
@@ -365,10 +365,6 @@ export class SeriesPageComponent implements AfterViewChecked {
|
|||||||
return this.coverScalePreferenceService.currentCardSize();
|
return this.coverScalePreferenceService.currentCardSize();
|
||||||
}
|
}
|
||||||
|
|
||||||
get gridColumnMinWidth(): string {
|
|
||||||
return this.coverScalePreferenceService.gridColumnMinWidth();
|
|
||||||
}
|
|
||||||
|
|
||||||
goToAuthorBooks(author: string): void {
|
goToAuthorBooks(author: string): void {
|
||||||
this.authorService.getAuthorByName(author).subscribe({
|
this.authorService.getAuthorByName(author).subscribe({
|
||||||
next: (authorDetails) => {
|
next: (authorDetails) => {
|
||||||
|
|||||||
+23
-25
@@ -45,24 +45,14 @@
|
|||||||
class="sort-dropdown">
|
class="sort-dropdown">
|
||||||
</p-select>
|
</p-select>
|
||||||
|
|
||||||
@if (!isMobile) {
|
@if (!isMobile()) {
|
||||||
<button class="display-settings-btn" (click)="displaySettingsPopover.toggle($event)">
|
<button class="display-settings-btn" (click)="displaySettingsPopover.toggle($event)">
|
||||||
<i class="pi pi-sliders-h"></i>
|
<i class="pi pi-sliders-h"></i>
|
||||||
</button>
|
</button>
|
||||||
<p-popover #displaySettingsPopover>
|
<p-popover #displaySettingsPopover>
|
||||||
<div class="display-settings-content">
|
<div class="display-settings-content">
|
||||||
<span class="display-settings-label">{{ t('cardSize') }}</span>
|
<span class="display-settings-label">{{ t('cardSize') }}</span>
|
||||||
<p-slider
|
<app-grid-density-buttons (densityChange)="adjustDesktopGridDensity($event)"/>
|
||||||
[ngModel]="seriesScaleService.scaleFactor()"
|
|
||||||
(ngModelChange)="seriesScaleService.setScale($event)"
|
|
||||||
[min]="0.7"
|
|
||||||
[max]="1.3"
|
|
||||||
[step]="0.01"
|
|
||||||
[style]="{ width: '100%' }">
|
|
||||||
</p-slider>
|
|
||||||
<div class="scale-value-display">
|
|
||||||
{{ seriesScaleService.scaleFactor().toFixed(2) }}x
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</p-popover>
|
</p-popover>
|
||||||
}
|
}
|
||||||
@@ -77,21 +67,29 @@
|
|||||||
<p>{{ t('noSeriesFound') }}</p>
|
<p>{{ t('noSeriesFound') }}</p>
|
||||||
</div>
|
</div>
|
||||||
} @else {
|
} @else {
|
||||||
<cdk-virtual-scroll-viewport [itemSize]="rowHeight" [minBufferPx]="600" [maxBufferPx]="1200" class="virtual-scroller">
|
<div #scrollElement class="virtual-scroller">
|
||||||
<div *cdkVirtualFor="let row of seriesRows(); let rowIdx = index" class="series-grid"
|
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
|
||||||
[ngStyle]="{'grid-template-columns': 'repeat(' + gridColumns() + ', 1fr)'}">
|
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
|
||||||
@for (series of row; track series.seriesName) {
|
@if (seriesList[virtualItem.index]; as series) {
|
||||||
<div class="virtual-scroller-item"
|
<div
|
||||||
[ngStyle]="{width: cardWidth + 'px', height: cardHeight + 'px'}"
|
class="virtual-cell"
|
||||||
[style.--card-scale]="seriesScaleService.scaleFactor()">
|
[style.width.px]="virtualGrid.itemWidth()"
|
||||||
<app-series-card
|
[style.height.px]="virtualItem.size"
|
||||||
[series]="series"
|
[style.transform]="virtualGrid.itemTransform(virtualItem)">
|
||||||
(cardClick)="navigateToSeries($event)">
|
<div class="virtual-scroller-item"
|
||||||
</app-series-card>
|
[style.width.px]="virtualGrid.itemWidth()"
|
||||||
</div>
|
[style.height.px]="virtualGrid.itemHeight()"
|
||||||
|
[style.--card-scale]="currentCardScale()">
|
||||||
|
<app-series-card
|
||||||
|
[series]="series"
|
||||||
|
(cardClick)="navigateToSeries($event)">
|
||||||
|
</app-series-card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</cdk-virtual-scroll-viewport>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-21
@@ -96,12 +96,6 @@
|
|||||||
color: #e2e8f0;
|
color: #e2e8f0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scale-value-display {
|
|
||||||
text-align: center;
|
|
||||||
font-size: 0.8rem;
|
|
||||||
color: #94a3b8;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Virtual scroller and grid
|
// Virtual scroller and grid
|
||||||
.virtual-scroller {
|
.virtual-scroller {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -132,21 +126,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.series-grid {
|
|
||||||
display: grid;
|
|
||||||
gap: 1.25rem;
|
|
||||||
place-items: start center;
|
|
||||||
width: 100%;
|
|
||||||
box-sizing: border-box;
|
|
||||||
padding-top: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.virtual-scroller-item {
|
|
||||||
position: relative;
|
|
||||||
overflow: visible;
|
|
||||||
transition: width 0.2s ease, height 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Empty state
|
// Empty state
|
||||||
.empty-state {
|
.empty-state {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|||||||
+66
-113
@@ -1,23 +1,22 @@
|
|||||||
import {Component, DestroyRef, HostListener, NgZone, computed, effect, inject, OnInit, signal, ViewChild} from '@angular/core';
|
import {Component, DestroyRef, ElementRef, HostListener, computed, inject, OnInit, signal, viewChild} from '@angular/core';
|
||||||
import {computeGridColumns} from '../../../../shared/util/viewport.util';
|
|
||||||
import {NgStyle} from '@angular/common';
|
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {InputText} from 'primeng/inputtext';
|
import {InputText} from 'primeng/inputtext';
|
||||||
import {Select} from 'primeng/select';
|
import {Select} from 'primeng/select';
|
||||||
import {Slider} from 'primeng/slider';
|
|
||||||
import {Popover} from 'primeng/popover';
|
import {Popover} from 'primeng/popover';
|
||||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||||
import {CdkFixedSizeVirtualScroll, CdkVirtualScrollViewport, CdkVirtualForOf} from '@angular/cdk/scrolling';
|
|
||||||
import {SeriesDataService} from '../../service/series-data.service';
|
import {SeriesDataService} from '../../service/series-data.service';
|
||||||
import {SeriesSummary} from '../../model/series.model';
|
import {SeriesSummary} from '../../model/series.model';
|
||||||
import {SeriesCardComponent} from '../series-card/series-card.component';
|
import {SeriesCardComponent} from '../series-card/series-card.component';
|
||||||
import {chunk} from '../../../../shared/util/array.util';
|
|
||||||
import {BookService} from '../../../book/service/book.service';
|
import {BookService} from '../../../book/service/book.service';
|
||||||
import {ReadStatus} from '../../../book/model/book.model';
|
import {ReadStatus} from '../../../book/model/book.model';
|
||||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||||
import {SeriesScalePreferenceService} from '../../service/series-scale-preference.service';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {Router} from '@angular/router';
|
import {createVirtualGrid, scaleForGridColumns} from '../../../../shared/util/virtual-grid.util';
|
||||||
|
import {RouteScrollPositionService} from '../../../../shared/service/route-scroll-position.service';
|
||||||
|
import {GridDensityButtonsComponent} from '../../../../shared/components/grid-density-buttons/grid-density-buttons.component';
|
||||||
|
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||||
|
import {ScalePreference} from '../../../../shared/util/scale-preference.util';
|
||||||
|
|
||||||
interface FilterOption {
|
interface FilterOption {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -35,18 +34,14 @@ interface SortOption {
|
|||||||
templateUrl: './series-browser.component.html',
|
templateUrl: './series-browser.component.html',
|
||||||
styleUrls: ['./series-browser.component.scss'],
|
styleUrls: ['./series-browser.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
NgStyle,
|
|
||||||
FormsModule,
|
FormsModule,
|
||||||
ProgressSpinner,
|
ProgressSpinner,
|
||||||
InputText,
|
InputText,
|
||||||
Select,
|
Select,
|
||||||
Slider,
|
|
||||||
Popover,
|
Popover,
|
||||||
TranslocoDirective,
|
TranslocoDirective,
|
||||||
|
GridDensityButtonsComponent,
|
||||||
SeriesCardComponent,
|
SeriesCardComponent,
|
||||||
CdkVirtualScrollViewport,
|
|
||||||
CdkFixedSizeVirtualScroll,
|
|
||||||
CdkVirtualForOf,
|
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
export class SeriesBrowserComponent implements OnInit {
|
export class SeriesBrowserComponent implements OnInit {
|
||||||
@@ -56,40 +51,19 @@ export class SeriesBrowserComponent implements OnInit {
|
|||||||
private static readonly MOBILE_BASE_WIDTH = 180;
|
private static readonly MOBILE_BASE_WIDTH = 180;
|
||||||
private static readonly MOBILE_BASE_HEIGHT = 250;
|
private static readonly MOBILE_BASE_HEIGHT = 250;
|
||||||
private static readonly GRID_GAP = 20;
|
private static readonly GRID_GAP = 20;
|
||||||
private static readonly ROW_TOP_PADDING = 16;
|
private static readonly SCALE_STORAGE_KEY = 'seriesScalePreference';
|
||||||
|
private static readonly MIN_SCALE = 0.7;
|
||||||
|
private static readonly MAX_SCALE = 1.3;
|
||||||
|
|
||||||
private seriesDataService = inject(SeriesDataService);
|
private seriesDataService = inject(SeriesDataService);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private pageTitle = inject(PageTitleService);
|
private pageTitle = inject(PageTitleService);
|
||||||
private t = inject(TranslocoService);
|
private t = inject(TranslocoService);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
|
private activatedRoute = inject(ActivatedRoute);
|
||||||
private destroyRef = inject(DestroyRef);
|
private destroyRef = inject(DestroyRef);
|
||||||
private zone = inject(NgZone);
|
private scrollService = inject(RouteScrollPositionService);
|
||||||
protected seriesScaleService = inject(SeriesScalePreferenceService);
|
private localStorageService = inject(LocalStorageService);
|
||||||
|
|
||||||
virtualScroller: CdkVirtualScrollViewport | undefined;
|
|
||||||
private pendingViewportRefresh: number | undefined;
|
|
||||||
|
|
||||||
@ViewChild(CdkVirtualScrollViewport)
|
|
||||||
set scrollViewport(vp: CdkVirtualScrollViewport | undefined) {
|
|
||||||
this.virtualScroller = vp;
|
|
||||||
this.viewportResizeObserver?.disconnect();
|
|
||||||
if (vp) {
|
|
||||||
const el = vp.elementRef.nativeElement as HTMLElement;
|
|
||||||
this.viewportWidth.set(this.measureViewportWidth(el));
|
|
||||||
this.viewportResizeObserver = new ResizeObserver(entries => {
|
|
||||||
this.zone.run(() => {
|
|
||||||
this.viewportWidth.set(this.measureViewportWidth(el, entries[0]));
|
|
||||||
this.scheduleViewportRefresh();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
this.viewportResizeObserver.observe(el);
|
|
||||||
this.scheduleViewportRefresh();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private readonly viewportWidth = signal(0);
|
|
||||||
private viewportResizeObserver: ResizeObserver | undefined;
|
|
||||||
|
|
||||||
readonly isBooksLoading = this.bookService.isBooksLoading;
|
readonly isBooksLoading = this.bookService.isBooksLoading;
|
||||||
private readonly searchTerm = signal('');
|
private readonly searchTerm = signal('');
|
||||||
@@ -110,53 +84,46 @@ export class SeriesBrowserComponent implements OnInit {
|
|||||||
return this.applySort(result, this.sortBy());
|
return this.applySort(result, this.sortBy());
|
||||||
});
|
});
|
||||||
|
|
||||||
screenWidth = window.innerWidth;
|
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
|
||||||
|
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute)) ?? 0;
|
||||||
|
private readonly scalePreference = new ScalePreference(this.localStorageService, {
|
||||||
|
storageKey: SeriesBrowserComponent.SCALE_STORAGE_KEY,
|
||||||
|
minScale: SeriesBrowserComponent.MIN_SCALE,
|
||||||
|
maxScale: SeriesBrowserComponent.MAX_SCALE,
|
||||||
|
});
|
||||||
|
private readonly scaleFactor = this.scalePreference.scaleFactor;
|
||||||
|
readonly screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
|
||||||
filterOptions: FilterOption[] = [];
|
filterOptions: FilterOption[] = [];
|
||||||
sortOptions: SortOption[] = [];
|
sortOptions: SortOption[] = [];
|
||||||
|
|
||||||
@HostListener('window:resize')
|
@HostListener('window:resize')
|
||||||
onResize(): void {
|
onResize(): void {
|
||||||
this.screenWidth = window.innerWidth;
|
this.screenWidth.set(window.innerWidth);
|
||||||
this.scheduleViewportRefresh();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get isMobile(): boolean {
|
readonly isMobile = computed(() => this.screenWidth() <= 767);
|
||||||
return this.screenWidth <= 767;
|
|
||||||
}
|
|
||||||
|
|
||||||
get cardWidth(): number {
|
private readonly baseCardWidth = computed(() => this.isMobile()
|
||||||
const base = this.isMobile
|
? SeriesBrowserComponent.MOBILE_BASE_WIDTH
|
||||||
? SeriesBrowserComponent.MOBILE_BASE_WIDTH
|
: SeriesBrowserComponent.BASE_WIDTH
|
||||||
: SeriesBrowserComponent.BASE_WIDTH;
|
);
|
||||||
return Math.round(base * this.seriesScaleService.scaleFactor());
|
private readonly cardAspectRatio = computed(() => {
|
||||||
}
|
const baseHeight = this.isMobile()
|
||||||
|
|
||||||
get cardHeight(): number {
|
|
||||||
const base = this.isMobile
|
|
||||||
? SeriesBrowserComponent.MOBILE_BASE_HEIGHT
|
? SeriesBrowserComponent.MOBILE_BASE_HEIGHT
|
||||||
: SeriesBrowserComponent.BASE_HEIGHT;
|
: SeriesBrowserComponent.BASE_HEIGHT;
|
||||||
return Math.round(base * this.seriesScaleService.scaleFactor());
|
return baseHeight / this.baseCardWidth();
|
||||||
}
|
|
||||||
|
|
||||||
get rowHeight(): number {
|
|
||||||
return this.cardHeight + SeriesBrowserComponent.ROW_TOP_PADDING;
|
|
||||||
}
|
|
||||||
|
|
||||||
readonly gridColumns = computed(() => {
|
|
||||||
return computeGridColumns(this.viewportWidth(), this.cardWidth || 230, SeriesBrowserComponent.GRID_GAP);
|
|
||||||
});
|
});
|
||||||
|
private readonly minCardWidth = computed(() => Math.round(this.baseCardWidth() * this.scaleFactor()));
|
||||||
readonly seriesRows = computed(() => {
|
readonly virtualGrid = createVirtualGrid({
|
||||||
return chunk(this.filteredSeries(), this.gridColumns());
|
items: this.filteredSeries,
|
||||||
});
|
scrollElement: this.scrollElement,
|
||||||
|
minItemWidth: this.minCardWidth,
|
||||||
private readonly refreshViewportEffect = effect(() => {
|
gap: SeriesBrowserComponent.GRID_GAP,
|
||||||
const hasRows = this.seriesRows().length > 0;
|
initialOffset: this.initialScrollOffset,
|
||||||
const rowHeight = this.rowHeight;
|
fillItemWidth: true,
|
||||||
if (hasRows && rowHeight > 0) {
|
estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()),
|
||||||
this.scheduleViewportRefresh();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
readonly currentCardScale = computed(() => this.virtualGrid.itemWidth() / this.baseCardWidth());
|
||||||
|
|
||||||
get searchValue(): string {
|
get searchValue(): string {
|
||||||
return this.searchTerm();
|
return this.searchTerm();
|
||||||
@@ -172,11 +139,10 @@ export class SeriesBrowserComponent implements OnInit {
|
|||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.pageTitle.setPageTitle(this.t.translate('seriesBrowser.pageTitle'));
|
this.pageTitle.setPageTitle(this.t.translate('seriesBrowser.pageTitle'));
|
||||||
this.destroyRef.onDestroy(() => {
|
this.scrollService.trackRoute({
|
||||||
this.viewportResizeObserver?.disconnect();
|
scrollElement: this.scrollElement,
|
||||||
if (this.pendingViewportRefresh !== undefined) {
|
route: this.activatedRoute,
|
||||||
window.cancelAnimationFrame(this.pendingViewportRefresh);
|
destroyRef: this.destroyRef,
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
this.filterOptions = [
|
this.filterOptions = [
|
||||||
@@ -197,8 +163,6 @@ export class SeriesBrowserComponent implements OnInit {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
onSearchChange(value: string): void {
|
onSearchChange(value: string): void {
|
||||||
this.searchTerm.set(value);
|
this.searchTerm.set(value);
|
||||||
}
|
}
|
||||||
@@ -211,41 +175,30 @@ export class SeriesBrowserComponent implements OnInit {
|
|||||||
this.sortBy.set(value);
|
this.sortBy.set(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
navigateToSeries(series: SeriesSummary): void {
|
adjustDesktopGridDensity(direction: 'smaller' | 'larger'): void {
|
||||||
this.router.navigate(['/series', series.seriesName]);
|
const currentColumns = this.virtualGrid.gridColumns();
|
||||||
}
|
const columns = Math.max(1, direction === 'smaller'
|
||||||
|
? currentColumns + 1
|
||||||
private measureViewportWidth(el: HTMLElement, entry?: ResizeObserverEntry): number {
|
: currentColumns - 1);
|
||||||
const style = getComputedStyle(el);
|
const viewportWidth = this.virtualGrid.viewportWidth() || this.screenWidth();
|
||||||
const horizontalPadding = this.parsePixelValue(style.paddingLeft) + this.parsePixelValue(style.paddingRight);
|
this.virtualGrid.updatePreservingScrollPosition(() => {
|
||||||
const observedWidth = entry?.contentRect.width ?? el.clientWidth - horizontalPadding;
|
this.setScale(scaleForGridColumns(
|
||||||
return Math.max(0, Math.floor(observedWidth));
|
viewportWidth,
|
||||||
}
|
SeriesBrowserComponent.GRID_GAP,
|
||||||
|
columns,
|
||||||
private parsePixelValue(value: string): number {
|
this.baseCardWidth(),
|
||||||
const parsed = Number.parseFloat(value);
|
SeriesBrowserComponent.MIN_SCALE,
|
||||||
return Number.isFinite(parsed) ? parsed : 0;
|
SeriesBrowserComponent.MAX_SCALE
|
||||||
}
|
));
|
||||||
|
|
||||||
private scheduleViewportRefresh(): void {
|
|
||||||
if (this.pendingViewportRefresh !== undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.pendingViewportRefresh = window.requestAnimationFrame(() => {
|
|
||||||
this.pendingViewportRefresh = undefined;
|
|
||||||
this.refreshViewport();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private refreshViewport(): void {
|
private setScale(scale: number): void {
|
||||||
if (!this.virtualScroller) {
|
this.scalePreference.setScale(scale);
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const el = this.virtualScroller.elementRef.nativeElement as HTMLElement;
|
navigateToSeries(series: SeriesSummary): void {
|
||||||
this.viewportWidth.set(this.measureViewportWidth(el));
|
this.router.navigate(['/series', series.seriesName]);
|
||||||
this.virtualScroller.checkViewportSize();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private applyStatusFilter(series: SeriesSummary[], filterValue: string): SeriesSummary[] {
|
private applyStatusFilter(series: SeriesSummary[], filterValue: string): SeriesSummary[] {
|
||||||
|
|||||||
-63
@@ -1,63 +0,0 @@
|
|||||||
import {TestBed} from '@angular/core/testing';
|
|
||||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
|
||||||
|
|
||||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
|
||||||
import {SeriesScalePreferenceService} from './series-scale-preference.service';
|
|
||||||
|
|
||||||
describe('SeriesScalePreferenceService', () => {
|
|
||||||
const localStorageService = {
|
|
||||||
get: vi.fn(),
|
|
||||||
set: vi.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
localStorageService.get.mockReset();
|
|
||||||
localStorageService.set.mockReset();
|
|
||||||
localStorageService.get.mockReturnValue(0.75);
|
|
||||||
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
providers: [
|
|
||||||
SeriesScalePreferenceService,
|
|
||||||
{provide: LocalStorageService, useValue: localStorageService},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.useRealTimers();
|
|
||||||
TestBed.resetTestingModule();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('loads the persisted scale and does not persist unchanged values', () => {
|
|
||||||
const service = TestBed.inject(SeriesScalePreferenceService);
|
|
||||||
|
|
||||||
expect(service.scaleFactor()).toBe(0.75);
|
|
||||||
|
|
||||||
service.setScale(0.75);
|
|
||||||
vi.runAllTimers();
|
|
||||||
|
|
||||||
expect(localStorageService.set).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('debounces and persists the most recent scale value', () => {
|
|
||||||
const service = TestBed.inject(SeriesScalePreferenceService);
|
|
||||||
|
|
||||||
service.setScale(0.9);
|
|
||||||
service.setScale(1.1);
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(1000);
|
|
||||||
|
|
||||||
expect(localStorageService.set).toHaveBeenCalledOnce();
|
|
||||||
expect(localStorageService.set).toHaveBeenCalledWith('seriesScalePreference', 1.1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to the default scale when storage contains an invalid value', () => {
|
|
||||||
localStorageService.get.mockReturnValue(undefined);
|
|
||||||
|
|
||||||
const service = TestBed.inject(SeriesScalePreferenceService);
|
|
||||||
|
|
||||||
expect(service.scaleFactor()).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
import {inject, Injectable, signal} from '@angular/core';
|
|
||||||
import {LocalStorageService} from '../../../shared/service/local-storage.service';
|
|
||||||
|
|
||||||
@Injectable({
|
|
||||||
providedIn: 'root'
|
|
||||||
})
|
|
||||||
export class SeriesScalePreferenceService {
|
|
||||||
|
|
||||||
private readonly DEBOUNCE_MS = 1000;
|
|
||||||
private readonly STORAGE_KEY = 'seriesScalePreference';
|
|
||||||
|
|
||||||
private readonly localStorageService = inject(LocalStorageService);
|
|
||||||
|
|
||||||
private readonly _scaleFactor = signal(1.0);
|
|
||||||
readonly scaleFactor = this._scaleFactor.asReadonly();
|
|
||||||
|
|
||||||
private saveTimeout: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
private lastPersistedScale = 1.0;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
const initialScale = this.loadScaleFromStorage();
|
|
||||||
this._scaleFactor.set(initialScale);
|
|
||||||
this.lastPersistedScale = initialScale;
|
|
||||||
}
|
|
||||||
|
|
||||||
setScale(scale: number): void {
|
|
||||||
this._scaleFactor.set(scale);
|
|
||||||
if (scale === this.lastPersistedScale) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.scheduleSave(scale);
|
|
||||||
}
|
|
||||||
|
|
||||||
private scheduleSave(scale: number): void {
|
|
||||||
if (this.saveTimeout) {
|
|
||||||
clearTimeout(this.saveTimeout);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.saveTimeout = setTimeout(() => {
|
|
||||||
this.saveScalePreference(scale);
|
|
||||||
}, this.DEBOUNCE_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private saveScalePreference(scale: number): void {
|
|
||||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
|
||||||
this.lastPersistedScale = scale;
|
|
||||||
}
|
|
||||||
|
|
||||||
private loadScaleFromStorage(): number {
|
|
||||||
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
|
||||||
if (saved !== null && !isNaN(saved)) {
|
|
||||||
return saved;
|
|
||||||
}
|
|
||||||
return 1.0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+17
@@ -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>
|
||||||
+14
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "",
|
"dismiss": "",
|
||||||
"discard": "",
|
"discard": "",
|
||||||
"review": "",
|
"review": "",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Verwerfen",
|
"dismiss": "Verwerfen",
|
||||||
"discard": "Verwerfen",
|
"discard": "Verwerfen",
|
||||||
"review": "Überprüfen",
|
"review": "Überprüfen",
|
||||||
"libraryPathInaccessible": "Der Pfad zur Bibliothek ist nicht zugreifbar"
|
"libraryPathInaccessible": "Der Pfad zur Bibliothek ist nicht zugreifbar",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,9 @@
|
|||||||
"discard": "Discard",
|
"discard": "Discard",
|
||||||
"review": "Review",
|
"review": "Review",
|
||||||
"libraryPathInaccessible": "Library path inaccessible",
|
"libraryPathInaccessible": "Library path inaccessible",
|
||||||
|
"decreaseCardSize": "Decrease card size",
|
||||||
|
"increaseCardSize": "Increase card size",
|
||||||
|
"cardSizeControls": "Card size controls",
|
||||||
"on": "On",
|
"on": "On",
|
||||||
"off": "Off"
|
"off": "Off"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Descartar",
|
"dismiss": "Descartar",
|
||||||
"discard": "Descartar",
|
"discard": "Descartar",
|
||||||
"review": "Revisar",
|
"review": "Revisar",
|
||||||
"libraryPathInaccessible": "Ruta de biblioteca inaccesible"
|
"libraryPathInaccessible": "Ruta de biblioteca inaccesible",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Ignorer",
|
"dismiss": "Ignorer",
|
||||||
"discard": "Abandonner",
|
"discard": "Abandonner",
|
||||||
"review": "Vérifier",
|
"review": "Vérifier",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Odbaci",
|
"dismiss": "Odbaci",
|
||||||
"discard": "Odbaci",
|
"discard": "Odbaci",
|
||||||
"review": "Pregledaj",
|
"review": "Pregledaj",
|
||||||
"libraryPathInaccessible": "Put do zbirke nije dostupan"
|
"libraryPathInaccessible": "Put do zbirke nije dostupan",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Ignorálás",
|
"dismiss": "Ignorálás",
|
||||||
"discard": "Elvetés",
|
"discard": "Elvetés",
|
||||||
"review": "Felülvizsgálat",
|
"review": "Felülvizsgálat",
|
||||||
"libraryPathInaccessible": "Könyvtár elérési útvonal elérhetetlen"
|
"libraryPathInaccessible": "Könyvtár elérési útvonal elérhetetlen",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Abaikan",
|
"dismiss": "Abaikan",
|
||||||
"discard": "Buang",
|
"discard": "Buang",
|
||||||
"review": "Tinjau",
|
"review": "Tinjau",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Ignora",
|
"dismiss": "Ignora",
|
||||||
"discard": "Scarta",
|
"discard": "Scarta",
|
||||||
"review": "Rivedi",
|
"review": "Rivedi",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "閉じる",
|
"dismiss": "閉じる",
|
||||||
"discard": "破棄",
|
"discard": "破棄",
|
||||||
"review": "確認",
|
"review": "確認",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Sluiten",
|
"dismiss": "Sluiten",
|
||||||
"discard": "Verwerpen",
|
"discard": "Verwerpen",
|
||||||
"review": "Beoordelen",
|
"review": "Beoordelen",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Odrzuć",
|
"dismiss": "Odrzuć",
|
||||||
"discard": "Odrzuć",
|
"discard": "Odrzuć",
|
||||||
"review": "Przegląd",
|
"review": "Przegląd",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Dispensar",
|
"dismiss": "Dispensar",
|
||||||
"discard": "Descartar",
|
"discard": "Descartar",
|
||||||
"review": "Revisar",
|
"review": "Revisar",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Отклонить",
|
"dismiss": "Отклонить",
|
||||||
"discard": "Отменить изменения",
|
"discard": "Отменить изменения",
|
||||||
"review": "Просмотреть",
|
"review": "Просмотреть",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "",
|
"dismiss": "",
|
||||||
"discard": "",
|
"discard": "",
|
||||||
"review": "",
|
"review": "",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Prezri",
|
"dismiss": "Prezri",
|
||||||
"discard": "Zavrzi",
|
"discard": "Zavrzi",
|
||||||
"review": "Preglej",
|
"review": "Preglej",
|
||||||
"libraryPathInaccessible": "Pot do knjižnice ni dostopna"
|
"libraryPathInaccessible": "Pot do knjižnice ni dostopna",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Stäng",
|
"dismiss": "Stäng",
|
||||||
"discard": "Förkasta",
|
"discard": "Förkasta",
|
||||||
"review": "Granska",
|
"review": "Granska",
|
||||||
"libraryPathInaccessible": "Bibliotekssökvägen är otillgänglig"
|
"libraryPathInaccessible": "Bibliotekssökvägen är otillgänglig",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "Відхилити",
|
"dismiss": "Відхилити",
|
||||||
"discard": "Відкинути",
|
"discard": "Відкинути",
|
||||||
"review": "Перевірити",
|
"review": "Перевірити",
|
||||||
"libraryPathInaccessible": "Шлях до бібліотеки недоступний"
|
"libraryPathInaccessible": "Шлях до бібліотеки недоступний",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,5 +22,8 @@
|
|||||||
"dismiss": "忽略",
|
"dismiss": "忽略",
|
||||||
"discard": "丢弃",
|
"discard": "丢弃",
|
||||||
"review": "审查",
|
"review": "审查",
|
||||||
"libraryPathInaccessible": ""
|
"libraryPathInaccessible": "",
|
||||||
|
"decreaseCardSize": "",
|
||||||
|
"increaseCardSize": "",
|
||||||
|
"cardSizeControls": ""
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,6 +67,62 @@ html {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.virtual-scroller {
|
||||||
|
.virtual-content {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.virtual-cell {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.virtual-cell > app-author-card,
|
||||||
|
.virtual-cell > app-book-card,
|
||||||
|
.virtual-cell > app-series-card {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.virtual-scroller-item {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.browser-grid-options {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.browser-grid-option-btn {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border: 1px solid var(--p-content-border-color);
|
||||||
|
border-radius: 6px;
|
||||||
|
background-color: var(--card-background);
|
||||||
|
color: var(--text-color);
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
border-color: var(--primary-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.active {
|
||||||
|
background-color: var(--primary-color);
|
||||||
|
border-color: var(--primary-color);
|
||||||
|
color: var(--primary-color-text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.p-toast {
|
.p-toast {
|
||||||
top: 4rem !important;
|
top: 4rem !important;
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-13
@@ -487,18 +487,6 @@ __metadata:
|
|||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
"@angular/cdk-experimental@npm:^21.2.8":
|
|
||||||
version: 21.2.8
|
|
||||||
resolution: "@angular/cdk-experimental@npm:21.2.8"
|
|
||||||
dependencies:
|
|
||||||
tslib: "npm:^2.3.0"
|
|
||||||
peerDependencies:
|
|
||||||
"@angular/cdk": 21.2.8
|
|
||||||
"@angular/core": ^21.0.0 || ^22.0.0
|
|
||||||
checksum: 10c0/7db17924936b179d7ab5dc43b1cfc69879880d3d255c6091b4a54f2248f1c30d57fdc8d7b1ce982182c8f856f8c85c574cbf72d36125f6c161ae2342e1c24359
|
|
||||||
languageName: node
|
|
||||||
linkType: hard
|
|
||||||
|
|
||||||
"@angular/cdk@npm:^21.2.8":
|
"@angular/cdk@npm:^21.2.8":
|
||||||
version: 21.2.8
|
version: 21.2.8
|
||||||
resolution: "@angular/cdk@npm:21.2.8"
|
resolution: "@angular/cdk@npm:21.2.8"
|
||||||
@@ -3870,6 +3858,18 @@ __metadata:
|
|||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
|
"@tanstack/angular-virtual@npm:^4.0.13":
|
||||||
|
version: 4.0.13
|
||||||
|
resolution: "@tanstack/angular-virtual@npm:4.0.13"
|
||||||
|
dependencies:
|
||||||
|
"@tanstack/virtual-core": "npm:3.14.0"
|
||||||
|
tslib: "npm:^2.8.1"
|
||||||
|
peerDependencies:
|
||||||
|
"@angular/core": ">=18.1.0"
|
||||||
|
checksum: 10c0/da9b7bf676d3f2553c09b4be3c36716525d9ce90168b0380f4eb0217ee3fd5400c253936f1d5e8293503da04b221f25b5274fbaebb125b20fba481db5a425f9f
|
||||||
|
languageName: node
|
||||||
|
linkType: hard
|
||||||
|
|
||||||
"@tanstack/query-core@npm:5.100.1":
|
"@tanstack/query-core@npm:5.100.1":
|
||||||
version: 5.100.1
|
version: 5.100.1
|
||||||
resolution: "@tanstack/query-core@npm:5.100.1"
|
resolution: "@tanstack/query-core@npm:5.100.1"
|
||||||
@@ -3884,6 +3884,13 @@ __metadata:
|
|||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
|
"@tanstack/virtual-core@npm:3.14.0":
|
||||||
|
version: 3.14.0
|
||||||
|
resolution: "@tanstack/virtual-core@npm:3.14.0"
|
||||||
|
checksum: 10c0/9e07e7f74f5e02dfc47b358f7b5089e680d8b14b9c5b90e9497be6f57c76ca98d185fbe5008795b89919346bfc3676ebe1c61b34980eefe6674c88ec6ff4b136
|
||||||
|
languageName: node
|
||||||
|
linkType: hard
|
||||||
|
|
||||||
"@testing-library/angular@npm:^19.2.1":
|
"@testing-library/angular@npm:^19.2.1":
|
||||||
version: 19.2.1
|
version: 19.2.1
|
||||||
resolution: "@testing-library/angular@npm:19.2.1"
|
resolution: "@testing-library/angular@npm:19.2.1"
|
||||||
@@ -6268,7 +6275,6 @@ __metadata:
|
|||||||
"@angular/animations": "npm:^21.2.10"
|
"@angular/animations": "npm:^21.2.10"
|
||||||
"@angular/build": "npm:^21.2.8"
|
"@angular/build": "npm:^21.2.8"
|
||||||
"@angular/cdk": "npm:^21.2.8"
|
"@angular/cdk": "npm:^21.2.8"
|
||||||
"@angular/cdk-experimental": "npm:^21.2.8"
|
|
||||||
"@angular/cli": "npm:^21.2.8"
|
"@angular/cli": "npm:^21.2.8"
|
||||||
"@angular/common": "npm:^21.2.10"
|
"@angular/common": "npm:^21.2.10"
|
||||||
"@angular/compiler": "npm:^21.2.10"
|
"@angular/compiler": "npm:^21.2.10"
|
||||||
@@ -6288,6 +6294,7 @@ __metadata:
|
|||||||
"@stomp/rx-stomp": "npm:^2.3.0"
|
"@stomp/rx-stomp": "npm:^2.3.0"
|
||||||
"@stomp/stompjs": "npm:^7.3.0"
|
"@stomp/stompjs": "npm:^7.3.0"
|
||||||
"@tanstack/angular-query-experimental": "npm:5.100.1"
|
"@tanstack/angular-query-experimental": "npm:5.100.1"
|
||||||
|
"@tanstack/angular-virtual": "npm:^4.0.13"
|
||||||
"@testing-library/angular": "npm:^19.2.1"
|
"@testing-library/angular": "npm:^19.2.1"
|
||||||
"@testing-library/dom": "npm:^10.4.1"
|
"@testing-library/dom": "npm:^10.4.1"
|
||||||
"@testing-library/jest-dom": "npm:^6.9.1"
|
"@testing-library/jest-dom": "npm:^6.9.1"
|
||||||
|
|||||||
Reference in New Issue
Block a user