diff --git a/frontend/package.json b/frontend/package.json index 7abde1db0..6c12cc27e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -24,7 +24,6 @@ "dependencies": { "@angular/animations": "^21.2.10", "@angular/cdk": "^21.2.8", - "@angular/cdk-experimental": "^21.2.8", "@angular/common": "^21.2.10", "@angular/compiler": "^21.2.10", "@angular/core": "^21.2.10", @@ -40,6 +39,7 @@ "@stomp/rx-stomp": "^2.3.0", "@stomp/stompjs": "^7.3.0", "@tanstack/angular-query-experimental": "5.100.1", + "@tanstack/angular-virtual": "^4.0.13", "chart.js": "^4.5.1", "chartjs-chart-matrix": "^3.0.0", "chartjs-plugin-datalabels": "^2.2.0", diff --git a/frontend/src/app/core/custom-reuse-strategy.spec.ts b/frontend/src/app/core/custom-reuse-strategy.spec.ts index 945308213..1073db8b5 100644 --- a/frontend/src/app/core/custom-reuse-strategy.spec.ts +++ b/frontend/src/app/core/custom-reuse-strategy.spec.ts @@ -1,193 +1,30 @@ -import {Injector, runInInjectionContext} from '@angular/core'; -import {ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router'; -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {ActivatedRouteSnapshot, Route} from '@angular/router'; +import {describe, expect, it} from 'vitest'; -import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service'; -import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service'; import {CustomReuseStrategy} from './custom-reuse-strategy'; -function createRoute(path: string, params: Record = {}): ActivatedRouteSnapshot { +function createRoute(routeConfig: Route, params: Record = {}): ActivatedRouteSnapshot { return { - routeConfig: {path}, + routeConfig, params } as ActivatedRouteSnapshot; } describe('CustomReuseStrategy', () => { - const handle = {componentRef: {destroy: vi.fn()} as never} as DetachedRouteHandle; - - let strategy: CustomReuseStrategy; - let scrollService: BookBrowserScrollService; - let selectionService: BookSelectionService; - - beforeEach(() => { - vi.restoreAllMocks(); - - scrollService = new BookBrowserScrollService(); - selectionService = new BookSelectionService(); - const injector = Injector.create({ - providers: [ - {provide: BookBrowserScrollService, useValue: scrollService}, - {provide: BookSelectionService, useValue: selectionService}, - ] - }); - strategy = runInInjectionContext(injector, () => new CustomReuseStrategy()); - }); - - afterEach(() => { - vi.useRealTimers(); - document.body.innerHTML = ''; - }); - - it('stores and reattaches book browser routes with their saved scroll position', async () => { - vi.useFakeTimers(); - const route = createRoute('all-books', {libraryId: '42'}); - const scrollElement = document.createElement('div'); - scrollElement.className = 'virtual-scroller'; - const querySelectorSpy = vi.spyOn(document, 'querySelector').mockReturnValue(scrollElement); - const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); - - scrollService.savePosition('all-books:42', 321); - strategy.store(route, handle); - - expect(strategy.shouldDetach(route)).toBe(true); - expect(strategy.shouldAttach(route)).toBe(true); - expect(deselectSpy).toHaveBeenCalledTimes(1); - - const restored = strategy.retrieve(route); - await vi.runAllTimersAsync(); - - expect(restored).toBe(handle); - expect(querySelectorSpy).toHaveBeenCalledWith('.virtual-scroller'); - expect(scrollElement.scrollTop).toBe(321); - }); - - it('ignores non-book routes when storing or attaching', () => { - const route = createRoute('login'); - const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); - - strategy.store(route, handle); - - expect(strategy.shouldDetach(route)).toBe(false); - expect(strategy.shouldAttach(route)).toBe(false); - expect(strategy.retrieve(route)).toBeNull(); - expect(deselectSpy).not.toHaveBeenCalled(); - }); - - it('ignores null handles for book browser routes', () => { - const route = createRoute('series', {seriesId: '77'}); - const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); - - strategy.store(route, null); - - expect(strategy.shouldDetach(route)).toBe(true); - expect(strategy.shouldAttach(route)).toBe(false); - expect(strategy.retrieve(route)).toBeNull(); - expect(deselectSpy).not.toHaveBeenCalled(); - }); - - it('returns a stored handle without touching the DOM when no scroll position was saved', () => { - const route = createRoute('authors'); - const querySelectorSpy = vi.spyOn(document, 'querySelector'); - const deselectSpy = vi.spyOn(selectionService, 'deselectAll'); - - strategy.store(route, handle); - - expect(deselectSpy).toHaveBeenCalledOnce(); - expect(strategy.shouldAttach(route)).toBe(true); - expect(strategy.retrieve(route)).toBe(handle); - expect(querySelectorSpy).not.toHaveBeenCalled(); - }); + const strategy = new CustomReuseStrategy(); it('reuses routes only when the route config and params both match', () => { const routeConfig = {path: 'series'}; - const current = { - routeConfig, - params: {seriesId: '12'} - } as unknown as ActivatedRouteSnapshot; - const same = { - routeConfig, - params: {seriesId: '12'} - } as unknown as ActivatedRouteSnapshot; - const differentParams = { - routeConfig, - params: {seriesId: '99'} - } as unknown as ActivatedRouteSnapshot; - const differentConfig = { - routeConfig: {path: 'authors'}, - params: {seriesId: '12'} - } as unknown as ActivatedRouteSnapshot; + const current = createRoute(routeConfig, {seriesId: '12'}); + const same = createRoute(routeConfig, {seriesId: '12'}); + const sameDifferentOrder = createRoute(routeConfig, {tab: 'books', seriesId: '12'}); + const currentWithTab = createRoute(routeConfig, {seriesId: '12', tab: 'books'}); + const differentParams = createRoute(routeConfig, {seriesId: '99'}); + const differentConfig = createRoute({path: 'authors'}, {seriesId: '12'}); expect(strategy.shouldReuseRoute(same, current)).toBe(true); + expect(strategy.shouldReuseRoute(sameDifferentOrder, currentWithTab)).toBe(true); expect(strategy.shouldReuseRoute(differentParams, current)).toBe(false); expect(strategy.shouldReuseRoute(differentConfig, current)).toBe(false); }); - - it('evicts the oldest route when storing more than MAX_STORED_ROUTES (3)', () => { - const route1 = createRoute('library/:libraryId/books', {libraryId: '1'}); - const route2 = createRoute('library/:libraryId/books', {libraryId: '2'}); - const route3 = createRoute('library/:libraryId/books', {libraryId: '3'}); - const route4 = createRoute('library/:libraryId/books', {libraryId: '4'}); - - const handle1 = {componentRef: {id: 1, destroy: vi.fn()} as never} as DetachedRouteHandle; - const handle2 = {componentRef: {id: 2, destroy: vi.fn()} as never} as DetachedRouteHandle; - const handle3 = {componentRef: {id: 3, destroy: vi.fn()} as never} as DetachedRouteHandle; - const handle4 = {componentRef: {id: 4, destroy: vi.fn()} as never} as DetachedRouteHandle; - - strategy.store(route1, handle1); - strategy.store(route2, handle2); - strategy.store(route3, handle3); - - expect(strategy.shouldAttach(route1)).toBe(true); - expect(strategy.shouldAttach(route2)).toBe(true); - expect(strategy.shouldAttach(route3)).toBe(true); - - strategy.store(route4, handle4); - - expect(strategy.shouldAttach(route1)).toBe(false); - expect(strategy.shouldAttach(route2)).toBe(true); - expect(strategy.shouldAttach(route3)).toBe(true); - expect(strategy.shouldAttach(route4)).toBe(true); - }); - - it('clears scroll positions when evicting old routes', () => { - const clearSpy = vi.spyOn(scrollService, 'clearPosition'); - - const route1 = createRoute('library/:libraryId/books', {libraryId: '10'}); - const route2 = createRoute('library/:libraryId/books', {libraryId: '20'}); - const route3 = createRoute('library/:libraryId/books', {libraryId: '30'}); - const route4 = createRoute('library/:libraryId/books', {libraryId: '40'}); - - scrollService.savePosition('library/:libraryId/books:10', 100); - - strategy.store(route1, handle); - strategy.store(route2, handle); - strategy.store(route3, handle); - - expect(clearSpy).not.toHaveBeenCalled(); - - strategy.store(route4, handle); - - expect(clearSpy).toHaveBeenCalledWith('library/:libraryId/books:10'); - }); - - it('re-storing an existing route refreshes its LRU position', () => { - const route1 = createRoute('library/:libraryId/books', {libraryId: '1'}); - const route2 = createRoute('library/:libraryId/books', {libraryId: '2'}); - const route3 = createRoute('library/:libraryId/books', {libraryId: '3'}); - const route4 = createRoute('library/:libraryId/books', {libraryId: '4'}); - - strategy.store(route1, handle); - strategy.store(route2, handle); - strategy.store(route3, handle); - - strategy.store(route1, handle); - - strategy.store(route4, handle); - - expect(strategy.shouldAttach(route1)).toBe(true); - expect(strategy.shouldAttach(route2)).toBe(false); - expect(strategy.shouldAttach(route3)).toBe(true); - expect(strategy.shouldAttach(route4)).toBe(true); - }); }); diff --git a/frontend/src/app/core/custom-reuse-strategy.ts b/frontend/src/app/core/custom-reuse-strategy.ts index e9625417a..cec0308c7 100644 --- a/frontend/src/app/core/custom-reuse-strategy.ts +++ b/frontend/src/app/core/custom-reuse-strategy.ts @@ -1,112 +1,17 @@ -import {inject, Injectable} from '@angular/core'; -import {ActivatedRouteSnapshot, DetachedRouteHandle, destroyDetachedRouteHandle, RouteReuseStrategy} from '@angular/router'; -import {BookBrowserScrollService} from '../features/book/components/book-browser/book-browser-scroll.service'; -import {BookSelectionService} from '../features/book/components/book-browser/book-selection.service'; +import {Injectable} from '@angular/core'; +import {ActivatedRouteSnapshot, BaseRouteReuseStrategy, Params} from '@angular/router'; -/** - * Maximum number of detached BookBrowser routes kept in memory. - * Each cached route retains its full component tree (book cards, images, - * event listeners, virtual-scroller instance) so an unbounded cache leads - * to severe memory growth when the user switches between libraries. - * - * 3 slots is enough for productive back-navigation while keeping memory - * usage under control. - */ -const MAX_STORED_ROUTES = 3; +function paramsMatch(a: Params, b: Params): boolean { + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + return aKeys.length === bKeys.length && aKeys.every(key => a[key] === b[key]); +} @Injectable({ providedIn: 'root', }) -export class CustomReuseStrategy implements RouteReuseStrategy { - private storedRoutes = new Map(); - /** Insertion-order queue so we can evict the oldest entry (LRU). */ - private insertionOrder: string[] = []; - private scrollService = inject(BookBrowserScrollService); - private bookSelectionService = inject(BookSelectionService); - - private readonly BOOK_BROWSER_PATHS = [ - 'all-books', - 'unshelved-books', - 'library/:libraryId/books', - 'shelf/:shelfId/books', - 'magic-shelf/:magicShelfId/books', - 'authors', - 'series' - ]; - - private readonly BOOK_DETAILS_PATH = 'book/:bookId'; - - private getRouteKey(route: ActivatedRouteSnapshot): string { - const path = route.routeConfig?.path || ''; - return this.scrollService.createKey(path, route.params); - } - - private isBookBrowserRoute(route: ActivatedRouteSnapshot): boolean { - const path = route.routeConfig?.path; - return this.BOOK_BROWSER_PATHS.includes(path || ''); - } - - shouldDetach(route: ActivatedRouteSnapshot): boolean { - return this.isBookBrowserRoute(route); - } - - store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void { - if (handle && this.isBookBrowserRoute(route)) { - const key = this.getRouteKey(route); - - // If the key already exists, remove it from insertion order so it - // can be re-appended at the end (most-recently-used). - const existingIdx = this.insertionOrder.indexOf(key); - if (existingIdx !== -1) { - this.insertionOrder.splice(existingIdx, 1); - } - - this.storedRoutes.set(key, handle); - this.insertionOrder.push(key); - this.bookSelectionService.deselectAll(); - - // Evict oldest routes when we exceed the budget. - while (this.insertionOrder.length > MAX_STORED_ROUTES) { - const evictKey = this.insertionOrder.shift()!; - const evictedHandle = this.storedRoutes.get(evictKey); - this.storedRoutes.delete(evictKey); - this.scrollService.clearPosition(evictKey); - if (evictedHandle) { - destroyDetachedRouteHandle(evictedHandle); - } - } - } - } - - shouldAttach(route: ActivatedRouteSnapshot): boolean { - if (!this.isBookBrowserRoute(route)) { - return false; - } - const key = this.getRouteKey(route); - return this.storedRoutes.has(key); - } - - retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null { - const key = this.getRouteKey(route); - const handle = this.storedRoutes.get(key) || null; - - if (handle) { - const savedPosition = this.scrollService.getPosition(key); - if (savedPosition !== undefined) { - setTimeout(() => { - const scrollElement = document.querySelector('.virtual-scroller'); - if (scrollElement) { - (scrollElement as HTMLElement).scrollTop = savedPosition; - } - }, 0); - } - } - - return handle; - } - - shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { - return future.routeConfig === curr.routeConfig && - JSON.stringify(future.params) === JSON.stringify(curr.params); +export class CustomReuseStrategy extends BaseRouteReuseStrategy { + override shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { + return future.routeConfig === curr.routeConfig && paramsMatch(future.params, curr.params); } } diff --git a/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.html b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.html index e31944b01..cfd77b9f3 100644 --- a/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.html +++ b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.html @@ -54,17 +54,7 @@
{{ t('cardSize') }} - - -
- {{ authorScaleService.scaleFactor().toFixed(2) }}x -
+
} @@ -193,36 +183,35 @@

{{ t('noAuthorsFound') }}

} @else { - -
- @for (author of row; track author.id; let colIdx = $index) { -
- - -
+
+
+ @for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) { + @if (authorList[virtualItem.index]; as author) { +
+ + +
+ } }
- +
} } diff --git a/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.scss b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.scss index 1d9aa776b..82f1e2710 100644 --- a/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.scss +++ b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.scss @@ -107,12 +107,6 @@ color: #e2e8f0; } -.scale-value-display { - text-align: center; - font-size: 0.8rem; - color: #94a3b8; -} - .filter-popover-content { display: flex; 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 { display: flex; flex-direction: column; diff --git a/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.ts b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.ts index 5c23a2852..643405ea5 100644 --- a/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.ts +++ b/frontend/src/app/features/author-browser/components/author-browser/author-browser.component.ts @@ -1,33 +1,28 @@ -import {Component, computed, DestroyRef, effect, HostListener, inject, OnInit, signal, ViewChild} from '@angular/core'; -import {computeGridColumns} from '../../../../shared/util/viewport.util'; -import {NgStyle} from '@angular/common'; +import {Component, computed, DestroyRef, effect, ElementRef, HostListener, inject, OnInit, signal, viewChild} from '@angular/core'; import {FormsModule} from '@angular/forms'; -import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; -import {filter} from 'rxjs/operators'; import {ProgressSpinner} from 'primeng/progressspinner'; import {InputText} from 'primeng/inputtext'; import {Select} from 'primeng/select'; -import {Slider} from 'primeng/slider'; import {Popover} from 'primeng/popover'; import {Button} from 'primeng/button'; import {Divider} from 'primeng/divider'; import {Tooltip} from 'primeng/tooltip'; import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; -import {CdkVirtualScrollViewport, CdkVirtualForOf} from '@angular/cdk/scrolling'; -import {CdkAutoSizeVirtualScroll} from '@angular/cdk-experimental/scrolling'; -import {BookBrowserScrollService} from '../../../book/components/book-browser/book-browser-scroll.service'; +import {RouteScrollPositionService} from '../../../../shared/service/route-scroll-position.service'; import {MessageService} from 'primeng/api'; import {AuthorService} from '../../service/author.service'; import {AuthorSummary, EnrichedAuthor, AuthorFilters, DEFAULT_AUTHOR_FILTERS} from '../../model/author.model'; 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 {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 {BookService} from '../../../book/service/book.service'; 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'; @@ -59,21 +54,17 @@ const DEFAULT_SORT_DIRECTIONS: Record = { templateUrl: './author-browser.component.html', styleUrls: ['./author-browser.component.scss'], imports: [ - NgStyle, FormsModule, ProgressSpinner, InputText, Select, - Slider, Popover, Button, Divider, Tooltip, TranslocoDirective, + GridDensityButtonsComponent, AuthorCardComponent, - CdkVirtualScrollViewport, - CdkVirtualForOf, - CdkAutoSizeVirtualScroll, ] }) export class AuthorBrowserComponent implements OnInit { @@ -82,39 +73,32 @@ export class AuthorBrowserComponent implements OnInit { private static readonly BASE_HEIGHT = 290; private static readonly MOBILE_BASE_WIDTH = 140; 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 bookService = inject(BookService); private messageService = inject(MessageService); private pageTitle = inject(PageTitleService); - private scrollService = inject(BookBrowserScrollService); + private scrollService = inject(RouteScrollPositionService); private t = inject(TranslocoService); private router = inject(Router); private activatedRoute = inject(ActivatedRoute); private destroyRef = inject(DestroyRef); + private localStorageService = inject(LocalStorageService); protected userService = inject(UserService); - protected authorScaleService = inject(AuthorScalePreferenceService); 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 readonly viewportWidth = signal(0); - private viewportResizeObserver: ResizeObserver | undefined; + private readonly scrollElement = viewChild>('scrollElement'); + 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); thumbnailCacheBusters = new Map(); @@ -204,29 +188,25 @@ export class AuthorBrowserComponent implements OnInit { } readonly isMobile = computed(() => this.screenWidth() <= 767); - - readonly cardWidth = computed(() => { - const base = this.isMobile() - ? AuthorBrowserComponent.MOBILE_BASE_WIDTH - : AuthorBrowserComponent.BASE_WIDTH; - return Math.round(base * this.authorScaleService.scaleFactor()); - }); - - readonly cardHeight = computed(() => { - const base = this.isMobile() + private readonly baseCardWidth = computed(() => this.isMobile() + ? AuthorBrowserComponent.MOBILE_BASE_WIDTH + : AuthorBrowserComponent.BASE_WIDTH + ); + private readonly cardAspectRatio = computed(() => { + const baseHeight = this.isMobile() ? AuthorBrowserComponent.MOBILE_BASE_HEIGHT : AuthorBrowserComponent.BASE_HEIGHT; - return Math.round(base * this.authorScaleService.scaleFactor()); + return baseHeight / this.baseCardWidth(); }); - - readonly gridColumnMinWidth = computed(() => `${this.cardWidth()}px`); - - readonly gridColumns = computed(() => { - return computeGridColumns(this.viewportWidth(), this.cardWidth() || 165, AuthorBrowserComponent.GRID_GAP); - }); - - readonly authorRows = computed(() => { - return chunk(this.filteredAuthors(), this.gridColumns()); + private readonly minCardWidth = computed(() => Math.round(this.baseCardWidth() * this.scaleFactor())); + readonly virtualGrid = createVirtualGrid({ + items: this.filteredAuthors, + scrollElement: this.scrollElement, + minItemWidth: this.minCardWidth, + gap: AuthorBrowserComponent.GRID_GAP, + initialOffset: this.initialScrollOffset, + fillItemWidth: true, + estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()), }); sortOptions: SortOption[] = []; @@ -238,7 +218,6 @@ export class AuthorBrowserComponent implements OnInit { ngOnInit(): void { this.pageTitle.setPageTitle(this.t.translate('authorBrowser.pageTitle')); - this.destroyRef.onDestroy(() => this.viewportResizeObserver?.disconnect()); this.sortOptions = [ {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.setupScrollPositionTracking(); + this.scrollService.trackRoute({ + scrollElement: this.scrollElement, + route: this.activatedRoute, + destroyRef: this.destroyRef, + dismissOverlaysBeforeSave: true, + }); 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 { 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 { const idSet = new Set(ids); this.allAuthorsState.update(current => (current ?? []).filter(author => !idSet.has(author.id))); diff --git a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.html b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.html index 0f43e7218..16de21917 100644 --- a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.html +++ b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.html @@ -104,22 +104,30 @@

{{ t('noBooksFound') }}

} @else { - -
- @for (book of row; let j = $index; track book.id) { -
- - -
+
+
+ @for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) { + @if (books[virtualItem.index]; as book) { +
+
+ + +
+
+ } }
- +
}
} diff --git a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.scss b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.scss index 469fce74d..afce10220 100644 --- a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.scss +++ b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.scss @@ -157,10 +157,11 @@ color: #e2e8f0; } -.books-virtual-scroller { +.author-books-scroller { width: 100%; height: calc(100dvh - 22rem); box-sizing: border-box; + overflow-y: auto; scrollbar-width: thin; 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 { display: flex; diff --git a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts index 6124bd4c2..70fdb3b0a 100644 --- a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts +++ b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.spec.ts @@ -1,4 +1,4 @@ -import {ElementRef, signal} from '@angular/core'; +import {signal} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {TranslocoService} from '@jsverse/transloco'; import {MessageService} from 'primeng/api'; @@ -99,8 +99,7 @@ describe('AuthorDetailComponent', () => { { provide: CoverScalePreferenceService, useValue: { - currentCardSize: vi.fn(() => 'medium'), - gridColumnMinWidth: vi.fn(() => '12rem'), + currentCardSize: vi.fn(() => ({width: 135, height: 220})), }, }, { @@ -182,29 +181,21 @@ describe('AuthorDetailComponent', () => { 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(); - component.descriptionContentRef = { - nativeElement: { - scrollHeight: 120, - clientHeight: 60, - }, - } as unknown as ElementRef; - - component.ngAfterViewChecked(); + component.updateDescriptionOverflow({ + scrollHeight: 120, + clientHeight: 60, + }); expect(component.isOverflowing).toBe(true); component.isExpanded = true; - component.descriptionContentRef = { - nativeElement: { - scrollHeight: 20, - clientHeight: 80, - }, - } as unknown as ElementRef; - - component.ngAfterViewChecked(); + component.updateDescriptionOverflow({ + scrollHeight: 20, + clientHeight: 80, + }); expect(component.isOverflowing).toBe(true); }); diff --git a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts index 1fcb26e93..1e2882a07 100644 --- a/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts +++ b/frontend/src/app/features/author-browser/components/author-detail/author-detail.component.ts @@ -1,14 +1,11 @@ -import { AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, OnInit, signal, ViewChild } from '@angular/core'; -import { computeGridColumns } from '../../../../shared/util/viewport.util'; +import { AfterViewChecked, Component, computed, ElementRef, inject, OnInit, signal, viewChild } from '@angular/core'; 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 { ProgressSpinner } from 'primeng/progressspinner'; import { Button } from 'primeng/button'; import { Tag } from 'primeng/tag'; 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 { Tooltip } from 'primeng/tooltip'; 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 { AuthorEditorComponent } from '../author-editor/author-editor.component'; import { PageTitleService } from '../../../../shared/service/page-title.service'; -import { chunk } from '../../../../shared/util/array.util'; +import { createVirtualGrid } from '../../../../shared/util/virtual-grid.util'; @Component({ selector: 'app-author-detail', @@ -30,7 +27,6 @@ import { chunk } from '../../../../shared/util/array.util'; styleUrls: ['./author-detail.component.scss'], imports: [ NgClass, - NgStyle, Tabs, TabList, Tab, @@ -41,9 +37,6 @@ import { chunk } from '../../../../shared/util/array.util'; Tag, TranslocoDirective, Tooltip, - CdkVirtualScrollViewport, - CdkVirtualForOf, - CdkAutoSizeVirtualScroll, BookCardComponent, AuthorMatchComponent, AuthorEditorComponent @@ -63,27 +56,9 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked { protected userService = inject(UserService); private pageTitle = inject(PageTitleService); private t = inject(TranslocoService); - private destroyRef = inject(DestroyRef); - @ViewChild('descriptionContent') descriptionContentRef?: ElementRef; - virtualScroller?: CdkVirtualScrollViewport; - - @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; + readonly descriptionContentRef = viewChild>('descriptionContent'); + private readonly scrollElement = viewChild>('scrollElement'); loading = signal(true); tab = 'books'; @@ -109,16 +84,12 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked { return this.coverScalePreferenceService.currentCardSize(); } - get gridColumnMinWidth(): string { - return this.coverScalePreferenceService.gridColumnMinWidth(); - } - - readonly gridColumns = computed(() => { - return computeGridColumns(this.viewportWidth(), parseInt(this.gridColumnMinWidth, 10) || 180, AuthorDetailComponent.GRID_GAP); - }); - - readonly bookRows = computed(() => { - return chunk(this.authorBooks(), this.gridColumns()); + readonly virtualGrid = createVirtualGrid({ + items: this.authorBooks, + scrollElement: this.scrollElement, + minItemWidth: computed(() => this.currentCardSize.width), + estimateItemHeight: () => this.currentCardSize.height, + gap: AuthorDetailComponent.GRID_GAP, }); get photoUrl(): string { @@ -139,15 +110,16 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked { this.tab = tabParam; } this.loadAuthor(authorId); - this.destroyRef.onDestroy(() => this.viewportResizeObserver?.disconnect()); } - - ngAfterViewChecked(): void { - if (!this.isExpanded && this.descriptionContentRef) { - const el = this.descriptionContentRef.nativeElement; - this.isOverflowing = el.scrollHeight > el.clientHeight; + const descriptionContent = this.descriptionContentRef(); + this.updateDescriptionOverflow(descriptionContent?.nativeElement); + } + + updateDescriptionOverflow(element?: Pick): void { + if (!this.isExpanded && element) { + this.isOverflowing = element.scrollHeight > element.clientHeight; } } diff --git a/frontend/src/app/features/author-browser/service/author-scale-preference.service.spec.ts b/frontend/src/app/features/author-browser/service/author-scale-preference.service.spec.ts deleted file mode 100644 index 6421a82fb..000000000 --- a/frontend/src/app/features/author-browser/service/author-scale-preference.service.spec.ts +++ /dev/null @@ -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); - }); -}); diff --git a/frontend/src/app/features/author-browser/service/author-scale-preference.service.ts b/frontend/src/app/features/author-browser/service/author-scale-preference.service.ts deleted file mode 100644 index 65586443b..000000000 --- a/frontend/src/app/features/author-browser/service/author-scale-preference.service.ts +++ /dev/null @@ -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 | 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(this.STORAGE_KEY); - if (saved !== null && !isNaN(saved)) { - return saved; - } - return 1.0; - } -} diff --git a/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.spec.ts deleted file mode 100644 index 3f3fa3e65..000000000 --- a/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.spec.ts +++ /dev/null @@ -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(); - }); -}); diff --git a/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.ts b/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.ts deleted file mode 100644 index c134a32de..000000000 --- a/frontend/src/app/features/book/components/book-browser/book-browser-scroll.service.ts +++ /dev/null @@ -1,29 +0,0 @@ -import {Injectable} from '@angular/core'; - -@Injectable({ - providedIn: 'root' -}) -export class BookBrowserScrollService { - private scrollPositions = new Map(); - - 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 { - const paramValues = Object.values(params).join('-'); - return paramValues ? `${path}:${paramValues}` : path; - } -} diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.html b/frontend/src/app/features/book/components/book-browser/book-browser.component.html index fae7d2a44..ee6e9e623 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.html +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.html @@ -124,20 +124,20 @@ @if (isMobile()) {
{{ t('labels.gridColumns') }} -
+
@@ -145,17 +145,7 @@ } @else {
{{ t('labels.gridItemSize') }} - - -
- {{ coverScalePreferenceService.scaleFactor().toFixed(2) }}x -
+
}
@@ -280,13 +270,16 @@ }
} @else if (showGridLoadingPlaceholder()) { -
- @for (item of skeletonSlots; track item) { -
-
- } +
+
+ @for (item of skeletonSlots; track item) { +
+
+ } +
} @else if (booksError()) {
@@ -294,59 +287,60 @@ {{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}

- } @else if (books(); as books) { -
-
- @if (books.length === 0 && !isBooksLoading()) { -
-

- {{ t('labels.noBooks') }} -

-
- } - @if (currentViewMode() === 'table' && books.length > 0) { - - } - @if (currentViewMode() === 'grid') { -
-
-
- @for (book of books; track book.id; let i = $index) { -
- - -
- } + } @else { + @let visibleBooks = books(); + @if (visibleBooks.length === 0 && !isBooksLoading()) { +
+

+ {{ t('labels.noBooks') }} +

+
+ } + @if (currentViewMode() === 'table' && visibleBooks.length > 0) { + + } + @if (currentViewMode() === 'grid') { +
+
+ @for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) { + @if (visibleBooks[virtualItem.index]; as book) { +
+ +
-
-
-
- } - @if (userService.currentUser(); as currentUser) { + } @else { +
+ } + } +
+
+ } + @if (userService.currentUser(); as currentUser) { -
}
diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.scss b/frontend/src/app/features/book/components/book-browser/book-browser.component.scss index 4c6066326..15acfc0b2 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.scss +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.scss @@ -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 { display: grid; gap: 21px; - align-items: start; + place-items: start center; width: 100%; @media (width <= 767px) { - gap: 0.5rem 8px; - padding: 0 0.5rem; + gap: 8px; } } @@ -221,38 +218,6 @@ 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 { position: relative; @@ -437,41 +402,18 @@ .virtual-scroller { width: 100%; height: calc(100dvh - 10.9rem); - padding: 1rem; + padding: 1rem 0; box-sizing: border-box; overflow-y: auto; @media (width <= 768px) { height: calc(100dvh - 9rem); + padding: 0.75rem; } } -.book-grid { - display: grid; - 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; - } +.virtual-loader-cell { + pointer-events: none; } // No books state @@ -608,12 +550,3 @@ } } } - -// Book state container -.book-state-wrapper { - position: relative; -} - -.book-state-content-refreshing { - pointer-events: none; -} diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts index 49330e2f5..3821c0ca6 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts @@ -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 {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router'; import {BehaviorSubject, Subject} from 'rxjs'; @@ -26,7 +26,7 @@ import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.s import {BookSelectionService} from './book-selection.service'; import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.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 {BookBrowserComponent, EntityType} from './book-browser.component'; import {SortService} from '../../service/sort.service'; @@ -106,6 +106,7 @@ interface BookBrowserHarness { booksError: WritableSignal; isBooksLoading: WritableSignal; paramMap$: BehaviorSubject; + setHasNextPage: (value: boolean) => void; queryParamsService: { shouldForceExpandSeries: ReturnType; updateViewMode: ReturnType; @@ -125,6 +126,7 @@ interface BookBrowserHarness { function createHarness(options?: { books?: Book[]; + totalElements?: number; booksError?: string | null; isBooksLoading?: boolean; translate?: (key: string) => string; @@ -138,6 +140,7 @@ function createHarness(options?: { ); const booksError = signal(options?.booksError ?? null); const isBooksLoading = signal(options?.isBooksLoading ?? false); + const hasNextPage = signal(false); const currentUser = signal(makeCurrentUser()); const showFilter = signal(false); const seriesCollapsed = signal(false); @@ -175,7 +178,6 @@ function createHarness(options?: { SortService, BookSelectionService, BookNavigationService, - BookBrowserScrollService, { provide: UserService, useValue: { @@ -187,9 +189,6 @@ function createHarness(options?: { { provide: CoverScalePreferenceService, useValue: { - currentCardSize: vi.fn(() => ({width: 120, height: 160})), - gridColumnMinWidth: vi.fn(() => '120px'), - getCardHeight: vi.fn(() => 160), scaleFactor: vi.fn(() => 1), setScale: vi.fn(), }, @@ -241,11 +240,13 @@ function createHarness(options?: { }, }, { - provide: BookBrowserScrollService, + provide: RouteScrollPositionService, useValue: { createKey: vi.fn(() => 'test-key'), + keyFor: vi.fn(() => 'test-key'), savePosition: vi.fn(), getPosition: vi.fn(() => 0), + trackRoute: vi.fn(), }, }, {provide: ConfirmationService, useValue: {confirm: vi.fn()}}, @@ -289,8 +290,6 @@ function createHarness(options?: { const _filters = signal({}); const _sort = signal({field: 'addedOn', dir: 'desc'}); const _search = signal(''); - const _hasNextPage = signal(false); - const filteredSortedBooks = computed(() => { let result = books(); const f = _filters(); @@ -307,12 +306,12 @@ function createHarness(options?: { } return result; }); + const totalElements = computed(() => options?.totalElements ?? filteredSortedBooks().length); return { books: filteredSortedBooks, - totalElements: computed(() => filteredSortedBooks().length), - hasNextPage: _hasNextPage.asReadonly(), - setHasNextPage: (v: boolean) => _hasNextPage.set(v), + totalElements, + hasNextPage: hasNextPage.asReadonly(), isLoading: isBooksLoading.asReadonly(), isFetchingNextPage: computed(() => false), isError: computed(() => !!booksError()), @@ -394,6 +393,7 @@ function createHarness(options?: { booksError, isBooksLoading, paramMap$, + setHasNextPage: value => hasNextPage.set(value), queryParamsService, routeSnapshot, }; @@ -407,11 +407,6 @@ describe('BookBrowserComponent', () => { unobserve = vi.fn(); disconnect = vi.fn(); }); - vi.stubGlobal('IntersectionObserver', class { - observe = vi.fn(); - unobserve = vi.fn(); - disconnect = vi.fn(); - }); }); afterEach(() => { @@ -428,48 +423,38 @@ describe('BookBrowserComponent', () => { 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); }); - it('keeps rendered books visible during same-context refreshes', () => { + it('updates books when sorting changes', () => { const {component} = createHarness(); - expect(component.books()).toBeUndefined(); + TestBed.flushEffects(); - vi.runOnlyPendingTimers(); - - expect(component.books()?.map(book => book.id)).toEqual([2, 1]); - expect(component.isBooksRefreshing()).toBe(false); + expect(component.books().map(book => book.id)).toEqual([2, 1]); component.applySortCriteria([ {label: 'Title', field: 'title', direction: SortDirection.ASCENDING}, ]); TestBed.flushEffects(); - 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); + expect(component.books().map(book => book.id)).toEqual([1, 2]); }); - 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(); - vi.runOnlyPendingTimers(); - expect(component.books()?.map(book => book.id)).toEqual([2, 1]); + TestBed.flushEffects(); + + expect(component.books().map(book => book.id)).toEqual([2, 1]); routeSnapshot.paramMap = convertToParamMap({libraryId: '2'}); routeSnapshot.params = {libraryId: '2'}; paramMap$.next(routeSnapshot.paramMap); TestBed.flushEffects(); - expect(component.books()).toBeUndefined(); - 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); + expect(component.books().map(book => book.id)).toEqual([3]); }); it('hides loading placeholders when the books query is in an error state', () => { @@ -478,17 +463,12 @@ describe('BookBrowserComponent', () => { isBooksLoading: true, }); - const comp = component as unknown as { - showBooksLoadingPlaceholder: () => boolean; - showGridLoadingPlaceholder: () => boolean; - showTableLoadingPlaceholder: () => boolean; - }; - expect(comp.showBooksLoadingPlaceholder()).toBe(false); - expect(comp.showGridLoadingPlaceholder()).toBe(false); - expect(comp.showTableLoadingPlaceholder()).toBe(false); + expect(component.showBooksLoadingPlaceholder()).toBe(false); + expect(component.showGridLoadingPlaceholder()).toBe(false); + expect(component.showTableLoadingPlaceholder()).toBe(false); }); - it('calls SeriesCollapseFilter.collapseBooks when computing pipelineInputs', () => { + it('calls SeriesCollapseFilter.collapseBooks when computing books', () => { createHarness(); const filter = TestBed.inject(SeriesCollapseFilter); const collapseBooksSpy = vi.spyOn(filter, 'collapseBooks'); @@ -499,35 +479,48 @@ describe('BookBrowserComponent', () => { expect(collapseBooksSpy).toHaveBeenCalled(); }); - it('triggers next page fetch when scrolled near the bottom of rendered content', async () => { - const {component} = createHarness(); + it('triggers next page fetch when the virtual grid reaches the loaded rows', () => { + const {component, setHasNextPage} = createHarness(); const appBooksApi = TestBed.inject(AppBooksApiService); - // Initial load vi.runOnlyPendingTimers(); TestBed.flushEffects(); - // Mock hasNextPage to be true - // @ts-expect-error test helper - appBooksApi.setHasNextPage(true); + vi.spyOn(component.virtualGrid.virtualizer, 'getVirtualItems').mockReturnValue([ + {index: 2, key: 2, start: 0, end: 241, size: 241, lane: 0} + ]); + + component.currentViewMode.set(VIEW_MODES.TABLE); + TestBed.flushEffects(); + + setHasNextPage(true); const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage'); - - // 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; - - // Trigger initial check - vi.runOnlyPendingTimers(); // For requestAnimationFrame + component.currentViewMode.set(VIEW_MODES.GRID); TestBed.flushEffects(); 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); + }); }); diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.ts index e7ec8e6cf..fd42a0e71 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.ts @@ -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 {ActivatedRoute, NavigationStart, Router} from '@angular/router'; +import {ActivatedRoute} from '@angular/router'; import {ConfirmationService, MenuItem, MessageService} from 'primeng/api'; import {PageTitleService} from '../../../../shared/service/page-title.service'; import {BookService} from '../../service/book.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 {DynamicDialogRef} from 'primeng/dynamicdialog'; import {Library} from '../../model/library.model'; @@ -13,9 +13,8 @@ import {SortDirection, SortOption} from '../../model/sort.model'; import {Book} from '../../model/book.model'; import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service'; import {BookTableComponent} from './book-table/book-table.component'; -import {computeGridColumns} from '../../../../shared/util/viewport.util'; 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 {Menu} from 'primeng/menu'; @@ -30,7 +29,6 @@ import {BookSorter} from './sorting/BookSorter'; import {BookDialogHelperService} from './book-dialog-helper.service'; import {Checkbox} from 'primeng/checkbox'; import {Popover} from 'primeng/popover'; -import {Slider} from 'primeng/slider'; import {Divider} from 'primeng/divider'; import {MultiSelect} from 'primeng/multiselect'; 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 {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-params.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 {MultiSortPopoverComponent} from './sorting/multi-sort-popover/multi-sort-popover.component'; import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; -import {DeferredRenderState} from './deferred-render-state'; import {SortService} from '../../service/sort.service'; import {AppBooksApiService} from '../../service/app-books-api.service'; 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 { LIBRARY = 'Library', @@ -74,8 +73,8 @@ export enum EntityType { changeDetection: ChangeDetectionStrategy.OnPush, imports: [ Button, BookCardComponent, Menu, InputText, FormsModule, - BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover, - Checkbox, Slider, Divider, MultiSelect, TieredMenu, Badge, MultiSortPopoverComponent, TranslocoDirective, + BookTableComponent, BookFilterComponent, Tooltip, NgClass, Popover, + Checkbox, Divider, MultiSelect, TieredMenu, Badge, MultiSortPopoverComponent, TranslocoDirective, GridDensityButtonsComponent, ], providers: [SeriesCollapseFilter], }) @@ -93,7 +92,6 @@ export class BookBrowserComponent implements AfterViewInit { protected appSettingsService = inject(AppSettingsService); private activatedRoute = inject(ActivatedRoute); - private router = inject(Router); private messageService = inject(MessageService); private bookService = inject(BookService); private bookMetadataManageService = inject(BookMetadataManageService); @@ -108,7 +106,7 @@ export class BookBrowserComponent implements AfterViewInit { private sortService = inject(SortService); private appBooksApi = inject(AppBooksApiService); private localStorageService = inject(LocalStorageService); - private scrollService = inject(BookBrowserScrollService); + private scrollService = inject(RouteScrollPositionService); private readonly t = inject(TranslocoService); private readonly destroyRef = inject(DestroyRef); @@ -116,15 +114,13 @@ export class BookBrowserComponent implements AfterViewInit { this.loadMobileColumnsPreference(); this.setupRouteChangeHandlers(); this.setupQueryParamSubscription(); - this.setupScrollPositionTracking(); - - this.destroyRef.onDestroy(() => { - if (this.scrollContainer) { - this.scrollContainer.removeEventListener('scroll', this.onScroll); - } - this.containerResizeObserver?.disconnect(); - this.sentinelObserver?.disconnect(); + this.scrollService.trackRoute({ + scrollElement: this.scrollElement, + route: this.activatedRoute, + destroyRef: this.destroyRef, + dismissOverlaysBeforeSave: true, }); + this.destroyRef.onDestroy(() => this.bookSelectionService.deselectAll()); } private readonly defaultSortCriteria: SortOption[] = [{ @@ -276,94 +272,63 @@ export class BookBrowserComponent implements AfterViewInit { } }); - // --- Deferred render: lets skeleton/refresh indicator paint before committing --- - private readonly booksRenderState = new DeferredRenderState(); - 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(() => { + readonly books = computed(() => { const books = this.appBooksApi.books(); 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 booksError = this.appBooksApi.error; - readonly bookIndexById = computed(() => { - const books = this.books(); - if (!books) return new Map(); - const map = new Map(); - 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 containerWidth = signal(0); - private containerResizeObserver: ResizeObserver | undefined; - - readonly gridColumns = computed(() => { - return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth(), 10) || 180, this.GRID_GAP); + 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 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>('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; }); - - /** - * Estimated total content height based on totalElements from the first API page. - * Used as min-height so the scrollbar reflects the full collection from the start. - * Only grows, never shrinks — prevents scroll teleportation. - */ - readonly estimatedTotalHeight = computed(() => { - const total = this.appBooksApi.totalElements(); - if (total === 0) return 0; - const cols = this.gridColumns(); - const rows = Math.ceil(total / cols); - const rowHeight = this.currentCardSize().height + this.GRID_GAP; - return rows * rowHeight; + readonly virtualGrid = createVirtualGrid({ + items: this.gridBooks, + scrollElement: this.scrollElement, + minItemWidth: this.minCardWidth, + gap: this.virtualGridGap, + columns: this.virtualGridColumns, + count: this.virtualBookCount, + enabled: this.isGridView, + initialOffset: this.initialScrollOffset, + fillItemWidth: true, + estimateItemHeight: itemWidth => this.isMobile() + ? this.mobileCardSizeForWidth(itemWidth).height + : 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); readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index); readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index); @@ -407,13 +372,6 @@ export class BookBrowserComponent implements AfterViewInit { entityViewPreferences: EntityViewPreferences | undefined; 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; protected metadataMenuItems: MenuItem[] | undefined; protected moreActionsMenuItems: MenuItem[] | undefined; @@ -467,12 +425,6 @@ export class BookBrowserComponent implements AfterViewInit { }); private readonly syncBooksEffect = effect(() => { const books = this.books(); - if (!books) { - this.bookSelectionService.setCurrentBooks([]); - this.bookNavigationService.setAvailableBookIds([]); - return; - } - this.bookSelectionService.setCurrentBooks(books); this.bookNavigationService.setAvailableBookIds(books.map(book => book.id)); }); @@ -483,61 +435,26 @@ export class BookBrowserComponent implements AfterViewInit { ); }); - /** - * Triggers sequential page loads if the current scroll position is beyond the loaded content. - * This is critical for scroll restoration on page reload. - */ - private readonly fillScrollGapEffect = effect(() => { - const books = this.books(); - if (books && books.length > 0) { - this.checkAndFetchIfNeeded(); + private readonly fetchNextPageEffect = effect(() => { + if (this.currentViewMode() !== VIEW_MODES.GRID) return; + + const virtualItems = this.virtualGrid.virtualizer.getVirtualItems(); + const loadedBookCount = this.gridBooks().length; + const lastItem = virtualItems.at(-1); + + if ( + lastItem && + loadedBookCount > 0 && + lastItem.index >= loadedBookCount - 1 && + this.appBooksApi.hasNextPage() && + !this.appBooksApi.isFetchingNextPage() + ) { + this.appBooksApi.fetchNextPage(); } }); - @ViewChild(BookTableComponent) - bookTableComponent!: BookTableComponent; - @ViewChild(BookFilterComponent, {static: true}) - bookFilterComponent!: BookFilterComponent; - - private scrollContainer: HTMLElement | undefined; - private sentinelObserver: IntersectionObserver | undefined; - - @ViewChild('scrollContainer') - set scrollContainerRef(ref: ElementRef | 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 | 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); - } - } + private readonly bookTableComponent = viewChild(BookTableComponent); + private readonly bookFilterComponent = viewChild(BookFilterComponent); @HostListener('window:resize') onResize(): void { @@ -556,40 +473,41 @@ export class BookBrowserComponent implements AfterViewInit { return {width: cardWidth, height: cardHeight}; }); - readonly currentCardSize = computed(() => { + readonly currentCardSize = computed<{width: number; height: number}>(() => { 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(); - if (this.isAudiobookOnlyLibrary()) { - const squareSide = Math.round(base.width * 1.1); - return { width: squareSide, height: squareSide + 31 }; - } - return base; + return this.cardSizeForWidth(this.virtualGrid.itemWidth()); }); - readonly gridColumnMinWidth = computed(() => { - if (this.isMobile()) { - return `${this.mobileCardSize().width}px`; - } - if (this.isAudiobookOnlyLibrary()) { - return `${this.currentCardSize().width}px`; - } - return this.coverScalePreferenceService.gridColumnMinWidth(); - }); + readonly skeletonMinCardWidth = computed(() => + `${this.isMobile() ? this.mobileCardSize().width : this.minCardWidth()}px` + ); - getCardHeight(_book: Book): number { - if (this.isMobile()) { - return this.mobileCardSize().height; - } + private cardSizeForWidth(width: number): { width: number; height: number } { + const cardWidth = Math.round(width); 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(() => - !this.booksError() && (this.isBooksLoading() || !this.hasRenderedBooks()) + !this.booksError() && this.isBooksLoading() && this.books().length === 0 ); readonly showTableLoadingPlaceholder = computed(() => @@ -636,61 +554,18 @@ export class BookBrowserComponent implements AfterViewInit { readonly sortCriteriaCount = computed(() => this.bookSorter.selectedSortCriteria.length); ngAfterViewInit(): void { - if (this.bookFilterComponent) { - this.bookFilterComponent.setFilters(this.parsedFilters); - this.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); + const bookFilterComponent = this.bookFilterComponent(); + if (bookFilterComponent) { + bookFilterComponent.setFilters(this.parsedFilters); + bookFilterComponent.onFilterModeChange(this.selectedFilterMode()); } } 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.bookTitle.set(''); this.bookSelectionService.deselectAll(); @@ -700,12 +575,11 @@ export class BookBrowserComponent implements AfterViewInit { } private scrollToTop(): void { - if (this.scrollContainer) { - this.scrollContainer.scrollTop = 0; - } - if (this.bookTableComponent) { - this.bookTableComponent.scrollToTop(); + const scrollElement = this.scrollElement()?.nativeElement; + if (scrollElement) { + scrollElement.scrollTop = 0; } + this.bookTableComponent()?.scrollToTop(); } private readonly syncMetadataMenuEffect = effect(() => { @@ -740,12 +614,9 @@ export class BookBrowserComponent implements AfterViewInit { currentUser.userSettings?.filterMode ?? 'and' ); - if (parseResult.filterMode !== this.selectedFilterMode()) { this.selectedFilterMode.set(parseResult.filterMode); - if (this.bookFilterComponent) { - this.bookFilterComponent.onFilterModeChange(parseResult.filterMode); - } + this.bookFilterComponent()?.onFilterModeChange(parseResult.filterMode); } const filterParams = queryParamMap.get('filter'); @@ -754,9 +625,7 @@ export class BookBrowserComponent implements AfterViewInit { this.settingFiltersFromUrl = true; 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) { this.currentFilterLabel.set(this.computedFilterLabel()); @@ -771,7 +640,6 @@ export class BookBrowserComponent implements AfterViewInit { this.parsedFilters = parseResult.filters; - this.entityViewPreferences = currentUser.userSettings?.entityViewPreferences; this.columnPreferenceService.initPreferences(currentUser.userSettings?.tableColumnPreference); 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])); this.visibleSortOptions.set(visibleFields.map(f => sortOptionsByField.get(f)).filter((o): o is SortOption => !!o)); - if (!this.areSortCriteriaEqual(this.bookSorter.selectedSortCriteria, parseResult.sortCriteria)) { this.bookSorter.setSortCriteria(parseResult.sortCriteria); } @@ -788,7 +655,6 @@ export class BookBrowserComponent implements AfterViewInit { this.applySortCriteria(this.bookSorter.selectedSortCriteria); - this.queryParamsService.syncQueryParams( this.currentViewMode()!, this.selectedFilterMode(), @@ -829,7 +695,10 @@ export class BookBrowserComponent implements AfterViewInit { } 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( (a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field) )); @@ -860,9 +729,7 @@ export class BookBrowserComponent implements AfterViewInit { deselectAllBooks(): void { this.bookSelectionService.deselectAll(); - if (this.bookTableComponent) { - this.bookTableComponent.clearSelectedBooks(); - } + this.bookTableComponent()?.clearSelectedBooks(); } confirmDeleteBooks(): void { @@ -1010,7 +877,7 @@ export class BookBrowserComponent implements AfterViewInit { } resetFilters(): void { - this.bookFilterComponent?.clearActiveFilter(); + this.bookFilterComponent()?.clearActiveFilter(); } clearFilter(): void { @@ -1192,7 +1059,7 @@ export class BookBrowserComponent implements AfterViewInit { attachFilesToBook(): void { const selectedBookIds = Array.from(this.selectedBooks()); - const sourceBooks = (this.books() ?? []).filter(book => + const sourceBooks = this.books().filter(book => selectedBookIds.includes(book.id) ); @@ -1230,7 +1097,7 @@ export class BookBrowserComponent implements AfterViewInit { const selectedBookIds = Array.from(this.selectedBooks()); if (selectedBookIds.length === 0) return false; - const selectedBooks = (this.books() ?? []).filter(book => + const selectedBooks = this.books().filter(book => selectedBookIds.includes(book.id) ); @@ -1245,6 +1112,24 @@ export class BookBrowserComponent implements AfterViewInit { 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 { const saved = this.localStorageService.get(this.MOBILE_COLUMNS_STORAGE_KEY); if (saved !== null && [2, 3, 4].includes(saved)) { diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts index f9456d2c9..4a3a76be4 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts @@ -110,13 +110,6 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges { this.selectedBookIds = new Set(this.preselectedBookIds); 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 { diff --git a/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts b/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts index e2dd4638a..1e485cfe5 100644 --- a/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts @@ -1,6 +1,4 @@ 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 {CoverScalePreferenceService} from './cover-scale-preference.service'; @@ -9,28 +7,15 @@ import {LocalStorageService} from '../../../../shared/service/local-storage.serv describe('CoverScalePreferenceService', () => { let service: CoverScalePreferenceService; let localStorageService: { get: ReturnType; set: ReturnType }; - let messageService: { add: ReturnType }; - let translocoService: { translate: ReturnType }; beforeEach(() => { - vi.useFakeTimers(); localStorageService = { get: vi.fn(), set: vi.fn() }; - messageService = { - add: vi.fn() - }; - translocoService = { - translate: vi.fn((key: string, params?: Record) => - params ? `${key}:${JSON.stringify(params)}` : `t:${key}` - ) - }; }); afterEach(() => { - vi.runOnlyPendingTimers(); - vi.useRealTimers(); TestBed.resetTestingModule(); }); @@ -41,8 +26,6 @@ describe('CoverScalePreferenceService', () => { providers: [ CoverScalePreferenceService, {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.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', () => { @@ -61,60 +58,30 @@ describe('CoverScalePreferenceService', () => { providers: [ CoverScalePreferenceService, {provide: LocalStorageService, useValue: localStorageService}, - {provide: MessageService, useValue: messageService}, - {provide: TranslocoService, useValue: translocoService} ] }); service = TestBed.inject(CoverScalePreferenceService); service.setScale(1.0); - vi.runOnlyPendingTimers(); 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); TestBed.configureTestingModule({ providers: [ CoverScalePreferenceService, {provide: LocalStorageService, useValue: localStorageService}, - {provide: MessageService, useValue: messageService}, - {provide: TranslocoService, useValue: translocoService} ] }); service = TestBed.inject(CoverScalePreferenceService); service.setScale(1.2); - expect(localStorageService.set).not.toHaveBeenCalled(); - - vi.advanceTimersByTime(1000); 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 - })); }); }); diff --git a/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.ts b/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.ts index 664e0967f..0c0248931 100644 --- a/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.ts +++ b/frontend/src/app/features/book/components/book-browser/cover-scale-preference.service.ts @@ -1,8 +1,6 @@ -import {computed, inject, Injectable, signal} from '@angular/core'; -import {MessageService} from 'primeng/api'; -import {TranslocoService} from '@jsverse/transloco'; +import {computed, inject, Injectable} from '@angular/core'; import {LocalStorageService} from '../../../../shared/service/local-storage.service'; -import {Book} from '../../model/book.model'; +import {ScalePreference} from '../../../../shared/util/scale-preference.util'; @Injectable({ providedIn: 'root' @@ -11,83 +9,24 @@ export class CoverScalePreferenceService { private readonly BASE_WIDTH = 135; private readonly BASE_HEIGHT = 220; - private readonly TITLE_BAR_HEIGHT = 31; - private readonly DEBOUNCE_MS = 1000; 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 _scaleFactor = signal(1.0); - readonly scaleFactor = this._scaleFactor.asReadonly(); + private readonly scalePreference = new ScalePreference(this.localStorageService, { + storageKey: this.STORAGE_KEY, + minScale: this.MIN_SCALE, + maxScale: this.MAX_SCALE, + }); + readonly scaleFactor = this.scalePreference.scaleFactor; readonly currentCardSize = computed(() => ({ width: Math.round(this.BASE_WIDTH * this.scaleFactor()), height: Math.round(this.BASE_HEIGHT * this.scaleFactor()), })); - readonly gridColumnMinWidth = computed(() => `${this.currentCardSize().width}px`); - - private saveTimeout: ReturnType | 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); - } - - 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(this.STORAGE_KEY); - if (saved !== null && !isNaN(saved)) { - return saved; - } - return 1.0; + this.scalePreference.setScale(scale); } } diff --git a/frontend/src/app/features/book/components/book-browser/deferred-render-state.spec.ts b/frontend/src/app/features/book/components/book-browser/deferred-render-state.spec.ts deleted file mode 100644 index 4fae0680b..000000000 --- a/frontend/src/app/features/book/components/book-browser/deferred-render-state.spec.ts +++ /dev/null @@ -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(); - - 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(); - - 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(); - - 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(); - - 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(); - - 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(); - - 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); - }); -}); diff --git a/frontend/src/app/features/book/components/book-browser/deferred-render-state.ts b/frontend/src/app/features/book/components/book-browser/deferred-render-state.ts deleted file mode 100644 index 93688c66f..000000000 --- a/frontend/src/app/features/book/components/book-browser/deferred-render-state.ts +++ /dev/null @@ -1,52 +0,0 @@ -import {computed, signal} from '@angular/core'; - -export type DeferredRenderMode = 'reset' | 'refresh'; - -export class DeferredRenderState { - private readonly _value = signal(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); - } -} diff --git a/frontend/src/app/features/book/components/series-page/series-page.component.html b/frontend/src/app/features/book/components/series-page/series-page.component.html index bb2cf9614..a16327984 100644 --- a/frontend/src/app/features/book/components/series-page/series-page.component.html +++ b/frontend/src/app/features/book/components/series-page/series-page.component.html @@ -279,11 +279,13 @@ {{ t('booksInSeries') }} + @let cardSize = currentCardSize;
+ [style.grid-template-columns]="'repeat(auto-fill, minmax(' + cardSize.width + 'px, 1fr))'"> @for (book of books; track book; let i = $index) {
+ [style.width.px]="cardSize.width" + [style.height.px]="cardSize.height"> { diff --git a/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.html b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.html index fb8029895..fa5a34dfb 100644 --- a/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.html +++ b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.html @@ -45,24 +45,14 @@ class="sort-dropdown"> - @if (!isMobile) { + @if (!isMobile()) {
{{ t('cardSize') }} - - -
- {{ seriesScaleService.scaleFactor().toFixed(2) }}x -
+
} @@ -77,21 +67,29 @@

{{ t('noSeriesFound') }}

} @else { - -
- @for (series of row; track series.seriesName) { -
- - -
+
+
+ @for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) { + @if (seriesList[virtualItem.index]; as series) { +
+
+ + +
+
+ } }
- +
} } } diff --git a/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.scss b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.scss index 54e31856e..b14c68b51 100644 --- a/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.scss +++ b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.scss @@ -96,12 +96,6 @@ color: #e2e8f0; } -.scale-value-display { - text-align: center; - font-size: 0.8rem; - color: #94a3b8; -} - // Virtual scroller and grid .virtual-scroller { 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 { display: flex; diff --git a/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.ts b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.ts index 96d5ddec1..c927b5a32 100644 --- a/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.ts +++ b/frontend/src/app/features/series-browser/components/series-browser/series-browser.component.ts @@ -1,23 +1,22 @@ -import {Component, DestroyRef, HostListener, NgZone, computed, effect, inject, OnInit, signal, ViewChild} from '@angular/core'; -import {computeGridColumns} from '../../../../shared/util/viewport.util'; -import {NgStyle} from '@angular/common'; +import {Component, DestroyRef, ElementRef, HostListener, computed, inject, OnInit, signal, viewChild} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {ProgressSpinner} from 'primeng/progressspinner'; import {InputText} from 'primeng/inputtext'; import {Select} from 'primeng/select'; -import {Slider} from 'primeng/slider'; import {Popover} from 'primeng/popover'; import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; -import {CdkFixedSizeVirtualScroll, CdkVirtualScrollViewport, CdkVirtualForOf} from '@angular/cdk/scrolling'; import {SeriesDataService} from '../../service/series-data.service'; import {SeriesSummary} from '../../model/series.model'; import {SeriesCardComponent} from '../series-card/series-card.component'; -import {chunk} from '../../../../shared/util/array.util'; import {BookService} from '../../../book/service/book.service'; import {ReadStatus} from '../../../book/model/book.model'; import {PageTitleService} from '../../../../shared/service/page-title.service'; -import {SeriesScalePreferenceService} from '../../service/series-scale-preference.service'; -import {Router} from '@angular/router'; +import {ActivatedRoute, 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 { label: string; @@ -35,18 +34,14 @@ interface SortOption { templateUrl: './series-browser.component.html', styleUrls: ['./series-browser.component.scss'], imports: [ - NgStyle, FormsModule, ProgressSpinner, InputText, Select, - Slider, Popover, TranslocoDirective, + GridDensityButtonsComponent, SeriesCardComponent, - CdkVirtualScrollViewport, - CdkFixedSizeVirtualScroll, - CdkVirtualForOf, ] }) 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_HEIGHT = 250; 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 bookService = inject(BookService); private pageTitle = inject(PageTitleService); private t = inject(TranslocoService); private router = inject(Router); + private activatedRoute = inject(ActivatedRoute); private destroyRef = inject(DestroyRef); - private zone = inject(NgZone); - protected seriesScaleService = inject(SeriesScalePreferenceService); - - 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; + private scrollService = inject(RouteScrollPositionService); + private localStorageService = inject(LocalStorageService); readonly isBooksLoading = this.bookService.isBooksLoading; private readonly searchTerm = signal(''); @@ -110,53 +84,46 @@ export class SeriesBrowserComponent implements OnInit { return this.applySort(result, this.sortBy()); }); - screenWidth = window.innerWidth; + private readonly scrollElement = viewChild>('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[] = []; sortOptions: SortOption[] = []; @HostListener('window:resize') onResize(): void { - this.screenWidth = window.innerWidth; - this.scheduleViewportRefresh(); + this.screenWidth.set(window.innerWidth); } - get isMobile(): boolean { - return this.screenWidth <= 767; - } + readonly isMobile = computed(() => this.screenWidth() <= 767); - get cardWidth(): number { - const base = this.isMobile - ? SeriesBrowserComponent.MOBILE_BASE_WIDTH - : SeriesBrowserComponent.BASE_WIDTH; - return Math.round(base * this.seriesScaleService.scaleFactor()); - } - - get cardHeight(): number { - const base = this.isMobile + private readonly baseCardWidth = computed(() => this.isMobile() + ? SeriesBrowserComponent.MOBILE_BASE_WIDTH + : SeriesBrowserComponent.BASE_WIDTH + ); + private readonly cardAspectRatio = computed(() => { + const baseHeight = this.isMobile() ? SeriesBrowserComponent.MOBILE_BASE_HEIGHT : SeriesBrowserComponent.BASE_HEIGHT; - return Math.round(base * this.seriesScaleService.scaleFactor()); - } - - get rowHeight(): number { - return this.cardHeight + SeriesBrowserComponent.ROW_TOP_PADDING; - } - - readonly gridColumns = computed(() => { - return computeGridColumns(this.viewportWidth(), this.cardWidth || 230, SeriesBrowserComponent.GRID_GAP); + return baseHeight / this.baseCardWidth(); }); - - readonly seriesRows = computed(() => { - return chunk(this.filteredSeries(), this.gridColumns()); - }); - - private readonly refreshViewportEffect = effect(() => { - const hasRows = this.seriesRows().length > 0; - const rowHeight = this.rowHeight; - if (hasRows && rowHeight > 0) { - this.scheduleViewportRefresh(); - } + private readonly minCardWidth = computed(() => Math.round(this.baseCardWidth() * this.scaleFactor())); + readonly virtualGrid = createVirtualGrid({ + items: this.filteredSeries, + scrollElement: this.scrollElement, + minItemWidth: this.minCardWidth, + gap: SeriesBrowserComponent.GRID_GAP, + initialOffset: this.initialScrollOffset, + fillItemWidth: true, + estimateItemHeight: itemWidth => Math.round(itemWidth * this.cardAspectRatio()), }); + readonly currentCardScale = computed(() => this.virtualGrid.itemWidth() / this.baseCardWidth()); get searchValue(): string { return this.searchTerm(); @@ -172,11 +139,10 @@ export class SeriesBrowserComponent implements OnInit { ngOnInit(): void { this.pageTitle.setPageTitle(this.t.translate('seriesBrowser.pageTitle')); - this.destroyRef.onDestroy(() => { - this.viewportResizeObserver?.disconnect(); - if (this.pendingViewportRefresh !== undefined) { - window.cancelAnimationFrame(this.pendingViewportRefresh); - } + this.scrollService.trackRoute({ + scrollElement: this.scrollElement, + route: this.activatedRoute, + destroyRef: this.destroyRef, }); this.filterOptions = [ @@ -197,8 +163,6 @@ export class SeriesBrowserComponent implements OnInit { ]; } - - onSearchChange(value: string): void { this.searchTerm.set(value); } @@ -211,41 +175,30 @@ export class SeriesBrowserComponent implements OnInit { this.sortBy.set(value); } - navigateToSeries(series: SeriesSummary): void { - this.router.navigate(['/series', series.seriesName]); - } - - private measureViewportWidth(el: HTMLElement, entry?: ResizeObserverEntry): number { - const style = getComputedStyle(el); - const horizontalPadding = this.parsePixelValue(style.paddingLeft) + this.parsePixelValue(style.paddingRight); - const observedWidth = entry?.contentRect.width ?? el.clientWidth - horizontalPadding; - return Math.max(0, Math.floor(observedWidth)); - } - - private parsePixelValue(value: string): number { - const parsed = Number.parseFloat(value); - return Number.isFinite(parsed) ? parsed : 0; - } - - private scheduleViewportRefresh(): void { - if (this.pendingViewportRefresh !== undefined) { - return; - } - - this.pendingViewportRefresh = window.requestAnimationFrame(() => { - this.pendingViewportRefresh = undefined; - this.refreshViewport(); + 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, + SeriesBrowserComponent.GRID_GAP, + columns, + this.baseCardWidth(), + SeriesBrowserComponent.MIN_SCALE, + SeriesBrowserComponent.MAX_SCALE + )); }); } - private refreshViewport(): void { - if (!this.virtualScroller) { - return; - } + private setScale(scale: number): void { + this.scalePreference.setScale(scale); + } - const el = this.virtualScroller.elementRef.nativeElement as HTMLElement; - this.viewportWidth.set(this.measureViewportWidth(el)); - this.virtualScroller.checkViewportSize(); + navigateToSeries(series: SeriesSummary): void { + this.router.navigate(['/series', series.seriesName]); } private applyStatusFilter(series: SeriesSummary[], filterValue: string): SeriesSummary[] { diff --git a/frontend/src/app/features/series-browser/service/series-scale-preference.service.spec.ts b/frontend/src/app/features/series-browser/service/series-scale-preference.service.spec.ts deleted file mode 100644 index 79aad66e2..000000000 --- a/frontend/src/app/features/series-browser/service/series-scale-preference.service.spec.ts +++ /dev/null @@ -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); - }); -}); diff --git a/frontend/src/app/features/series-browser/service/series-scale-preference.service.ts b/frontend/src/app/features/series-browser/service/series-scale-preference.service.ts deleted file mode 100644 index 81abf4d2e..000000000 --- a/frontend/src/app/features/series-browser/service/series-scale-preference.service.ts +++ /dev/null @@ -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 | 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(this.STORAGE_KEY); - if (saved !== null && !isNaN(saved)) { - return saved; - } - return 1.0; - } -} diff --git a/frontend/src/app/shared/components/grid-density-buttons/grid-density-buttons.component.html b/frontend/src/app/shared/components/grid-density-buttons/grid-density-buttons.component.html new file mode 100644 index 000000000..0fb046f0b --- /dev/null +++ b/frontend/src/app/shared/components/grid-density-buttons/grid-density-buttons.component.html @@ -0,0 +1,17 @@ +
+ + +
diff --git a/frontend/src/app/shared/components/grid-density-buttons/grid-density-buttons.component.ts b/frontend/src/app/shared/components/grid-density-buttons/grid-density-buttons.component.ts new file mode 100644 index 000000000..344b5f5ab --- /dev/null +++ b/frontend/src/app/shared/components/grid-density-buttons/grid-density-buttons.component.ts @@ -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(); +} diff --git a/frontend/src/app/shared/service/route-scroll-position.service.spec.ts b/frontend/src/app/shared/service/route-scroll-position.service.spec.ts new file mode 100644 index 000000000..2d530ad5e --- /dev/null +++ b/frontend/src/app/shared/service/route-scroll-position.service.spec.ts @@ -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'); + }); +}); diff --git a/frontend/src/app/shared/service/route-scroll-position.service.ts b/frontend/src/app/shared/service/route-scroll-position.service.ts new file mode 100644 index 000000000..d0f6ef706 --- /dev/null +++ b/frontend/src/app/shared/service/route-scroll-position.service.ts @@ -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 | 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(); + + 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 { + 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); + } + }); + } +} diff --git a/frontend/src/app/shared/util/array.util.spec.ts b/frontend/src/app/shared/util/array.util.spec.ts deleted file mode 100644 index 4bd1a7bd5..000000000 --- a/frontend/src/app/shared/util/array.util.spec.ts +++ /dev/null @@ -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]]); - }); - }); -}); diff --git a/frontend/src/app/shared/util/array.util.ts b/frontend/src/app/shared/util/array.util.ts deleted file mode 100644 index ce7d1bf6c..000000000 --- a/frontend/src/app/shared/util/array.util.ts +++ /dev/null @@ -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(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; -} diff --git a/frontend/src/app/shared/util/scale-preference.util.ts b/frontend/src/app/shared/util/scale-preference.util.ts new file mode 100644 index 000000000..d8dbb71a4 --- /dev/null +++ b/frontend/src/app/shared/util/scale-preference.util.ts @@ -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; + readonly scaleFactor: Signal; + 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(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; + } +} diff --git a/frontend/src/app/shared/util/viewport.util.ts b/frontend/src/app/shared/util/viewport.util.ts deleted file mode 100644 index 5e6c8b034..000000000 --- a/frontend/src/app/shared/util/viewport.util.ts +++ /dev/null @@ -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))); -} diff --git a/frontend/src/app/shared/util/virtual-grid.util.ts b/frontend/src/app/shared/util/virtual-grid.util.ts new file mode 100644 index 000000000..45ed9deaf --- /dev/null +++ b/frontend/src/app/shared/util/virtual-grid.util.ts @@ -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; + scrollElement: Signal | undefined>; + minItemWidth: Signal; + estimateItemHeight: (itemWidth: number) => number; + gap: number | Signal; + overscan?: number; + count?: Signal; + columns?: Signal; + initialOffset?: () => number; + fillItemWidth?: boolean; + enabled?: Signal; +} + +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(() => ({ + 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, + }; +} diff --git a/frontend/src/i18n/da/common.json b/frontend/src/i18n/da/common.json index 7cf9004ca..5f65e8755 100644 --- a/frontend/src/i18n/da/common.json +++ b/frontend/src/i18n/da/common.json @@ -22,5 +22,8 @@ "dismiss": "", "discard": "", "review": "", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/de/common.json b/frontend/src/i18n/de/common.json index 383b275ab..aba97c927 100644 --- a/frontend/src/i18n/de/common.json +++ b/frontend/src/i18n/de/common.json @@ -22,5 +22,8 @@ "dismiss": "Verwerfen", "discard": "Verwerfen", "review": "Überprüfen", - "libraryPathInaccessible": "Der Pfad zur Bibliothek ist nicht zugreifbar" + "libraryPathInaccessible": "Der Pfad zur Bibliothek ist nicht zugreifbar", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/en/common.json b/frontend/src/i18n/en/common.json index 1ca397651..f6310900d 100644 --- a/frontend/src/i18n/en/common.json +++ b/frontend/src/i18n/en/common.json @@ -23,6 +23,9 @@ "discard": "Discard", "review": "Review", "libraryPathInaccessible": "Library path inaccessible", + "decreaseCardSize": "Decrease card size", + "increaseCardSize": "Increase card size", + "cardSizeControls": "Card size controls", "on": "On", "off": "Off" } diff --git a/frontend/src/i18n/es/common.json b/frontend/src/i18n/es/common.json index d01fe2579..670095586 100644 --- a/frontend/src/i18n/es/common.json +++ b/frontend/src/i18n/es/common.json @@ -22,5 +22,8 @@ "dismiss": "Descartar", "discard": "Descartar", "review": "Revisar", - "libraryPathInaccessible": "Ruta de biblioteca inaccesible" + "libraryPathInaccessible": "Ruta de biblioteca inaccesible", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/fr/common.json b/frontend/src/i18n/fr/common.json index ebece33fe..9f4ca8aa8 100644 --- a/frontend/src/i18n/fr/common.json +++ b/frontend/src/i18n/fr/common.json @@ -22,5 +22,8 @@ "dismiss": "Ignorer", "discard": "Abandonner", "review": "Vérifier", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/hr/common.json b/frontend/src/i18n/hr/common.json index 299e4a879..66fce4fa9 100644 --- a/frontend/src/i18n/hr/common.json +++ b/frontend/src/i18n/hr/common.json @@ -22,5 +22,8 @@ "dismiss": "Odbaci", "discard": "Odbaci", "review": "Pregledaj", - "libraryPathInaccessible": "Put do zbirke nije dostupan" + "libraryPathInaccessible": "Put do zbirke nije dostupan", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/hu/common.json b/frontend/src/i18n/hu/common.json index d87f1ffd2..1a6464903 100644 --- a/frontend/src/i18n/hu/common.json +++ b/frontend/src/i18n/hu/common.json @@ -22,5 +22,8 @@ "dismiss": "Ignorálás", "discard": "Elvetés", "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": "" } diff --git a/frontend/src/i18n/id/common.json b/frontend/src/i18n/id/common.json index 6c7471f63..ffe67b399 100644 --- a/frontend/src/i18n/id/common.json +++ b/frontend/src/i18n/id/common.json @@ -22,5 +22,8 @@ "dismiss": "Abaikan", "discard": "Buang", "review": "Tinjau", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/it/common.json b/frontend/src/i18n/it/common.json index 00d67ed4e..81b722d7d 100644 --- a/frontend/src/i18n/it/common.json +++ b/frontend/src/i18n/it/common.json @@ -22,5 +22,8 @@ "dismiss": "Ignora", "discard": "Scarta", "review": "Rivedi", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/ja/common.json b/frontend/src/i18n/ja/common.json index 19d1bd8da..1ec896d47 100644 --- a/frontend/src/i18n/ja/common.json +++ b/frontend/src/i18n/ja/common.json @@ -22,5 +22,8 @@ "dismiss": "閉じる", "discard": "破棄", "review": "確認", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/nl/common.json b/frontend/src/i18n/nl/common.json index 1de11ca3c..0e563e178 100644 --- a/frontend/src/i18n/nl/common.json +++ b/frontend/src/i18n/nl/common.json @@ -22,5 +22,8 @@ "dismiss": "Sluiten", "discard": "Verwerpen", "review": "Beoordelen", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/pl/common.json b/frontend/src/i18n/pl/common.json index 44b03fa60..9e99bc481 100644 --- a/frontend/src/i18n/pl/common.json +++ b/frontend/src/i18n/pl/common.json @@ -22,5 +22,8 @@ "dismiss": "Odrzuć", "discard": "Odrzuć", "review": "Przegląd", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/pt/common.json b/frontend/src/i18n/pt/common.json index aa5858c62..ed0cb9812 100644 --- a/frontend/src/i18n/pt/common.json +++ b/frontend/src/i18n/pt/common.json @@ -22,5 +22,8 @@ "dismiss": "Dispensar", "discard": "Descartar", "review": "Revisar", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/ru/common.json b/frontend/src/i18n/ru/common.json index 6b6e1fb75..122fe30d4 100644 --- a/frontend/src/i18n/ru/common.json +++ b/frontend/src/i18n/ru/common.json @@ -22,5 +22,8 @@ "dismiss": "Отклонить", "discard": "Отменить изменения", "review": "Просмотреть", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/sk/common.json b/frontend/src/i18n/sk/common.json index 643dfdbdf..d27f81589 100644 --- a/frontend/src/i18n/sk/common.json +++ b/frontend/src/i18n/sk/common.json @@ -22,5 +22,8 @@ "dismiss": "", "discard": "", "review": "", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/sl/common.json b/frontend/src/i18n/sl/common.json index 46273dbd5..078896f57 100644 --- a/frontend/src/i18n/sl/common.json +++ b/frontend/src/i18n/sl/common.json @@ -22,5 +22,8 @@ "dismiss": "Prezri", "discard": "Zavrzi", "review": "Preglej", - "libraryPathInaccessible": "Pot do knjižnice ni dostopna" + "libraryPathInaccessible": "Pot do knjižnice ni dostopna", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/sv/common.json b/frontend/src/i18n/sv/common.json index bb8d6da4c..bd5265ef9 100644 --- a/frontend/src/i18n/sv/common.json +++ b/frontend/src/i18n/sv/common.json @@ -22,5 +22,8 @@ "dismiss": "Stäng", "discard": "Förkasta", "review": "Granska", - "libraryPathInaccessible": "Bibliotekssökvägen är otillgänglig" + "libraryPathInaccessible": "Bibliotekssökvägen är otillgänglig", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/uk/common.json b/frontend/src/i18n/uk/common.json index 931f14ed6..08551a8ab 100644 --- a/frontend/src/i18n/uk/common.json +++ b/frontend/src/i18n/uk/common.json @@ -22,5 +22,8 @@ "dismiss": "Відхилити", "discard": "Відкинути", "review": "Перевірити", - "libraryPathInaccessible": "Шлях до бібліотеки недоступний" + "libraryPathInaccessible": "Шлях до бібліотеки недоступний", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/i18n/zh/common.json b/frontend/src/i18n/zh/common.json index 64f180468..4230abf6d 100644 --- a/frontend/src/i18n/zh/common.json +++ b/frontend/src/i18n/zh/common.json @@ -22,5 +22,8 @@ "dismiss": "忽略", "discard": "丢弃", "review": "审查", - "libraryPathInaccessible": "" + "libraryPathInaccessible": "", + "decreaseCardSize": "", + "increaseCardSize": "", + "cardSizeControls": "" } diff --git a/frontend/src/styles.scss b/frontend/src/styles.scss index 48be0996c..4593f7d33 100644 --- a/frontend/src/styles.scss +++ b/frontend/src/styles.scss @@ -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 { top: 4rem !important; } diff --git a/frontend/yarn.lock b/frontend/yarn.lock index a74902f0c..b4bd66b70 100644 --- a/frontend/yarn.lock +++ b/frontend/yarn.lock @@ -487,18 +487,6 @@ __metadata: languageName: node 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": version: 21.2.8 resolution: "@angular/cdk@npm:21.2.8" @@ -3870,6 +3858,18 @@ __metadata: languageName: node 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": version: 5.100.1 resolution: "@tanstack/query-core@npm:5.100.1" @@ -3884,6 +3884,13 @@ __metadata: languageName: node 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": version: 19.2.1 resolution: "@testing-library/angular@npm:19.2.1" @@ -6268,7 +6275,6 @@ __metadata: "@angular/animations": "npm:^21.2.10" "@angular/build": "npm:^21.2.8" "@angular/cdk": "npm:^21.2.8" - "@angular/cdk-experimental": "npm:^21.2.8" "@angular/cli": "npm:^21.2.8" "@angular/common": "npm:^21.2.10" "@angular/compiler": "npm:^21.2.10" @@ -6288,6 +6294,7 @@ __metadata: "@stomp/rx-stomp": "npm:^2.3.0" "@stomp/stompjs": "npm:^7.3.0" "@tanstack/angular-query-experimental": "npm:5.100.1" + "@tanstack/angular-virtual": "npm:^4.0.13" "@testing-library/angular": "npm:^19.2.1" "@testing-library/dom": "npm:^10.4.1" "@testing-library/jest-dom": "npm:^6.9.1"