refactor(ui): unify author/series/book browsers using tanstack virtual (#941)
This commit is contained in:
-33
@@ -1,33 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {BookBrowserScrollService} from './book-browser-scroll.service';
|
||||
|
||||
describe('BookBrowserScrollService', () => {
|
||||
const service = new BookBrowserScrollService();
|
||||
|
||||
it('stores, retrieves, clears, and creates stable keys', () => {
|
||||
expect(service.getPosition('books')).toBeUndefined();
|
||||
|
||||
service.savePosition('books', 144);
|
||||
service.savePosition('books:library', 288);
|
||||
|
||||
expect(service.getPosition('books')).toBe(144);
|
||||
expect(service.getPosition('books:library')).toBe(288);
|
||||
expect(service.createKey('/books', {libraryId: '1', shelfId: '2'})).toBe('/books:1-2');
|
||||
expect(service.createKey('/books', {})).toBe('/books');
|
||||
|
||||
service.clearPosition('books');
|
||||
expect(service.getPosition('books')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('clearAll removes all stored positions', () => {
|
||||
const fresh = new BookBrowserScrollService();
|
||||
fresh.savePosition('a', 10);
|
||||
fresh.savePosition('b', 20);
|
||||
|
||||
fresh.clearAll();
|
||||
|
||||
expect(fresh.getPosition('a')).toBeUndefined();
|
||||
expect(fresh.getPosition('b')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookBrowserScrollService {
|
||||
private scrollPositions = new Map<string, number>();
|
||||
|
||||
savePosition(key: string, position: number): void {
|
||||
this.scrollPositions.set(key, position);
|
||||
}
|
||||
|
||||
getPosition(key: string): number | undefined {
|
||||
return this.scrollPositions.get(key);
|
||||
}
|
||||
|
||||
clearPosition(key: string): void {
|
||||
this.scrollPositions.delete(key);
|
||||
}
|
||||
|
||||
clearAll(): void {
|
||||
this.scrollPositions.clear();
|
||||
}
|
||||
|
||||
createKey(path: string, params: Record<string, string>): string {
|
||||
const paramValues = Object.values(params).join('-');
|
||||
return paramValues ? `${path}:${paramValues}` : path;
|
||||
}
|
||||
}
|
||||
+68
-76
@@ -124,20 +124,20 @@
|
||||
@if (isMobile()) {
|
||||
<div class="display-settings-section">
|
||||
<span class="display-settings-label">{{ t('labels.gridColumns') }}</span>
|
||||
<div class="column-options">
|
||||
<div class="browser-grid-options">
|
||||
<button
|
||||
type="button"
|
||||
class="column-option-btn"
|
||||
class="browser-grid-option-btn"
|
||||
[class.active]="mobileColumnCount() === 2"
|
||||
(click)="setMobileColumns(2)">2</button>
|
||||
<button
|
||||
type="button"
|
||||
class="column-option-btn"
|
||||
class="browser-grid-option-btn"
|
||||
[class.active]="mobileColumnCount() === 3"
|
||||
(click)="setMobileColumns(3)">3</button>
|
||||
<button
|
||||
type="button"
|
||||
class="column-option-btn"
|
||||
class="browser-grid-option-btn"
|
||||
[class.active]="mobileColumnCount() === 4"
|
||||
(click)="setMobileColumns(4)">4</button>
|
||||
</div>
|
||||
@@ -145,17 +145,7 @@
|
||||
} @else {
|
||||
<div class="display-settings-section">
|
||||
<span class="display-settings-label">{{ t('labels.gridItemSize') }}</span>
|
||||
<p-slider
|
||||
[ngModel]="coverScalePreferenceService.scaleFactor()"
|
||||
(ngModelChange)="coverScalePreferenceService.setScale($event)"
|
||||
[min]="0.5"
|
||||
[max]="1.5"
|
||||
[step]="0.01"
|
||||
[style]="{ width: '100%' }">
|
||||
</p-slider>
|
||||
<div class="scale-value-display">
|
||||
{{ coverScalePreferenceService.scaleFactor().toFixed(2) }}x
|
||||
</div>
|
||||
<app-grid-density-buttons (densityChange)="adjustDesktopGridDensity($event)"/>
|
||||
</div>
|
||||
}
|
||||
<div class="display-settings-section">
|
||||
@@ -280,13 +270,16 @@
|
||||
}
|
||||
</div>
|
||||
} @else if (showGridLoadingPlaceholder()) {
|
||||
<div class="skeleton-grid"
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth() + ', 1fr))'}">
|
||||
@for (item of skeletonSlots; track item) {
|
||||
<div class="skeleton-card"
|
||||
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
|
||||
</div>
|
||||
}
|
||||
<div #scrollElement class="virtual-scroller">
|
||||
<div class="skeleton-grid"
|
||||
[style.grid-template-columns]="'repeat(auto-fill, minmax(' + skeletonMinCardWidth() + ', 1fr))'">
|
||||
@for (item of skeletonSlots; track item) {
|
||||
<div class="skeleton-card"
|
||||
[style.width.px]="currentCardSize().width"
|
||||
[style.height.px]="currentCardSize().height">
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
} @else if (booksError()) {
|
||||
<div class="no-books-container">
|
||||
@@ -294,59 +287,60 @@
|
||||
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
|
||||
</p>
|
||||
</div>
|
||||
} @else if (books(); as books) {
|
||||
<div class="book-state-wrapper">
|
||||
<div
|
||||
class="book-state-content"
|
||||
[attr.aria-busy]="isBooksRefreshing() ? 'true' : 'false'"
|
||||
[class.book-state-content-refreshing]="isBooksRefreshing()"
|
||||
[attr.inert]="isBooksRefreshing() ? '' : null">
|
||||
@if (books.length === 0 && !isBooksLoading()) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
{{ t('labels.noBooks') }}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
@if (currentViewMode() === 'table' && books.length > 0) {
|
||||
<app-book-table
|
||||
[books]="books"
|
||||
[preselectedBookIds]="selectedBooks()"
|
||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||
(selectAllRequested)="selectAllBooks()"
|
||||
[sortOption]="this.bookSorter.selectedSort!"
|
||||
[visibleColumns]="visibleColumns()"
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode() === 'grid') {
|
||||
<div class="virtual-scroller" #scrollContainer>
|
||||
<div class="scroll-height-anchor" [ngStyle]="{'min-height': estimatedTotalHeight() + 'px'}">
|
||||
<div class="book-grid"
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth() + ', 1fr))'}">
|
||||
@for (book of books; track book.id; let i = $index) {
|
||||
<div
|
||||
class="virtual-scroller-item"
|
||||
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
|
||||
<app-book-card
|
||||
[index]="i"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[seriesViewEnabled]="seriesViewEnabled()"
|
||||
[onBookSelect]="onBookCardSelect"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="bookSelectionService.isBookSelected(book)"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary()"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
}
|
||||
} @else {
|
||||
@let visibleBooks = books();
|
||||
@if (visibleBooks.length === 0 && !isBooksLoading()) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
{{ t('labels.noBooks') }}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
@if (currentViewMode() === 'table' && visibleBooks.length > 0) {
|
||||
<app-book-table
|
||||
[books]="visibleBooks"
|
||||
[preselectedBookIds]="selectedBooks()"
|
||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||
(selectAllRequested)="selectAllBooks()"
|
||||
[sortOption]="this.bookSorter.selectedSort!"
|
||||
[visibleColumns]="visibleColumns()"
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode() === 'grid') {
|
||||
<div #scrollElement class="virtual-scroller">
|
||||
<div class="virtual-content" [style.height.px]="virtualGrid.virtualizer.getTotalSize()">
|
||||
@for (virtualItem of virtualGrid.virtualizer.getVirtualItems(); track virtualItem.key) {
|
||||
@if (visibleBooks[virtualItem.index]; as book) {
|
||||
<div
|
||||
class="virtual-cell"
|
||||
[style.width.px]="virtualGrid.itemWidth()"
|
||||
[style.height.px]="virtualItem.size"
|
||||
[style.transform]="virtualGrid.itemTransform(virtualItem)">
|
||||
<app-book-card
|
||||
[index]="virtualItem.index"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[seriesViewEnabled]="seriesViewEnabled()"
|
||||
[onBookSelect]="onBookCardSelect"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="bookSelectionService.isBookSelected(book)"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary()"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
<div class="scroll-sentinel" #scrollSentinel></div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (userService.currentUser(); as currentUser) {
|
||||
} @else {
|
||||
<div
|
||||
class="virtual-cell virtual-loader-cell"
|
||||
[style.width.px]="virtualGrid.itemWidth()"
|
||||
[style.height.px]="virtualItem.size"
|
||||
[style.transform]="virtualGrid.itemTransform(virtualItem)"></div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (userService.currentUser(); as currentUser) {
|
||||
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
||||
<div class="footer-content">
|
||||
<div class="footer-left">
|
||||
@@ -469,8 +463,6 @@
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
// Skeleton loader — opacity animation runs on the compositor thread
|
||||
// so it stays smooth while the main thread computes books.
|
||||
.skeleton-grid {
|
||||
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;
|
||||
}
|
||||
|
||||
+60
-67
@@ -1,4 +1,4 @@
|
||||
import {computed, ElementRef, signal, WritableSignal} from '@angular/core';
|
||||
import {computed, signal, WritableSignal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {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<string | null>;
|
||||
isBooksLoading: WritableSignal<boolean>;
|
||||
paramMap$: BehaviorSubject<ParamMap>;
|
||||
setHasNextPage: (value: boolean) => void;
|
||||
queryParamsService: {
|
||||
shouldForceExpandSeries: ReturnType<typeof vi.fn>;
|
||||
updateViewMode: ReturnType<typeof vi.fn>;
|
||||
@@ -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<string | null>(options?.booksError ?? null);
|
||||
const isBooksLoading = signal<boolean>(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<AppBookFilters>({});
|
||||
const _sort = signal<AppBookSort>({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<HTMLElement>;
|
||||
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
|
||||
+144
-259
@@ -1,11 +1,11 @@
|
||||
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, computed, effect, inject, signal, untracked, ViewChild} from '@angular/core';
|
||||
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, computed, effect, inject, signal, viewChild} from '@angular/core';
|
||||
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||
import {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<Book[]>();
|
||||
readonly books = this.booksRenderState.value;
|
||||
readonly hasRenderedBooks = this.booksRenderState.hasValue;
|
||||
readonly isBooksRefreshing = this.booksRenderState.isRefreshing;
|
||||
|
||||
private lastBooksContextKey: string | null = null;
|
||||
private readonly booksContextKey = computed(() => {
|
||||
const {entityId, entityType} = this.entityInfo();
|
||||
return Number.isNaN(entityId) ? entityType : `${entityType}:${entityId}`;
|
||||
});
|
||||
|
||||
private readonly pipelineInputs = computed(() => {
|
||||
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<number, number>();
|
||||
const map = new Map<number, number>();
|
||||
for (let i = 0; i < books.length; i++) {
|
||||
map.set(books[i].id, i);
|
||||
}
|
||||
return map;
|
||||
});
|
||||
readonly compareBookItems = (a: Book, b: Book): boolean => a?.id === b?.id;
|
||||
|
||||
private readonly GRID_GAP = 21;
|
||||
private readonly 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<ElementRef<HTMLElement>>('scrollElement');
|
||||
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute)) ?? 0;
|
||||
private readonly gridBooks = this.books;
|
||||
private readonly desktopBaseCardWidth = computed(() =>
|
||||
this.isAudiobookOnlyLibrary()
|
||||
? this.DESKTOP_CARD_BASE_WIDTH * 1.1
|
||||
: this.DESKTOP_CARD_BASE_WIDTH
|
||||
);
|
||||
private readonly minCardWidth = computed(() =>
|
||||
this.isMobile()
|
||||
? 1
|
||||
: Math.round(this.desktopBaseCardWidth() * this.coverScalePreferenceService.scaleFactor())
|
||||
);
|
||||
private readonly virtualGridGap = computed(() => this.isMobile() ? this.MOBILE_GAP : this.GRID_GAP);
|
||||
private readonly virtualGridColumns = computed(() => this.isMobile() ? this.mobileColumnCount() : undefined);
|
||||
private readonly isGridView = computed(() => this.currentViewMode() === VIEW_MODES.GRID);
|
||||
private readonly virtualBookCount = computed(() => {
|
||||
const renderedBookCount = this.gridBooks().length;
|
||||
return this.appBooksApi.hasNextPage()
|
||||
? Math.max(this.appBooksApi.totalElements(), renderedBookCount)
|
||||
: renderedBookCount;
|
||||
});
|
||||
|
||||
/**
|
||||
* 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<HTMLElement> | undefined) {
|
||||
this.containerResizeObserver?.disconnect();
|
||||
if (this.scrollContainer) {
|
||||
this.scrollContainer.removeEventListener('scroll', this.onScroll);
|
||||
}
|
||||
this.scrollContainer = ref?.nativeElement;
|
||||
if (this.scrollContainer) {
|
||||
const el = this.scrollContainer;
|
||||
this.containerWidth.set(el.clientWidth);
|
||||
this.containerResizeObserver = new ResizeObserver(entries => {
|
||||
this.containerWidth.set(entries[0]?.contentRect.width ?? el.clientWidth);
|
||||
});
|
||||
this.containerResizeObserver.observe(el);
|
||||
el.addEventListener('scroll', this.onScroll, {passive: true});
|
||||
// Initial check in case we are already scrolled down
|
||||
globalThis.requestAnimationFrame(() => this.checkAndFetchIfNeeded());
|
||||
}
|
||||
}
|
||||
|
||||
@ViewChild('scrollSentinel')
|
||||
set scrollSentinelRef(ref: ElementRef<HTMLElement> | undefined) {
|
||||
this.sentinelObserver?.disconnect();
|
||||
const el = ref?.nativeElement;
|
||||
if (el) {
|
||||
this.sentinelObserver = new IntersectionObserver(
|
||||
entries => {
|
||||
if (entries[0]?.isIntersecting) {
|
||||
this.checkAndFetchNextPage();
|
||||
}
|
||||
},
|
||||
{root: this.scrollContainer, rootMargin: '600px'}
|
||||
);
|
||||
this.sentinelObserver.observe(el);
|
||||
}
|
||||
}
|
||||
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<number>(this.MOBILE_COLUMNS_STORAGE_KEY);
|
||||
if (saved !== null && [2, 3, 4].includes(saved)) {
|
||||
|
||||
-7
@@ -110,13 +110,6 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
this.selectedBookIds = new Set(this.preselectedBookIds);
|
||||
this.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 {
|
||||
|
||||
+17
-50
@@ -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<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
|
||||
let messageService: { add: ReturnType<typeof vi.fn> };
|
||||
let translocoService: { translate: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
localStorageService = {
|
||||
get: vi.fn(),
|
||||
set: vi.fn()
|
||||
};
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
translocoService = {
|
||||
translate: vi.fn((key: string, params?: Record<string, unknown>) =>
|
||||
params ? `${key}:${JSON.stringify(params)}` : `t:${key}`
|
||||
)
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
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
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
+11
-72
@@ -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<typeof setTimeout> | null = null;
|
||||
private lastPersistedScale = 1.0;
|
||||
|
||||
constructor() {
|
||||
const initialScale = this.loadScaleFromStorage();
|
||||
this._scaleFactor.set(initialScale);
|
||||
this.lastPersistedScale = initialScale;
|
||||
}
|
||||
|
||||
setScale(scale: number): void {
|
||||
this._scaleFactor.set(scale);
|
||||
if (scale === this.lastPersistedScale) {
|
||||
return;
|
||||
}
|
||||
this.scheduleSave(scale);
|
||||
}
|
||||
|
||||
getCardHeight(_book: Book): number {
|
||||
void _book;
|
||||
// Use uniform height for all book types to ensure smooth virtual scrolling.
|
||||
// Mixed heights cause choppy/jumpy scrolling because the virtual scroller
|
||||
// cannot accurately estimate positions when item heights vary.
|
||||
return this.currentCardSize().height;
|
||||
}
|
||||
|
||||
private scheduleSave(scale: number): void {
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
}
|
||||
|
||||
this.saveTimeout = setTimeout(() => {
|
||||
this.saveScalePreference(scale);
|
||||
}, this.DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
private saveScalePreference(scale: number): void {
|
||||
try {
|
||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
||||
this.lastPersistedScale = scale;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.coverPref.toast.savedSummary'),
|
||||
detail: this.t.translate('book.coverPref.toast.savedDetail', {scale: scale.toFixed(2)}),
|
||||
life: 1500
|
||||
});
|
||||
} catch {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.coverPref.toast.saveFailedSummary'),
|
||||
detail: this.t.translate('book.coverPref.toast.saveFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private loadScaleFromStorage(): number {
|
||||
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
||||
if (saved !== null && !isNaN(saved)) {
|
||||
return saved;
|
||||
}
|
||||
return 1.0;
|
||||
this.scalePreference.setScale(scale);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {DeferredRenderState} from './deferred-render-state';
|
||||
|
||||
describe('DeferredRenderState', () => {
|
||||
it('clears the current value for reset runs', () => {
|
||||
const state = new DeferredRenderState<number[]>();
|
||||
|
||||
const initialRequest = state.begin('reset');
|
||||
state.commit(initialRequest, [1, 2, 3]);
|
||||
|
||||
expect(state.value()).toEqual([1, 2, 3]);
|
||||
expect(state.hasValue()).toBe(true);
|
||||
|
||||
state.begin('reset');
|
||||
|
||||
expect(state.value()).toBeUndefined();
|
||||
expect(state.hasValue()).toBe(false);
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the current value visible during refresh runs', () => {
|
||||
const state = new DeferredRenderState<number[]>();
|
||||
|
||||
const initialRequest = state.begin('reset');
|
||||
state.commit(initialRequest, [1, 2, 3]);
|
||||
|
||||
const refreshRequest = state.begin('refresh');
|
||||
|
||||
expect(state.value()).toEqual([1, 2, 3]);
|
||||
expect(state.isRefreshing()).toBe(true);
|
||||
|
||||
state.commit(refreshRequest, [4, 5]);
|
||||
|
||||
expect(state.value()).toEqual([4, 5]);
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores stale commits from older requests', () => {
|
||||
const state = new DeferredRenderState<number[]>();
|
||||
|
||||
const initialRequest = state.begin('reset');
|
||||
state.commit(initialRequest, [1]);
|
||||
|
||||
const staleRefresh = state.begin('refresh');
|
||||
const latestRefresh = state.begin('refresh');
|
||||
|
||||
expect(state.commit(staleRefresh, [2])).toBe(false);
|
||||
expect(state.value()).toEqual([1]);
|
||||
expect(state.isRefreshing()).toBe(true);
|
||||
|
||||
expect(state.commit(latestRefresh, [3])).toBe(true);
|
||||
expect(state.value()).toEqual([3]);
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores cancel with a stale request id', () => {
|
||||
const state = new DeferredRenderState<number[]>();
|
||||
|
||||
const first = state.begin('reset');
|
||||
state.commit(first, [1]);
|
||||
|
||||
const stale = state.begin('refresh');
|
||||
const current = state.begin('refresh');
|
||||
|
||||
state.cancel(stale);
|
||||
|
||||
// Cancel was a no-op — isRefreshing still true from the current request
|
||||
expect(state.isRefreshing()).toBe(true);
|
||||
expect(state.value()).toEqual([1]);
|
||||
|
||||
state.commit(current, [2]);
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
expect(state.value()).toEqual([2]);
|
||||
});
|
||||
|
||||
it('cancel during a reset leaves value undefined', () => {
|
||||
const state = new DeferredRenderState<number[]>();
|
||||
|
||||
const request = state.begin('reset');
|
||||
|
||||
expect(state.value()).toBeUndefined();
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
|
||||
state.cancel(request);
|
||||
|
||||
expect(state.value()).toBeUndefined();
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
});
|
||||
|
||||
it('does not set isRefreshing when no value exists yet', () => {
|
||||
const state = new DeferredRenderState<number[]>();
|
||||
|
||||
const request = state.begin('refresh');
|
||||
|
||||
// No prior value, so nothing to "refresh" — isRefreshing stays false
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
expect(state.value()).toBeUndefined();
|
||||
expect(state.hasValue()).toBe(false);
|
||||
|
||||
state.commit(request, [1]);
|
||||
expect(state.value()).toEqual([1]);
|
||||
expect(state.isRefreshing()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
import {computed, signal} from '@angular/core';
|
||||
|
||||
export type DeferredRenderMode = 'reset' | 'refresh';
|
||||
|
||||
export class DeferredRenderState<T> {
|
||||
private readonly _value = signal<T | undefined>(undefined);
|
||||
readonly value = this._value.asReadonly();
|
||||
|
||||
private readonly _isRefreshing = signal(false);
|
||||
readonly isRefreshing = this._isRefreshing.asReadonly();
|
||||
|
||||
readonly hasValue = computed(() => this._value() !== undefined);
|
||||
|
||||
private activeRequestId = 0;
|
||||
|
||||
begin(mode: DeferredRenderMode): number {
|
||||
this.activeRequestId += 1;
|
||||
|
||||
if (mode === 'reset') {
|
||||
this._value.set(undefined);
|
||||
this._isRefreshing.set(false);
|
||||
} else {
|
||||
this._isRefreshing.set(this._value() !== undefined);
|
||||
}
|
||||
|
||||
return this.activeRequestId;
|
||||
}
|
||||
|
||||
/** Direct update without refresh animation used for in-place data swaps. */
|
||||
update(value: T): void {
|
||||
this._value.set(value);
|
||||
this._isRefreshing.set(false);
|
||||
}
|
||||
|
||||
commit(requestId: number, value: T): boolean {
|
||||
if (requestId !== this.activeRequestId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._value.set(value);
|
||||
this._isRefreshing.set(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
cancel(requestId: number): void {
|
||||
if (requestId !== this.activeRequestId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._isRefreshing.set(false);
|
||||
}
|
||||
}
|
||||
@@ -279,11 +279,13 @@
|
||||
<i class="pi pi-objects-column"></i>
|
||||
{{ t('booksInSeries') }}
|
||||
</h3>
|
||||
@let cardSize = currentCardSize;
|
||||
<div class="series-items-grid" #Container
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
[style.grid-template-columns]="'repeat(auto-fill, minmax(' + cardSize.width + 'px, 1fr))'">
|
||||
@for (book of books; track book; let i = $index) {
|
||||
<div class="grid-item"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||
[style.width.px]="cardSize.width"
|
||||
[style.height.px]="cardSize.height">
|
||||
<app-book-card
|
||||
[index]="i"
|
||||
[book]="book"
|
||||
|
||||
@@ -365,10 +365,6 @@ export class SeriesPageComponent implements AfterViewChecked {
|
||||
return this.coverScalePreferenceService.currentCardSize();
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return this.coverScalePreferenceService.gridColumnMinWidth();
|
||||
}
|
||||
|
||||
goToAuthorBooks(author: string): void {
|
||||
this.authorService.getAuthorByName(author).subscribe({
|
||||
next: (authorDetails) => {
|
||||
|
||||
Reference in New Issue
Block a user