fix(ui): revert to UI-based filtering & sorting (#935)

This commit is contained in:
James Ward
2026-05-04 13:37:07 -04:00
committed by GitHub
parent 3f3beaf86b
commit de96fd89c9
5 changed files with 159 additions and 471 deletions
@@ -446,6 +446,8 @@
[showFilter]="showFilter()"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter() }"
[entity]="entity()"
[entityType]="entityType()"
[style.display]="showFilter() ? '' : 'none'"
(filterSelected)="onFilterSelected($event)"
(filterModeChanged)="onFilterModeChanged($event)">
@@ -1,4 +1,4 @@
import {computed, signal, WritableSignal} from '@angular/core';
import {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,8 +31,6 @@ 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';
import {LayoutService} from '../../../../shared/layout/layout.service';
import {type VirtualGridMetrics} from '../../../../shared/util/virtual-grid.util';
@@ -222,12 +220,6 @@ function createHarness(options?: {
setCollapsed: vi.fn((value: boolean) => seriesCollapsed.set(value)),
},
},
{
provide: SortService,
useValue: {
applySort: vi.fn((b: Book[]) => b),
},
},
{
provide: BookSelectionService,
useValue: {
@@ -289,47 +281,6 @@ 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();
result = [...result].sort((a, b) => {
const aVal = s.field === 'title' ? (a.metadata?.title ?? '') : (a.addedOn ?? '');
const bVal = s.field === 'title' ? (b.metadata?.title ?? '') : (b.addedOn ?? '');
return String(aVal).localeCompare(String(bVal));
});
if (s.dir === 'desc') {
result.reverse();
}
return result;
});
const totalElements = computed(() => options?.totalElements ?? filteredSortedBooks().length);
return {
books: filteredSortedBooks,
totalElements,
hasNextPage: hasNextPage.asReadonly(),
isLoading: isBooksLoading.asReadonly(),
isFetchingNextPage: isFetchingNextPage.asReadonly(),
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: {}},
{
@@ -501,94 +452,7 @@ describe('BookBrowserComponent', () => {
expect(collapseBooksSpy).toHaveBeenCalled();
});
it('triggers next page fetch when the virtual grid reaches the loaded rows', () => {
const {component, setHasNextPage} = createHarness({totalElements: 100});
const appBooksApi = TestBed.inject(AppBooksApiService);
vi.runOnlyPendingTimers();
TestBed.flushEffects();
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');
component.currentViewMode.set(VIEW_MODES.GRID);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalled();
});
it('re-arms grid pagination after a next-page request completes without new books', () => {
const {component, books, setHasNextPage, setIsFetchingNextPage} = createHarness({totalElements: 100});
const appBooksApi = TestBed.inject(AppBooksApiService);
vi.spyOn(component.virtualGrid.virtualizer, 'getVirtualItems').mockReturnValue([
{index: 2, key: 3, start: 0, end: 241, size: 241, lane: 0}
]);
component.currentViewMode.set(VIEW_MODES.TABLE);
TestBed.flushEffects();
setHasNextPage(true);
const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage');
component.currentViewMode.set(VIEW_MODES.GRID);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(1);
setIsFetchingNextPage(true);
TestBed.flushEffects();
setIsFetchingNextPage(false);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(1);
books.update(current => [...current]);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(2);
});
it('keeps fetching grid pages when collapsed series hide newly loaded books', () => {
const {component, books, setHasNextPage} = createHarness({
books: [
makeBook(1, 1, 'Alpha', '2024-01-01T00:00:00Z'),
makeBook(2, 1, 'Bravo', '2024-02-01T00:00:00Z'),
makeBook(3, 1, 'Charlie', '2024-03-01T00:00:00Z'),
],
totalElements: 100,
});
const appBooksApi = TestBed.inject(AppBooksApiService);
const filter = TestBed.inject(SeriesCollapseFilter);
vi.mocked(filter.collapseBooks).mockImplementation((items: Book[]) => items.slice(0, 3));
vi.spyOn(component.virtualGrid.virtualizer, 'getVirtualItems').mockReturnValue([
{index: 2, key: 3, start: 0, end: 241, size: 241, lane: 0}
]);
component.currentViewMode.set(VIEW_MODES.TABLE);
TestBed.flushEffects();
setHasNextPage(true);
vi.mocked(filter.setCollapsed)(true);
const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage');
component.currentViewMode.set(VIEW_MODES.GRID);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(1);
books.update(current => [...current, makeBook(4, 1, 'Collapsed', '2024-04-01T00:00:00Z')]);
TestBed.flushEffects();
expect(component.books()).toHaveLength(3);
expect(fetchNextPageSpy).toHaveBeenCalledTimes(2);
});
it('uses the known total book count while more pages are available', () => {
it.skip('uses the known total book count while more pages are available', () => {
const {component, setHasNextPage} = createHarness({totalElements: 100});
setHasNextPage(true);
@@ -600,7 +464,7 @@ describe('BookBrowserComponent', () => {
expect(component.virtualGrid.virtualizer.options().count).toBe(100);
});
it('uses one unloaded slot for collapsed series while more pages are available', () => {
it.skip('uses one unloaded slot for collapsed series while more pages are available', () => {
const {component, setHasNextPage} = createHarness({totalElements: 100});
const filter = TestBed.inject(SeriesCollapseFilter);
filter.setCollapsed(true);
@@ -614,7 +478,7 @@ describe('BookBrowserComponent', () => {
});
it('uses the rendered book count once pagination is exhausted', () => {
const {component} = createHarness({totalElements: 100});
const {component} = createHarness();
const filter = TestBed.inject(SeriesCollapseFilter);
vi.mocked(filter.collapseBooks).mockImplementation((items: Book[]) => items.slice(0, 1));
@@ -52,10 +52,10 @@ import {MultiSortPopoverComponent} from './sorting/multi-sort-popover/multi-sort
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {SortService} from '../../service/sort.service';
import {AppBooksApiService} from '../../service/app-books-api.service';
import {AppBookFilters} from '../../model/app-book.model';
import {createVirtualGrid, scaleForGridColumns, type VirtualGridMetrics} from '../../../../shared/util/virtual-grid.util';
import {GridDensityButtonsComponent, type GridDensityDirection} from '../../../../shared/components/grid-density-buttons/grid-density-buttons.component';
import {filterBooksBySearchTerm} from './filters/HeaderFilter';
import {filterBooksByFilters} from './filters/sidebar-filter';
import {LayoutService} from '../../../../shared/layout/layout.service';
export enum EntityType {
@@ -110,7 +110,6 @@ export class BookBrowserComponent implements AfterViewInit {
private queryParamsService = inject(BookBrowserQueryParamsService);
private entityService = inject(BookBrowserEntityService);
private sortService = inject(SortService);
private appBooksApi = inject(AppBooksApiService);
private localStorageService = inject(LocalStorageService);
private scrollService = inject(RouteScrollPositionService);
private layoutService = inject(LayoutService);
@@ -202,94 +201,32 @@ export class BookBrowserComponent implements AfterViewInit {
return actions;
});
// --- Server-side data pipeline: delegates filtering, sorting, searching to the API ---
// --- 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())
);
private readonly forceExpandSeries = computed(() =>
this.queryParamsService.shouldForceExpandSeries(this.queryParamMap())
);
private readonly collapsedBooks = computed(() =>
this.seriesCollapseFilter.collapseBooks(
this.filteredBooks(), this.forceExpandSeries(), this.seriesCollapsed()
)
);
/** 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();
readonly books = computed(() =>
this.sortService.applyMultiSort(this.collapsedBooks(), 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; break;
case 'bookType': scopeFilters.fileType = strValues; break;
case 'ageRating': scopeFilters.ageRating = strValues; break;
case 'contentRating': scopeFilters.contentRating = strValues; break;
case 'matchScore': scopeFilters.matchScore = strValues; break;
case 'publishedDate': scopeFilters.publishedDate = strValues; break;
case 'fileSize': scopeFilters.fileSize = strValues; break;
case 'personalRating': scopeFilters.personalRating = strValues; break;
case 'amazonRating': scopeFilters.amazonRating = strValues; break;
case 'goodreadsRating': scopeFilters.goodreadsRating = strValues; break;
case 'hardcoverRating': scopeFilters.hardcoverRating = strValues; break;
case 'lubimyczytacRating': scopeFilters.lubimyczytacRating = strValues; break;
case 'ranobedbRating': scopeFilters.ranobedbRating = strValues; break;
case 'audibleRating': scopeFilters.audibleRating = strValues; break;
case 'pageCount': scopeFilters.pageCount = strValues; break;
case 'shelfStatus':
scopeFilters.shelfStatus = strValues;
break;
case 'comicCharacter': scopeFilters.comicCharacter = strValues; break;
case 'comicTeam': scopeFilters.comicTeam = strValues; break;
case 'comicLocation': scopeFilters.comicLocation = strValues; break;
case 'comicCreator': scopeFilters.comicCreator = strValues; break;
case 'shelf': scopeFilters.shelves = strValues; break;
case 'library': scopeFilters.libraries = strValues; 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});
}
});
readonly books = computed(() => {
const books = this.appBooksApi.books();
return this.seriesCollapseFilter.collapseBooks(books, this.forceExpandSeries());
});
readonly isBooksLoading = computed(() => this.appBooksApi.isLoading());
readonly booksError = this.appBooksApi.error;
readonly isBooksLoading = this.bookService.isBooksLoading;
readonly booksError = this.bookService.booksError;
private readonly GRID_GAP = 21;
private readonly MOBILE_BREAKPOINT = 768;
@@ -317,7 +254,7 @@ export class BookBrowserComponent implements AfterViewInit {
private readonly virtualGridColumns = computed(() => this.isMobile() ? this.gridMobileColumnCount() : undefined);
readonly virtualRowCount = computed(() => this.bookCountIncludingUnloadedPages(this.books().length));
private readonly hasUnloadedBooks = computed(() => this.books().length < this.virtualRowCount());
readonly loadedBookCount = computed(() => this.appBooksApi.books().length);
readonly loadedBookCount = computed(() => this.books().length);
readonly virtualGrid = createVirtualGrid({
items: this.books,
scrollElement: this.scrollElement,
@@ -356,16 +293,15 @@ export class BookBrowserComponent implements AfterViewInit {
const lastVirtualItem = this.virtualGrid.virtualizer.getVirtualItems().at(-1);
if (!lastVirtualItem || items.length === 0) return;
if (lastVirtualItem.index < items.length - 1) return;
if (!this.hasUnloadedBooks() || this.appBooksApi.isFetchingNextPage()) return;
if (!this.hasUnloadedBooks()) return;
if (this.gridLastLoadRequestLoadedBookCount === loadedBookCount) {
this.gridLastLoadRequestLoadedBookCount = undefined;
return;
}
this.gridLastLoadRequestLoadedBookCount = loadedBookCount;
this.appBooksApi.fetchNextPage();
});
readonly isFetchingNextBooksPage = this.appBooksApi.isFetchingNextPage;
readonly isFetchingNextBooksPage = this.bookService.isBooksLoading;
parsedFilters: Record<string, string[]> = {};
dynamicDialogRef: DynamicDialogRef | undefined | null;
@@ -517,13 +453,7 @@ export class BookBrowserComponent implements AfterViewInit {
if (this.showBooksLoadingPlaceholder()) {
return INITIAL_LOADING_ROW_COUNT;
}
if (!this.appBooksApi.hasNextPage()) {
return renderedBookCount;
}
if (!this.seriesCollapsed() || this.forceExpandSeries()) {
return Math.max(this.appBooksApi.totalElements(), renderedBookCount);
}
return renderedBookCount + 1;
return renderedBookCount;
}
private minimumLoadingGridItemCount({viewportHeight, columns, itemHeight, gap}: VirtualGridMetrics): number {
@@ -731,20 +661,14 @@ export class BookBrowserComponent implements AfterViewInit {
}
selectAllBooks(): void {
this.appBooksApi.fetchAllBookIds().pipe(take(1)).subscribe({
next: (allIds) => {
this.bookSelectionService.selectAll(allIds);
},
error: () => {
this.bookSelectionService.selectAll();
}
});
this.bookSelectionService.selectAll(
this.filteredBooks().map(b => b.id)
);
}
loadNextBooksPage(): void {
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
this.appBooksApi.fetchNextPage();
}
// This function is temporarily a no-op while a long term plan is being considered.
return;
}
deselectAllBooks(): void {
@@ -9,6 +9,10 @@ import {BookFilterMode, DEFAULT_VISIBLE_FILTERS, UserService, VisibleFilterType}
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
import {BookFilterService} from './book-filter.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {EntityType} from '../book-browser.component';
interface FilterModeOption {
label: string;
@@ -31,6 +35,9 @@ interface FilterModeOption {
export class BookFilterComponent {
readonly showFilter = input(false);
readonly entity = input<Library | Shelf | MagicShelf | null>(null);
readonly entityType = input<EntityType>(EntityType.ALL_BOOKS);
readonly filterSelected = output<Record<string, unknown> | null>();
readonly filterModeChanged = output<BookFilterMode>();
@@ -38,10 +45,6 @@ export class BookFilterComponent {
private readonly userService = inject(UserService);
private readonly t = inject(TranslocoService);
/** Stable reference to the singleton filter signals — never recreated. */
readonly filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.filterSignals;
readonly filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
readonly activeFilters = signal<Record<string, unknown[]>>({});
readonly expandedPanels = signal<number[]>([]);
@@ -64,6 +67,16 @@ export class BookFilterComponent {
private readonly _selectedFilterMode = signal<BookFilterMode>('and');
readonly selectedFilterMode = this._selectedFilterMode.asReadonly();
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
this.entity,
this.entityType,
this.activeFilters,
this.selectedFilterMode
);
get filterTypes(): FilterType[] {
return Object.keys(this.filterSignals) as FilterType[];
}
private readonly syncUserSettings = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
@@ -3,38 +3,74 @@ import {Book} from '../../../model/book.model';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {AppBooksApiService} from '../../../service/app-books-api.service';
import {BookService} from '../../../service/book.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';
import {EntityType} from '../book-browser.component';
import {
ageRatingRanges,
CONTENT_RATING_LABELS,
Filter,
fileSizeRanges,
FilterType,
matchScoreRanges,
NUMERIC_ID_FILTER_TYPES,
pageCountRanges,
ratingRanges,
READ_STATUS_LABELS,
} from './book-filter.config';
import {AppFilterOptions, CountedOption, LanguageOption} from '../../../model/app-book.model';
import {ReadStatus} from '../../../model/book.model';
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';
const MAX_FILTER_ITEMS = 100;
@Injectable({providedIn: 'root'})
export class BookFilterService {
private readonly appBooksApi = inject(AppBooksApiService);
private readonly bookService = inject(BookService);
private readonly libraryService = inject(LibraryService);
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
/** Cached filter signals — created once, shared across component instances. */
private _filterSignals: Record<FilterType, Signal<Filter[]>> | null = null;
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())
);
get filterSignals(): Record<FilterType, Signal<Filter[]>> {
if (!this._filterSignals) {
this._filterSignals = this.buildFilterSignals();
const signals = {} as Record<FilterType, Signal<Filter[]>>;
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
const filterType = type as Exclude<FilterType, 'library'>;
signals[filterType] = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
});
}
return this._filterSignals;
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 filterMap = new Map<number, Filter>();
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) ?? book.libraryName ?? `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
return signals;
}
filterBooksByEntity(
@@ -56,6 +92,9 @@ export class BookFilterService {
case EntityType.MAGIC_SHELF:
return this.filterByMagicShelf(books, entity as MagicShelf);
case EntityType.UNSHELVED:
return books.filter(book => !book.shelves || book.shelves.length === 0);
default:
return books;
}
@@ -72,207 +111,53 @@ export class BookFilterService {
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
}
private buildFilterSignals(): Record<FilterType, Signal<Filter[]>> {
const signals = {} as Record<FilterType, Signal<Filter[]>>;
signals['author'] = computed(() => this.countedToFilters(this.appBooksApi.authorOptions()));
signals['category'] = computed(() => this.countedToFilters(this.appBooksApi.categoryOptions()));
signals['series'] = computed(() => this.countedToFilters(this.appBooksApi.seriesOptions()));
signals['publisher'] = computed(() => this.countedToFilters(this.appBooksApi.publisherOptions()));
signals['tag'] = computed(() => this.countedToFilters(this.appBooksApi.tagOptions()));
signals['mood'] = computed(() => this.countedToFilters(this.appBooksApi.moodOptions()));
signals['narrator'] = computed(() => this.countedToFilters(this.appBooksApi.narratorOptions()));
signals['language'] = computed(() => this.appBooksApi.languageOptions().map((lang: LanguageOption) => ({
value: {id: lang.code, name: lang.label || lang.code},
bookCount: lang.count,
})));
signals['readStatus'] = computed(() => this.appBooksApi.readStatusOptions().map(item => ({
value: {id: item.name, name: READ_STATUS_LABELS[item.name as ReadStatus] || item.name},
bookCount: item.count
})));
signals['bookType'] = computed(() => this.countedToFilters(this.appBooksApi.fileTypeOptions()));
signals['ageRating'] = computed(() => this.rangedFilters(this.appBooksApi.ageRatingOptions(), ageRatingRanges));
signals['contentRating'] = computed(() => this.appBooksApi.contentRatingOptions().map(item => ({
value: {id: item.name, name: CONTENT_RATING_LABELS[item.name] || item.name},
bookCount: item.count
})));
signals['matchScore'] = computed(() => this.rangedFilters(this.appBooksApi.matchScoreOptions(), matchScoreRanges));
signals['publishedDate'] = computed(() => this.appBooksApi.publishedYearOptions().map(item => ({
value: {id: item.name, name: item.name},
bookCount: item.count
})));
signals['fileSize'] = computed(() => this.rangedFilters(this.appBooksApi.fileSizeOptions(), fileSizeRanges));
signals['personalRating'] = computed(() => this.appBooksApi.personalRatingOptions().map(item => ({
value: {id: Number(item.name), name: item.name},
bookCount: item.count
})));
signals['amazonRating'] = computed(() => this.rangedFilters(this.appBooksApi.amazonRatingOptions(), ratingRanges));
signals['goodreadsRating'] = computed(() => this.rangedFilters(this.appBooksApi.goodreadsRatingOptions(), ratingRanges));
signals['hardcoverRating'] = computed(() => this.rangedFilters(this.appBooksApi.hardcoverRatingOptions(), ratingRanges));
signals['lubimyczytacRating'] = computed(() => this.rangedFilters(this.appBooksApi.lubimyczytacRatingOptions(), ratingRanges));
signals['ranobedbRating'] = computed(() => this.rangedFilters(this.appBooksApi.ranobedbRatingOptions(), ratingRanges));
signals['audibleRating'] = computed(() => this.rangedFilters(this.appBooksApi.audibleRatingOptions(), ratingRanges));
signals['pageCount'] = computed(() => this.rangedFilters(this.appBooksApi.pageCountOptions(), pageCountRanges));
signals['shelfStatus'] = computed(() => this.appBooksApi.shelfStatusOptions().map(item => ({
value: {id: item.name, name: item.name.charAt(0).toUpperCase() + item.name.slice(1)},
bookCount: item.count
})));
signals['comicCharacter'] = computed(() => this.countedToFilters(this.appBooksApi.comicCharacterOptions()));
signals['comicTeam'] = computed(() => this.countedToFilters(this.appBooksApi.comicTeamOptions()));
signals['comicLocation'] = computed(() => this.countedToFilters(this.appBooksApi.comicLocationOptions()));
signals['comicCreator'] = computed(() => this.appBooksApi.comicCreatorOptions().map(item => {
const parts = item.name.split(':');
const role = parts.pop()!;
const name = parts.join(':');
return {
value: {id: item.name, name: `${name} (${role})`},
bookCount: item.count
};
}));
signals['shelf'] = computed(() => this.appBooksApi.shelfOptions().map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
}));
signals['library'] = computed(() => this.appBooksApi.libraryOptions().map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
}));
return signals;
}
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(item => ({
value: {id: item.name, name: READ_STATUS_LABELS[item.name as ReadStatus] || item.name},
bookCount: item.count
}));
case 'bookType':
return this.countedToFilters(options.fileTypes);
case 'ageRating':
return this.rangedFilters(options.ageRatings, ageRatingRanges);
case 'contentRating':
return (options.contentRatings ?? []).map(item => ({
value: {id: item.name, name: CONTENT_RATING_LABELS[item.name] || item.name},
bookCount: item.count
}));
case 'matchScore':
return this.rangedFilters(options.matchScores, matchScoreRanges);
case 'publishedDate':
return (options.publishedYears ?? []).map(item => ({
value: {id: item.name, name: item.name},
bookCount: item.count
}));
case 'fileSize':
return this.rangedFilters(options.fileSizes, fileSizeRanges);
case 'personalRating':
return (options.personalRatings ?? []).map(item => ({
value: {id: Number(item.name), name: item.name},
bookCount: item.count
}));
case 'amazonRating':
return this.rangedFilters(options.amazonRatings, ratingRanges);
case 'goodreadsRating':
return this.rangedFilters(options.goodreadsRatings, ratingRanges);
case 'hardcoverRating':
return this.rangedFilters(options.hardcoverRatings, ratingRanges);
case 'lubimyczytacRating':
return this.rangedFilters(options.lubimyczytacRatings, ratingRanges);
case 'ranobedbRating':
return this.rangedFilters(options.ranobedbRatings, ratingRanges);
case 'audibleRating':
return this.rangedFilters(options.audibleRatings, ratingRanges);
case 'pageCount':
return this.rangedFilters(options.pageCounts, pageCountRanges);
case 'shelfStatus':
return (options.shelfStatuses ?? []).map(item => ({
value: {id: item.name, name: item.name.charAt(0).toUpperCase() + item.name.slice(1)},
bookCount: item.count
}));
case 'comicCharacter':
return this.countedToFilters(options.comicCharacters);
case 'comicTeam':
return this.countedToFilters(options.comicTeams);
case 'comicLocation':
return this.countedToFilters(options.comicLocations);
case 'comicCreator':
return (options.comicCreators ?? []).map(item => {
const parts = item.name.split(':');
const role = parts.pop()!;
const name = parts.join(':');
return {
value: {id: item.name, name: `${name} (${role})`},
bookCount: item.count
};
});
case 'shelf':
return (options.shelves ?? []).map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
});
case 'library':
return (options.libraries ?? []).map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
});
default:
return [];
}
}
private countedToFilters(items: CountedOption[]): Filter[] {
return (items ?? []).map(item => ({
value: {id: item.name, name: item.name},
bookCount: item.count,
}));
}
private rangedFilters(
items: CountedOption[] | undefined,
ranges: readonly {id: number; label: string; sortIndex: number}[]
private buildAndSortFilters(
books: Book[],
extractor: (book: Book) => FilterValue[],
sortMode: SortMode
): Filter[] {
return (items ?? []).map(item => {
const rangeId = Number(item.name);
const range = ranges.find(r => r.id === rangeId);
return {
value: {id: rangeId, name: range?.label || item.name, sortIndex: range?.sortIndex},
bookCount: item.count
};
const filterMap = new Map<unknown, Filter>();
for (const book of books) {
for (const item of extractor(book)) {
const id = item.id;
if (!filterMap.has(id)) {
filterMap.set(id, {value: item, bookCount: 0});
}
filterMap.get(id)!.bookCount++;
}
}
const filters = Array.from(filterMap.values());
const sorted = sortMode === 'sortIndex'
? this.sortFiltersBySortIndex(filters)
: this.sortFiltersByCount(filters);
return sorted.slice(0, MAX_FILTER_ITEMS);
}
private sortFiltersByCount(filters: Filter[]): Filter[] {
return filters.sort((a, b) => {
if (b.bookCount !== a.bookCount) return b.bookCount - a.bookCount;
return this.compareNames(a, b);
});
}
private sortFiltersBySortIndex(filters: Filter[]): Filter[] {
return filters.sort((a, b) => {
const aIndex = (a.value as { sortIndex?: number }).sortIndex ?? 999;
const bIndex = (b.value as { sortIndex?: number }).sortIndex ?? 999;
if (aIndex !== bIndex) return aIndex - bIndex;
return this.compareNames(a, b);
});
}
private compareNames(a: Filter, b: Filter): number {
const aName = String((a.value as { name?: string }).name ?? '');
const bName = String((b.value as { name?: string }).name ?? '');
return aName.localeCompare(bName);
}
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
if (!magicShelf.filterJson) return [];
try {