refactor(api): optimize caching mechanisms and improve book filtering (#372)
* refactor(api): optimize caching mechanisms and improve book filtering logic * refactor(preferences): remove unused ExternalDocLinkComponent and enhance translate function typing * refactor(initializer): add Duration import for improved cache management * refactor(docker): increase MaxMetaspaceSize for improved memory management * refactor(repository): replace findAllForSummaryByIds with findAllById * refactor(cache): implement invalidateAppBooksQueries for improved cache management * refactor(AppBookService): increase default page size and optimize magic shelf book resolution * refactor(AppBookSpecification, MagicShelfBookService, TaskCancellationManager, magic-shelf-component): streamline join handling and improve memory management * refactor(AppBookService, MagicShelfBookService): enhance book retrieval logic and improve error handling * chore: fix formatting * chore: fix formatting
This commit is contained in:
@@ -318,7 +318,7 @@
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode === 'grid') {
|
||||
<virtual-scroller class="virtual-scroller" #scroll [items]="books" [bufferAmount]="16">
|
||||
<virtual-scroller class="virtual-scroller" #scroll [items]="books" [bufferAmount]="16" (vsEnd)="onScrollEnd()">
|
||||
<div
|
||||
class="grid"
|
||||
#container
|
||||
|
||||
+42
-1
@@ -1,4 +1,4 @@
|
||||
import {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';
|
||||
@@ -31,6 +31,8 @@ import {AppSettingsService} from '../../../../shared/service/app-settings.servic
|
||||
import {BookBrowserComponent, EntityType} from './book-browser.component';
|
||||
import {SortService} from '../../service/sort.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {AppBooksApiService} from '../../service/app-books-api.service';
|
||||
import {AppBookFilters, AppBookSort} from '../../model/app-book.model';
|
||||
|
||||
function makeBook(id: number, libraryId: number, title: string, addedOn: string): Book {
|
||||
return {
|
||||
@@ -239,6 +241,45 @@ function createHarness(options?: {
|
||||
booksError: booksError.asReadonly(),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: AppBooksApiService,
|
||||
useFactory: () => {
|
||||
const _filters = signal<AppBookFilters>({});
|
||||
const _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
|
||||
const _search = signal('');
|
||||
|
||||
const filteredSortedBooks = computed(() => {
|
||||
let result = books();
|
||||
const f = _filters();
|
||||
if (f.libraryId) result = result.filter(b => b.libraryId === f.libraryId);
|
||||
|
||||
const s = _sort();
|
||||
const dir = s.dir === 'asc' ? 1 : -1;
|
||||
result = [...result].sort((a, b) => {
|
||||
if (s.field === 'title') return dir * ((a.metadata?.title ?? '') as string).localeCompare((b.metadata?.title ?? '') as string);
|
||||
if (s.field === 'addedOn') return dir * (a.addedOn ?? '').localeCompare(b.addedOn ?? '');
|
||||
return 0;
|
||||
});
|
||||
return result;
|
||||
});
|
||||
|
||||
return {
|
||||
books: filteredSortedBooks,
|
||||
totalElements: computed(() => filteredSortedBooks().length),
|
||||
hasNextPage: computed(() => false),
|
||||
isLoading: isBooksLoading.asReadonly(),
|
||||
isFetchingNextPage: computed(() => false),
|
||||
isError: computed(() => !!booksError()),
|
||||
error: computed(() => booksError()),
|
||||
filterOptions: computed(() => null),
|
||||
setFilters: (f: AppBookFilters) => _filters.set(f),
|
||||
setSort: (s: AppBookSort) => _sort.set(s),
|
||||
setSearch: (s: string) => _search.set(s),
|
||||
fetchNextPage: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
};
|
||||
},
|
||||
},
|
||||
{provide: BookMetadataManageService, useValue: {}},
|
||||
{provide: BookDialogHelperService, useValue: {}},
|
||||
{
|
||||
|
||||
@@ -56,8 +56,8 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {DeferredRenderState} from './deferred-render-state';
|
||||
|
||||
import {SortService} from '../../service/sort.service';
|
||||
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
|
||||
import {filterBooksByFilters} from './filters/sidebar-filter';
|
||||
import {AppBooksApiService} from '../../service/app-books-api.service';
|
||||
import {AppBookFilters} from '../../model/app-book.model';
|
||||
|
||||
export enum EntityType {
|
||||
LIBRARY = 'Library',
|
||||
@@ -118,6 +118,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
private queryParamsService = inject(BookBrowserQueryParamsService);
|
||||
private entityService = inject(BookBrowserEntityService);
|
||||
private sortService = inject(SortService);
|
||||
private appBooksApi = inject(AppBooksApiService);
|
||||
private localStorageService = inject(LocalStorageService);
|
||||
private scrollService = inject(BookBrowserScrollService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
@@ -184,28 +185,64 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
|
||||
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())
|
||||
);
|
||||
// --- Server-side data pipeline: delegates filtering, sorting, searching to the API ---
|
||||
private readonly forceExpandSeries = computed(() =>
|
||||
this.queryParamsService.shouldForceExpandSeries(this.queryParamMap())
|
||||
);
|
||||
private readonly collapsedBooks = computed(() =>
|
||||
this.seriesCollapseFilter.collapseBooks(
|
||||
this.filteredBooks(), this.forceExpandSeries(), this.seriesCollapsed()
|
||||
)
|
||||
);
|
||||
private readonly sortedBooks = computed(() =>
|
||||
this.sortService.applyMultiSort(this.collapsedBooks(), this.sortCriteria())
|
||||
);
|
||||
|
||||
/** Sync entity scope, filters, search, and sort to the API service. */
|
||||
private readonly syncApiStateEffect = effect(() => {
|
||||
const {entityId, entityType} = this.entityInfo();
|
||||
const search = this.debouncedSearchTerm();
|
||||
const sidebarFilters = this.selectedFilter();
|
||||
const sortCriteria = this.sortCriteria();
|
||||
|
||||
const scopeFilters: AppBookFilters = {};
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
if (!Number.isNaN(entityId)) scopeFilters.libraryId = entityId;
|
||||
break;
|
||||
case EntityType.SHELF:
|
||||
if (!Number.isNaN(entityId)) scopeFilters.shelfId = entityId;
|
||||
break;
|
||||
case EntityType.MAGIC_SHELF:
|
||||
if (!Number.isNaN(entityId)) scopeFilters.magicShelfId = entityId;
|
||||
break;
|
||||
case EntityType.UNSHELVED:
|
||||
scopeFilters.unshelved = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (sidebarFilters) {
|
||||
for (const [type, values] of Object.entries(sidebarFilters)) {
|
||||
if (!values || values.length === 0) continue;
|
||||
const strValues = values.map(String);
|
||||
switch (type) {
|
||||
case 'author': scopeFilters.authors = strValues; break;
|
||||
case 'category': scopeFilters.category = strValues; break;
|
||||
case 'series': scopeFilters.series = strValues; break;
|
||||
case 'publisher': scopeFilters.publisher = strValues; break;
|
||||
case 'tag': scopeFilters.tag = strValues; break;
|
||||
case 'mood': scopeFilters.mood = strValues; break;
|
||||
case 'narrator': scopeFilters.narrator = strValues; break;
|
||||
case 'language': scopeFilters.language = strValues; break;
|
||||
case 'readStatus': scopeFilters.status = strValues[0]; break;
|
||||
case 'bookType': scopeFilters.fileType = strValues[0]; break;
|
||||
}
|
||||
}
|
||||
const mode = this.selectedFilterMode();
|
||||
scopeFilters.filterMode = mode === 'single' ? 'or' : mode;
|
||||
}
|
||||
|
||||
this.appBooksApi.setFilters(scopeFilters);
|
||||
this.appBooksApi.setSearch(search);
|
||||
|
||||
if (sortCriteria.length > 0) {
|
||||
const primary = sortCriteria[0];
|
||||
const dir = primary.direction === SortDirection.ASCENDING ? 'asc' as const : 'desc' as const;
|
||||
this.appBooksApi.setSort({field: primary.field, dir});
|
||||
}
|
||||
});
|
||||
|
||||
// --- Deferred render: lets skeleton/refresh indicator paint before committing ---
|
||||
private readonly booksRenderState = new DeferredRenderState<Book[]>();
|
||||
@@ -220,7 +257,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
});
|
||||
|
||||
private readonly pipelineInputs = computed(() => ({
|
||||
books: this.bookService.books(),
|
||||
books: this.appBooksApi.books(),
|
||||
entity: this.entityInfo(),
|
||||
search: this.debouncedSearchTerm(),
|
||||
filter: this.selectedFilter(),
|
||||
@@ -238,20 +275,15 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
this.lastBooksContextKey = contextKey;
|
||||
|
||||
if (shouldRefreshInPlace) {
|
||||
// Same context (sort/filter/search change within the same entity).
|
||||
// Commit synchronously — the memoized computed chain is fast and
|
||||
// skipping the setTimeout avoids a one-frame skeleton flash.
|
||||
const requestId = this.booksRenderState.begin('refresh');
|
||||
this.booksRenderState.commit(requestId, this.sortedBooks());
|
||||
this.booksRenderState.commit(requestId, this.appBooksApi.books());
|
||||
return;
|
||||
}
|
||||
|
||||
// Context changed (navigation between entities or first load).
|
||||
// Defer so the skeleton can paint before the pipeline evaluates.
|
||||
const requestId = this.booksRenderState.begin('reset');
|
||||
|
||||
const timeout = globalThis.setTimeout(() => {
|
||||
this.booksRenderState.commit(requestId, this.sortedBooks());
|
||||
this.booksRenderState.commit(requestId, this.appBooksApi.books());
|
||||
});
|
||||
|
||||
onCleanup(() => {
|
||||
@@ -259,8 +291,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
this.booksRenderState.cancel(requestId);
|
||||
});
|
||||
});
|
||||
readonly isBooksLoading = this.bookService.isBooksLoading;
|
||||
readonly booksError = this.bookService.booksError;
|
||||
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>();
|
||||
@@ -1046,7 +1078,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
|
||||
attachFilesToBook(): void {
|
||||
const selectedBookIds = Array.from(this.selectedBooks());
|
||||
const sourceBooks = this.bookService.books().filter(book =>
|
||||
const sourceBooks = (this.books() ?? []).filter(book =>
|
||||
selectedBookIds.includes(book.id)
|
||||
);
|
||||
|
||||
@@ -1084,7 +1116,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
const selectedBookIds = Array.from(this.selectedBooks());
|
||||
if (selectedBookIds.length === 0) return false;
|
||||
|
||||
const selectedBooks = this.bookService.books().filter(book =>
|
||||
const selectedBooks = (this.books() ?? []).filter(book =>
|
||||
selectedBookIds.includes(book.id)
|
||||
);
|
||||
|
||||
@@ -1106,4 +1138,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
onScrollEnd(): void {
|
||||
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
|
||||
this.appBooksApi.fetchNextPage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+92
-27
@@ -4,6 +4,7 @@ import {Library} from '../../../model/library.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {AppBooksApiService} from '../../../service/app-books-api.service';
|
||||
import {LibraryService} from '../../../service/library.service';
|
||||
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
|
||||
@@ -11,64 +12,85 @@ import {EntityType} from '../book-browser.component';
|
||||
import {Filter, FILTER_CONFIGS, FILTER_EXTRACTORS, FilterType, FilterValue, NUMERIC_ID_FILTER_TYPES, SortMode} from './book-filter.config';
|
||||
import {filterBooksByFilters} from '../filters/sidebar-filter';
|
||||
import {BookFilterMode} from '../../../../settings/user-management/user.service';
|
||||
import {AppFilterOptions, CountedOption, LanguageOption} from '../../../model/app-book.model';
|
||||
|
||||
const MAX_FILTER_ITEMS = 100;
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookFilterService {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly appBooksApi = inject(AppBooksApiService);
|
||||
private readonly libraryService = inject(LibraryService);
|
||||
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
|
||||
/** Server-supported filter types -- these use /api/v1/app/filter-options data. */
|
||||
private static readonly SERVER_FILTER_TYPES = new Set<FilterType>([
|
||||
'author', 'category', 'series', 'publisher', 'tag', 'mood',
|
||||
'narrator', 'language', 'readStatus', 'bookType',
|
||||
]);
|
||||
|
||||
createFilterSignals(
|
||||
entity: Signal<Library | Shelf | MagicShelf | null>,
|
||||
entityType: Signal<EntityType>,
|
||||
activeFilters: Signal<Record<string, unknown[]> | null>,
|
||||
filterMode: Signal<BookFilterMode>
|
||||
): Record<FilterType, Signal<Filter[]>> {
|
||||
const filteredBooks = computed(() =>
|
||||
this.filterBooksByEntity(this.bookService.books(), entity(), entityType())
|
||||
);
|
||||
|
||||
const signals = {} as Record<FilterType, Signal<Filter[]>>;
|
||||
|
||||
// Server-backed filter types use the filter-options API
|
||||
for (const type of BookFilterService.SERVER_FILTER_TYPES) {
|
||||
signals[type] = computed(() => {
|
||||
const options = this.appBooksApi.filterOptions();
|
||||
if (!options) return [];
|
||||
return this.serverOptionsToFilters(type, options);
|
||||
});
|
||||
}
|
||||
|
||||
// Client-side filter types that don't have server support use loaded books
|
||||
const filteredBooks = computed(() =>
|
||||
this.appBooksApi.books()
|
||||
);
|
||||
|
||||
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
|
||||
const filterType = type as Exclude<FilterType, 'library'>;
|
||||
if (BookFilterService.SERVER_FILTER_TYPES.has(filterType)) continue;
|
||||
signals[filterType] = computed(() => {
|
||||
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
|
||||
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
|
||||
});
|
||||
}
|
||||
|
||||
signals.library = computed(() => {
|
||||
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
|
||||
const libraries = this.libraryService.libraries();
|
||||
if (!signals.library) {
|
||||
signals.library = computed(() => {
|
||||
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
|
||||
const libraries = this.libraryService.libraries();
|
||||
|
||||
const libraryMap = new Map(
|
||||
libraries
|
||||
.filter(lib => lib.id !== undefined)
|
||||
.map(lib => [lib.id!, lib.name])
|
||||
);
|
||||
const libraryMap = new Map(
|
||||
libraries
|
||||
.filter(lib => lib.id !== undefined)
|
||||
.map(lib => [lib.id!, lib.name])
|
||||
);
|
||||
|
||||
const filterMap = new Map<number, Filter>();
|
||||
const filterMap = new Map<number, Filter>();
|
||||
|
||||
for (const book of books) {
|
||||
if (book.libraryId == null) continue;
|
||||
for (const book of books) {
|
||||
if (book.libraryId == null) continue;
|
||||
|
||||
if (!filterMap.has(book.libraryId)) {
|
||||
filterMap.set(book.libraryId, {
|
||||
value: {
|
||||
id: book.libraryId,
|
||||
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
|
||||
},
|
||||
bookCount: 0
|
||||
});
|
||||
if (!filterMap.has(book.libraryId)) {
|
||||
filterMap.set(book.libraryId, {
|
||||
value: {
|
||||
id: book.libraryId,
|
||||
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
|
||||
},
|
||||
bookCount: 0
|
||||
});
|
||||
}
|
||||
filterMap.get(book.libraryId)!.bookCount++;
|
||||
}
|
||||
filterMap.get(book.libraryId)!.bookCount++;
|
||||
}
|
||||
|
||||
return this.sortFiltersByCount(Array.from(filterMap.values()));
|
||||
});
|
||||
return this.sortFiltersByCount(Array.from(filterMap.values()));
|
||||
});
|
||||
}
|
||||
|
||||
return signals;
|
||||
}
|
||||
@@ -108,6 +130,49 @@ export class BookFilterService {
|
||||
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
|
||||
}
|
||||
|
||||
private serverOptionsToFilters(type: FilterType, options: AppFilterOptions): Filter[] {
|
||||
switch (type) {
|
||||
case 'author':
|
||||
return this.countedToFilters(options.authors);
|
||||
case 'category':
|
||||
return this.countedToFilters(options.categories);
|
||||
case 'series':
|
||||
return this.countedToFilters(options.series);
|
||||
case 'publisher':
|
||||
return this.countedToFilters(options.publishers);
|
||||
case 'tag':
|
||||
return this.countedToFilters(options.tags);
|
||||
case 'mood':
|
||||
return this.countedToFilters(options.moods);
|
||||
case 'narrator':
|
||||
return this.countedToFilters(options.narrators);
|
||||
case 'language':
|
||||
return (options.languages ?? []).map((lang: LanguageOption) => ({
|
||||
value: {id: lang.code, name: lang.label || lang.code},
|
||||
bookCount: lang.count,
|
||||
}));
|
||||
case 'readStatus':
|
||||
return (options.readStatuses ?? []).map((status: string) => ({
|
||||
value: {id: status, name: status},
|
||||
bookCount: 0,
|
||||
}));
|
||||
case 'bookType':
|
||||
return (options.fileTypes ?? []).map((ft: string) => ({
|
||||
value: {id: ft, name: ft},
|
||||
bookCount: 0,
|
||||
}));
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private countedToFilters(items: CountedOption[]): Filter[] {
|
||||
return (items ?? []).map(item => ({
|
||||
value: {id: item.name, name: item.name},
|
||||
bookCount: item.count,
|
||||
}));
|
||||
}
|
||||
|
||||
private buildAndSortFilters(
|
||||
books: Book[],
|
||||
extractor: (book: Book) => FilterValue[],
|
||||
|
||||
Reference in New Issue
Block a user