refactor(ui): restore deferred render state service (#1255)

This commit is contained in:
Alex
2026-05-10 17:49:47 +01:00
committed by GitHub
parent 1042cad74a
commit cac86818c5
4 changed files with 120 additions and 25 deletions
@@ -21,7 +21,7 @@
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive() || hasSearchTerm()) ? ' ' + t('labels.filteredSuffix') : '' }}
}
</p>
@if (!isBooksLoading() && seriesCollapseFilter.seriesCollapsed() && books(); as books) {
@if (!showBooksLoadingPlaceholder() && seriesCollapseFilter.seriesCollapsed() && books(); as books) {
<p class="series-collapsed-info">
{{ t('labels.seriesCollapsedInfo', { count: books.length, itemWord: books.length === 1 ? t('labels.item') : t('labels.items') }) }}
</p>
@@ -252,7 +252,7 @@
} @else {
<div class="book-browser-content">
@let visibleBooks = books();
@if (visibleBooks.length === 0 && !isBooksLoading()) {
@if (visibleBooks.length === 0 && !showBooksLoadingPlaceholder()) {
<div class="no-books-container">
<p class="no-books-text">
{{ t('labels.noBooks') }}
@@ -388,6 +388,7 @@ describe('BookBrowserComponent', () => {
const {component} = createHarness();
TestBed.flushEffects();
vi.runOnlyPendingTimers();
expect(component.books().map(book => book.id)).toEqual([2, 1]);
@@ -395,6 +396,7 @@ describe('BookBrowserComponent', () => {
{label: 'Title', field: 'title', direction: SortDirection.ASCENDING},
]);
TestBed.flushEffects();
vi.runOnlyPendingTimers();
expect(component.books().map(book => book.id)).toEqual([1, 2]);
});
@@ -403,6 +405,7 @@ describe('BookBrowserComponent', () => {
const {component, paramMap$, routeSnapshot} = createHarness();
TestBed.flushEffects();
vi.runOnlyPendingTimers();
expect(component.books().map(book => book.id)).toEqual([2, 1]);
@@ -410,6 +413,7 @@ describe('BookBrowserComponent', () => {
routeSnapshot.params = {libraryId: '2'};
paramMap$.next(routeSnapshot.paramMap);
TestBed.flushEffects();
vi.runOnlyPendingTimers();
expect(component.books().map(book => book.id)).toEqual([3]);
});
@@ -424,6 +428,24 @@ describe('BookBrowserComponent', () => {
expect(component.showTableLoadingPlaceholder()).toBe(false);
});
it('keeps rendered books visible when loading starts after the first render', () => {
const renderedBooks = Array.from({length: 30}, (_, index) =>
makeBook(index + 1, 1, `Book ${index + 1}`, `2024-01-${String(index + 1).padStart(2, '0')}T00:00:00Z`)
);
const {component, isBooksLoading} = createHarness({books: renderedBooks});
TestBed.flushEffects();
vi.runOnlyPendingTimers();
expect(component.books()).toHaveLength(30);
expect(component.virtualRowCount()).toBe(30);
isBooksLoading.set(true);
expect(component.showBooksLoadingPlaceholder()).toBe(false);
expect(component.virtualRowCount()).toBe(30);
});
it('sizes grid loading placeholders to fill the viewport', () => {
const {component} = createHarness({books: [], isBooksLoading: true});
const loadingGrid = component as unknown as {
@@ -1,4 +1,4 @@
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, computed, effect, inject, signal, viewChild} from '@angular/core';
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, computed, effect, inject, signal, untracked, viewChild} from '@angular/core';
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
import {ActivatedRoute} from '@angular/router';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
@@ -58,6 +58,7 @@ import {filterBooksBySearchTerm} from './filters/HeaderFilter';
import {filterBooksByFilters} from './filters/sidebar-filter';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {createGridDensity} from '../../../../shared/util/grid-density.util';
import {DeferredRenderState} from './deferred-render-state';
export enum EntityType {
LIBRARY = 'Library',
@@ -200,29 +201,51 @@ export class BookBrowserComponent implements AfterViewInit {
return actions;
});
// --- Layered pipeline: each computed only recomputes when its direct inputs change ---
private readonly entityBooks = computed(() => {
const {entityId, entityType} = this.entityInfo();
return this.entityService.getBooksByEntity(this.bookService.books(), entityId, entityType);
});
private readonly searchedBooks = computed(() =>
filterBooksBySearchTerm(this.entityBooks(), this.debouncedSearchTerm())
);
private readonly filteredBooks = computed(() =>
filterBooksByFilters(this.searchedBooks(), this.selectedFilter(), this.selectedFilterMode())
);
// Deferred pipeline: heavy filter/sort runs in a setTimeout so the page chrome
// and skeletons paint first, then real books replace them on the next task.
private readonly forceExpandSeries = computed(() =>
this.queryParamsService.shouldForceExpandSeries(this.queryParamMap())
);
private readonly collapsedBooks = computed(() =>
this.seriesCollapseFilter.collapseBooks(
this.filteredBooks(), this.forceExpandSeries(), this.seriesCollapsed()
)
);
private readonly booksContextKey = computed(() => {
const {entityId, entityType} = this.entityInfo();
return Number.isNaN(entityId) ? entityType : `${entityType}:${entityId}`;
});
private lastBooksContextKey: string | null = null;
private readonly booksRenderState = new DeferredRenderState<Book[]>();
readonly books = computed(() => this.booksRenderState.value() ?? []);
readonly hasRenderedBooks = this.booksRenderState.hasValue;
readonly isBooksRefreshing = this.booksRenderState.isRefreshing;
readonly books = computed(() =>
this.sortService.applyMultiSort(this.collapsedBooks(), this.sortCriteria())
);
private readonly computeBooksEffect = effect((onCleanup) => {
const contextKey = this.booksContextKey();
const allBooks = this.bookService.books();
const {entityId, entityType} = this.entityInfo();
const searchTerm = this.debouncedSearchTerm();
const filters = this.selectedFilter();
const filterMode = this.selectedFilterMode();
const collapsedFlag = this.seriesCollapsed();
const forceExpand = this.forceExpandSeries();
const sortCriteria = this.sortCriteria();
const sameContext = contextKey === this.lastBooksContextKey;
const shouldRefresh = sameContext && untracked(() => this.hasRenderedBooks());
const requestId = this.booksRenderState.begin(shouldRefresh ? 'refresh' : 'reset');
this.lastBooksContextKey = contextKey;
const timeoutId = globalThis.setTimeout(() => {
const entityBooks = this.entityService.getBooksByEntity(allBooks, entityId, entityType);
const searched = filterBooksBySearchTerm(entityBooks, searchTerm);
const filtered = filterBooksByFilters(searched, filters, filterMode);
const collapsed = this.seriesCollapseFilter.collapseBooks(filtered, forceExpand, collapsedFlag);
const sorted = this.sortService.applyMultiSort(collapsed, sortCriteria);
this.booksRenderState.commit(requestId, sorted);
});
onCleanup(() => {
globalThis.clearTimeout(timeoutId);
this.booksRenderState.cancel(requestId);
});
});
readonly isBooksLoading = this.bookService.isBooksLoading;
readonly booksError = this.bookService.booksError;
@@ -447,7 +470,7 @@ export class BookBrowserComponent implements AfterViewInit {
}
readonly showBooksLoadingPlaceholder = computed(() =>
!this.booksError() && this.isBooksLoading() && this.books().length === 0
!this.booksError() && (!this.hasRenderedBooks() || (this.isBooksLoading() && this.books().length === 0))
);
readonly showTableLoadingPlaceholder = computed(() =>
@@ -666,9 +689,13 @@ export class BookBrowserComponent implements AfterViewInit {
}
selectAllBooks(): void {
this.bookSelectionService.selectAll(
this.filteredBooks().map(b => b.id)
const {entityId, entityType} = this.entityInfo();
const entityBooks = this.entityService.getBooksByEntity(
this.bookService.books(), entityId, entityType
);
const searched = filterBooksBySearchTerm(entityBooks, this.debouncedSearchTerm());
const filtered = filterBooksByFilters(searched, this.selectedFilter(), this.selectedFilterMode());
this.bookSelectionService.selectAll(filtered.map(b => b.id));
}
loadNextBooksPage(): void {
@@ -0,0 +1,46 @@
import {computed, signal, untracked} 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(untracked(() => this._value() !== undefined));
}
return this.activeRequestId;
}
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);
}
}