feat(filters): add age rating and content rating filters, improve filter options (#479)

* feat(filters): add age rating and content rating filters, improve filter options

* fix(book-browser): update view mode handling to use reactive properties

* fix(book-browser): update view mode handling to use getter methods

* feat(filters): improve filtering capabilities with comic creators and validate input values

* test(filters): fix AppBookServiceFilterOptionsTest with additional query mocks

* fix(filters): improve error handling for invalid filter bucket IDs and roles

* refactor(book-browser): remove unused computedFilterLabel

* fix(filters): validate shelfStatus values and throw error for invalid inputs

* test(book-browser): mock TranslocoService for language changes in tests

* fix(book-browser): ensure active language is set before syncing browser state
This commit is contained in:
brios
2026-04-22 17:27:15 -04:00
committed by Zach Yale
parent fcee609b15
commit 502f5738bf
20 changed files with 1456 additions and 525 deletions
@@ -8,17 +8,17 @@
<div class="entity-info">
<p class="entity-title">
@if (entityType === EntityType.ALL_BOOKS) {
@if (currentFilterLabel && rawFilterParamFromUrl) {
{{ currentFilterLabel }}
} @else if (isFilterActive || hasSearchTerm) {
{{ computedFilterLabel }}
@if (currentFilterLabel() && rawFilterParamFromUrl) {
{{ currentFilterLabel() }}
} @else if (isFilterActive() || hasSearchTerm()) {
{{ computedFilterLabel() }}
} @else {
{{ t('labels.allBooks') }}
}
} @else if (entityType === EntityType.UNSHELVED) {
{{ (isFilterActive || hasSearchTerm) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
{{ (isFilterActive() || hasSearchTerm()) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
} @else {
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive() || hasSearchTerm()) ? ' ' + t('labels.filteredSuffix') : '' }}
}
</p>
@if (!isBooksLoading() && seriesCollapseFilter.seriesCollapsed() && books(); as books) {
@@ -46,7 +46,7 @@
</div>
<div class="toolbar-actions">
<div class="toolbar-icons">
@if (isFilterActive) {
@if (isFilterActive()) {
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="clearFilter()" (keydown.enter)="clearFilter()">
<i
class="pi pi-filter-slash filter-clear-icon"
@@ -56,7 +56,7 @@
</a>
}
@if (currentViewMode === 'table') {
@if (currentViewMode() === 'table') {
<div>
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="columnPopover.toggle($event)" (keydown.enter)="columnPopover.toggle($event)">
<i
@@ -92,7 +92,7 @@
}
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
<i
[ngClass]="viewIcon"
[ngClass]="viewIcon()"
[pTooltip]="t('tooltip.toggleView')"
tooltipPosition="top">
</i>
@@ -121,24 +121,24 @@
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
</div>
</div>
@if (isMobile) {
@if (isMobile()) {
<div class="display-settings-section">
<span class="display-settings-label">{{ t('labels.gridColumns') }}</span>
<div class="column-options">
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 2"
[class.active]="mobileColumnCount() === 2"
(click)="setMobileColumns(2)">2</button>
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 3"
[class.active]="mobileColumnCount() === 3"
(click)="setMobileColumns(3)">3</button>
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 4"
[class.active]="mobileColumnCount() === 4"
(click)="setMobileColumns(4)">4</button>
</div>
</div>
@@ -188,7 +188,7 @@
<app-multi-sort-popover
[sortCriteria]="this.bookSorter.selectedSortCriteria"
[availableSortOptions]="visibleSortOptions"
[showSaveButton]="canSaveSort"
[showSaveButton]="canSaveSort()"
(criteriaChange)="onSortCriteriaChange($event)"
(saveSortConfig)="onSaveSortConfig($event)">
</app-multi-sort-popover>
@@ -263,7 +263,7 @@
</div>
</div>
@if (showTableLoadingPlaceholder) {
@if (showTableLoadingPlaceholder()) {
<div class="table-skeleton" aria-hidden="true">
<div class="table-skeleton-header">
@for (column of tableSkeletonColumns; track column) {
@@ -279,12 +279,12 @@
</div>
}
</div>
} @else if (showGridLoadingPlaceholder) {
} @else if (showGridLoadingPlaceholder()) {
<div class="skeleton-grid"
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
[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'}">
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
</div>
}
</div>
@@ -308,7 +308,7 @@
</p>
</div>
}
@if (currentViewMode === 'table' && books.length > 0) {
@if (currentViewMode() === 'table' && books.length > 0) {
<app-book-table
[books]="books"
[preselectedBookIds]="selectedBooks()"
@@ -317,15 +317,15 @@
[visibleColumns]="visibleColumns"
></app-book-table>
}
@if (currentViewMode === 'grid') {
@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))'}">
[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'}">
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
<app-book-card
[index]="i"
[book]="book"
@@ -335,7 +335,7 @@
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="selectedBooks().has(book.id)"
[useSquareCovers]="isAudiobookOnlyLibrary"
[useSquareCovers]="isAudiobookOnlyLibrary()"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
@@ -481,17 +481,15 @@
(click)="toggleSidebar()"
(keydown.enter)="toggleSidebar()">
</div>
<app-book-filter
[showFilter]="showFilter()"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter() }"
[entity]="entity()"
[entityType]="entityType()"
[resetFilter$]="resetFilterSubject"
(filterSelected)="onFilterSelected($event)"
(filterModeChanged)="onFilterModeChanged($event)">
</app-book-filter>
}
<app-book-filter
[showFilter]="showFilter()"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter() }"
[style.display]="showFilter() ? '' : 'none'"
(filterSelected)="onFilterSelected($event)"
(filterModeChanged)="onFilterModeChanged($event)">
</app-book-filter>
</div>
</ng-container>
@@ -324,6 +324,8 @@ function createHarness(options?: {
{
provide: TranslocoService,
useValue: {
langChanges$: new Subject<string>().asObservable(),
getActiveLang: vi.fn(() => 'en'),
translate: vi.fn((key: string) => {
if (options?.translate) {
return options.translate(key);
@@ -378,11 +380,11 @@ describe('BookBrowserComponent', () => {
it('switches view mode through the display settings control', () => {
const {component, queryParamsService} = createHarness();
component.currentViewMode = VIEW_MODES.GRID;
component.currentViewMode.set(VIEW_MODES.GRID);
component.onViewModeChange(VIEW_MODES.TABLE);
expect(component.currentViewMode).toBe(VIEW_MODES.TABLE);
expect(component.currentViewMode()).toBe(VIEW_MODES.TABLE);
expect(queryParamsService.updateViewMode).toHaveBeenCalledWith(VIEW_MODES.TABLE);
});
@@ -432,9 +434,9 @@ describe('BookBrowserComponent', () => {
isBooksLoading: true,
});
expect(component.showBooksLoadingPlaceholder).toBe(false);
expect(component.showGridLoadingPlaceholder).toBe(false);
expect(component.showTableLoadingPlaceholder).toBe(false);
expect(component.showBooksLoadingPlaceholder()).toBe(false);
expect(component.showGridLoadingPlaceholder()).toBe(false);
expect(component.showTableLoadingPlaceholder()).toBe(false);
});
it('triggers next page fetch when scrolled near the bottom of rendered content', async () => {
@@ -460,7 +462,7 @@ describe('BookBrowserComponent', () => {
removeEventListener: vi.fn(),
} as unknown as HTMLElement;
component.currentViewMode = VIEW_MODES.GRID;
component.currentViewMode.set(VIEW_MODES.GRID);
component.scrollContainerRef = {nativeElement: mockElement} as ElementRef<HTMLElement>;
// Trigger initial check
@@ -6,7 +6,7 @@ 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 {combineLatest, finalize, Subject} from 'rxjs';
import {combineLatest, finalize} from 'rxjs';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
import {SortDirection, SortOption} from '../../model/sort.model';
@@ -217,6 +217,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
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 '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();
@@ -288,7 +307,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private containerResizeObserver: ResizeObserver | undefined;
readonly gridColumns = computed(() => {
return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth, 10) || 180, this.GRID_GAP);
return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth(), 10) || 180, this.GRID_GAP);
});
/**
@@ -301,7 +320,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (total === 0) return 0;
const cols = this.gridColumns();
const rows = Math.ceil(total / cols);
const rowHeight = this.currentCardSize.height + this.GRID_GAP;
const rowHeight = this.currentCardSize().height + this.GRID_GAP;
return rows * rowHeight;
});
@@ -313,28 +332,64 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
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;
const rowHeight = this.currentCardSize().height + this.GRID_GAP;
return rows * rowHeight;
});
protected resetFilterSubject = new Subject<void>();
readonly skeletonSlots = Array.from({length: 24}, (_, index) => index);
skeletonSlots = Array.from({length: 24}, (_, index) => index);
readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index);
readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
parsedFilters: Record<string, string[]> = {};
bookTitle = '';
dynamicDialogRef: DynamicDialogRef | undefined | null;
EntityType = EntityType;
currentFilterLabel: string | null = null;
private readonly activeLang = toSignal(this.t.langChanges$, {
initialValue: this.t.getActiveLang()
});
readonly computedFilterLabel = computed(() => {
this.activeLang();
const filters = this.selectedFilter();
if (!filters || Object.keys(filters).length === 0) {
return this.t.translate('book.browser.labels.allBooks');
}
const filterEntries = Object.entries(filters);
if (filterEntries.length === 1) {
const [filterType, values] = filterEntries[0];
const filterName = FilterLabelHelper.getFilterTypeName(filterType);
if (values.length === 1) {
const displayValue = FilterLabelHelper.getFilterDisplayValue(filterType, values[0]);
return `${filterName}: ${displayValue}`;
}
return `${filterName} (${values.length})`;
}
const filterSummary = filterEntries
.map(([type, values]) => `${FilterLabelHelper.getFilterTypeName(type)} (${values.length})`)
.join(', ');
return filterSummary.length > 50
? this.t.translate('book.browser.labels.activeFilters', {count: filterEntries.length})
: filterSummary;
});
readonly currentFilterLabel = computed(() => this.computedFilterLabel());
rawFilterParamFromUrl: string | null = null;
visibleColumns: { field: string; header: string }[] = [];
entityViewPreferences: EntityViewPreferences | undefined;
currentViewMode: string | undefined;
currentViewMode = signal<string | undefined>(undefined);
lastAppliedSortCriteria: SortOption[] = [];
visibleSortOptions: SortOption[] = [];
screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024;
mobileColumnCount = 3;
screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
mobileColumnCount = signal(3);
private readonly MOBILE_BREAKPOINT = 768;
private readonly CARD_ASPECT_RATIO = 7 / 5;
@@ -355,6 +410,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.t
);
private readonly syncBrowserStateEffect = effect(() => {
this.activeLang();
const entityType = this.entityType();
const entity = this.entity();
@@ -424,7 +480,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild(BookTableComponent)
bookTableComponent!: BookTableComponent;
@ViewChild(BookFilterComponent, {static: false})
@ViewChild(BookFilterComponent, {static: true})
bookFilterComponent!: BookFilterComponent;
private scrollContainer: HTMLElement | undefined;
@@ -469,112 +525,80 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
@HostListener('window:resize')
onResize(): void {
this.screenWidth = window.innerWidth;
this.screenWidth.set(window.innerWidth);
}
get isMobile(): boolean {
return this.screenWidth < this.MOBILE_BREAKPOINT;
}
readonly isMobile = computed(() => this.screenWidth() < this.MOBILE_BREAKPOINT);
get mobileCardSize(): { width: number; height: number } {
const columns = this.mobileColumnCount;
readonly mobileCardSize = computed(() => {
const columns = this.mobileColumnCount();
const totalGaps = (columns - 1) * this.MOBILE_GAP;
const availableWidth = this.screenWidth - totalGaps - this.MOBILE_PADDING;
const availableWidth = this.screenWidth() - totalGaps - this.MOBILE_PADDING;
const cardWidth = Math.floor(availableWidth / columns);
const coverHeight = this.isAudiobookOnlyLibrary ? cardWidth : Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
const coverHeight = this.isAudiobookOnlyLibrary() ? cardWidth : Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
const cardHeight = coverHeight + this.MOBILE_TITLE_BAR_HEIGHT;
return {width: cardWidth, height: cardHeight};
}
});
get currentCardSize() {
if (this.isMobile) {
return this.mobileCardSize;
readonly currentCardSize = computed(() => {
if (this.isMobile()) {
return this.mobileCardSize();
}
const base = this.coverScalePreferenceService.currentCardSize();
if (this.isAudiobookOnlyLibrary) {
if (this.isAudiobookOnlyLibrary()) {
const squareSide = Math.round(base.width * 1.1);
return { width: squareSide, height: squareSide + 31 };
}
return base;
}
});
get gridColumnMinWidth(): string {
if (this.isMobile) {
return `${this.mobileCardSize.width}px`;
readonly gridColumnMinWidth = computed(() => {
if (this.isMobile()) {
return `${this.mobileCardSize().width}px`;
}
if (this.isAudiobookOnlyLibrary) {
return `${this.currentCardSize.width}px`;
if (this.isAudiobookOnlyLibrary()) {
return `${this.currentCardSize().width}px`;
}
return this.coverScalePreferenceService.gridColumnMinWidth();
}
});
getCardHeight(_book: Book): number {
if (this.isMobile) {
return this.mobileCardSize.height;
if (this.isMobile()) {
return this.mobileCardSize().height;
}
if (this.isAudiobookOnlyLibrary) {
return this.currentCardSize.height;
if (this.isAudiobookOnlyLibrary()) {
return this.currentCardSize().height;
}
return this.coverScalePreferenceService.getCardHeight(_book);
}
get showBooksLoadingPlaceholder(): boolean {
return !this.booksError() && (this.isBooksLoading() || !this.hasRenderedBooks());
}
readonly showBooksLoadingPlaceholder = computed(() =>
!this.booksError() && !this.hasRenderedBooks()
);
get showTableLoadingPlaceholder(): boolean {
return this.showBooksLoadingPlaceholder && this.currentViewMode === VIEW_MODES.TABLE;
}
readonly showTableLoadingPlaceholder = computed(() =>
this.showBooksLoadingPlaceholder() && this.currentViewMode() === VIEW_MODES.TABLE
);
get showGridLoadingPlaceholder(): boolean {
return this.showBooksLoadingPlaceholder && this.currentViewMode !== VIEW_MODES.TABLE;
}
readonly showGridLoadingPlaceholder = computed(() =>
this.showBooksLoadingPlaceholder() && this.currentViewMode() === VIEW_MODES.GRID
);
get viewIcon(): string {
return this.currentViewMode === VIEW_MODES.TABLE ? 'pi pi-table' : 'pi pi-objects-column';
}
readonly viewIcon = computed(() =>
this.currentViewMode() === VIEW_MODES.TABLE ? 'pi pi-table' : 'pi pi-objects-column'
);
get isFilterActive(): boolean {
readonly isFilterActive = computed(() => {
const selectedFilter = this.selectedFilter();
return !!selectedFilter && Object.keys(selectedFilter).length > 0;
}
});
get computedFilterLabel(): string {
const filters = this.selectedFilter();
if (!filters || Object.keys(filters).length === 0) {
return this.t.translate('book.browser.labels.allBooks');
}
const filterEntries = Object.entries(filters);
if (filterEntries.length === 1) {
const [filterType, values] = filterEntries[0];
const filterName = FilterLabelHelper.getFilterTypeName(filterType);
if (values.length === 1) {
const displayValue = FilterLabelHelper.getFilterDisplayValue(filterType, values[0]);
return `${filterName}: ${displayValue}`;
}
return `${filterName} (${values.length})`;
}
const filterSummary = filterEntries
.map(([type, values]) => `${FilterLabelHelper.getFilterTypeName(type)} (${values.length})`)
.join(', ');
return filterSummary.length > 50
? this.t.translate('book.browser.labels.activeFilters', {count: filterEntries.length})
: filterSummary;
}
get isAudiobookOnlyLibrary(): boolean {
readonly isAudiobookOnlyLibrary = computed(() => {
const entity = this.entity();
if (!entity || this.entityType() !== EntityType.LIBRARY) return false;
const library = entity as Library;
return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK';
}
});
get seriesViewEnabled(): boolean {
return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView);
@@ -597,9 +621,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
ngAfterViewInit(): void {
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(this.parsedFilters);
this.bookFilterComponent.onFiltersChanged?.();
this.bookFilterComponent.selectedFilterMode = this.selectedFilterMode();
this.bookFilterComponent.setFilters(this.parsedFilters);
this.bookFilterComponent.onFilterModeChange(this.selectedFilterMode());
}
}
@@ -620,7 +643,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
* and fetches the next page if necessary.
*/
private checkAndFetchIfNeeded(): void {
if (!this.scrollContainer || this.currentViewMode === VIEW_MODES.TABLE) return;
if (!this.scrollContainer || this.currentViewMode() !== VIEW_MODES.GRID) return;
const {scrollTop, clientHeight} = this.scrollContainer;
const buffer = 1000; // Large buffer to facilitate scroll restoration
@@ -713,11 +736,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (parseResult.filterMode !== this.selectedFilterMode()) {
this.selectedFilterMode.set(parseResult.filterMode);
if (this.bookFilterComponent) {
this.bookFilterComponent.selectedFilterMode = parseResult.filterMode;
this.bookFilterComponent.onFilterModeChange(parseResult.filterMode);
}
}
this.currentFilterLabel = this.t.translate('book.browser.labels.allBooks');
const filterParams = queryParamMap.get('filter');
if (filterParams) {
@@ -725,12 +747,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.selectedFilter.set(parseResult.filters);
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(parseResult.filters);
this.bookFilterComponent.onFiltersChanged?.();
}
if (Object.keys(parseResult.filters).length > 0) {
this.currentFilterLabel = this.computedFilterLabel;
this.bookFilterComponent.setFilters(parseResult.filters);
}
this.rawFilterParamFromUrl = filterParams;
@@ -755,7 +772,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (!this.areSortCriteriaEqual(this.bookSorter.selectedSortCriteria, parseResult.sortCriteria)) {
this.bookSorter.setSortCriteria(parseResult.sortCriteria);
}
this.currentViewMode = parseResult.viewMode;
this.currentViewMode.set(parseResult.viewMode);
if (!this.areSortCriteriaEqual(this.lastAppliedSortCriteria, this.bookSorter.selectedSortCriteria)) {
this.lastAppliedSortCriteria = [...this.bookSorter.selectedSortCriteria];
@@ -764,7 +781,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.queryParamsService.syncQueryParams(
this.currentViewMode!,
this.currentViewMode()!,
this.selectedFilterMode(),
this.parsedFilters
);
@@ -786,9 +803,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.selectedFilter.set(normalizedFilters);
this.rawFilterParamFromUrl = null;
const hasSidebarFilters = !!normalizedFilters && Object.keys(normalizedFilters).length > 0;
this.currentFilterLabel = hasSidebarFilters ? this.computedFilterLabel : this.t.translate('book.browser.labels.allBooks');
this.queryParamsService.updateFilters(normalizedFilters);
}
@@ -896,18 +910,16 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.onMultiSortChange(criteria);
}
get canSaveSort(): boolean {
readonly canSaveSort = computed(() => {
const entityType = this.entityType();
return entityType === EntityType.LIBRARY ||
entityType === EntityType.SHELF ||
entityType === EntityType.MAGIC_SHELF ||
entityType === EntityType.ALL_BOOKS ||
entityType === EntityType.UNSHELVED;
}
});
get hasSearchTerm(): boolean {
return this.searchTerm().trim().length > 0;
}
readonly hasSearchTerm = computed(() => this.searchTerm().trim().length > 0);
onSaveSortConfig(criteria: SortOption[]): void {
const entityType = this.entityType();
@@ -998,7 +1010,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
resetFilters(): void {
this.resetFilterSubject.next();
this.bookFilterComponent?.clearActiveFilter();
}
clearFilter(): void {
@@ -1009,13 +1021,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
toggleTableGrid(): void {
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
this.queryParamsService.updateViewMode(this.currentViewMode as 'grid' | 'table');
const newMode = this.currentViewMode() === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
this.currentViewMode.set(newMode);
this.queryParamsService.updateViewMode(newMode as 'grid' | 'table');
}
onViewModeChange(mode: string): void {
if (mode && mode !== this.currentViewMode) {
this.currentViewMode = mode;
if (mode && mode !== this.currentViewMode()) {
this.currentViewMode.set(mode);
this.queryParamsService.updateViewMode(mode as 'grid' | 'table');
}
}
@@ -1228,14 +1241,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
setMobileColumns(columns: number): void {
this.mobileColumnCount = columns;
this.mobileColumnCount.set(columns);
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
}
private loadMobileColumnsPreference(): void {
const saved = this.localStorageService.get<number>(this.MOBILE_COLUMNS_STORAGE_KEY);
if (saved !== null && [2, 3, 4].includes(saved)) {
this.mobileColumnCount = saved;
this.mobileColumnCount.set(saved);
}
}
}
@@ -5,7 +5,8 @@
<span class="filter-title">{{ t('title') }}</span>
<p-selectButton
[options]="filterModeOptions"
[(ngModel)]="selectedFilterMode"
[ngModel]="selectedFilterMode()"
(ngModelChange)="onFilterModeChange($event)"
optionLabel="label"
optionValue="value"
class="filter-mode-select"
@@ -14,24 +15,24 @@
</div>
<div class="filter-content">
<p-accordion [value]="expandedPanels" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
@for (filterType of visibleFilterTypes; track trackByFilterType(i, filterType); let i = $index) {
<p-accordion [value]="expandedPanels()" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
@for (filterType of visibleFilterTypes(); track filterType; let i = $index) {
<p-accordion-panel [value]="i">
<p-accordion-header>
<span class="filter-type-label">
<span class="filter-label-text">
{{ getFilterLabel(filterType) }}
</span>
@if (activeFilters[filterType]?.length) {
@if (activeFilters()[filterType]?.length; as count) {
<span class="active-filter-count">
({{ activeFilters[filterType].length }})
({{ count }})
</span>
}
</span>
</p-accordion-header>
<p-accordion-content>
@if (expandedPanels.includes(i)) {
@if (expandedPanels().includes(i)) {
@if (filterSignals[filterType](); as filters) {
@if (filters.length > 0) {
<cdk-virtual-scroll-viewport
@@ -44,8 +45,8 @@
role="button"
tabindex="0"
[ngClass]="{
'active': activeFilters[filterType]?.includes(getFilterValueId(filter)),
'active-not': activeFilters[filterType]?.includes(getFilterValueId(filter)) && selectedFilterMode === 'not'
'active': isActive(filterType, getFilterValueId(filter)),
'active-not': isActive(filterType, getFilterValueId(filter)) && selectedFilterMode() === 'not'
}"
(click)="handleFilterClick(filterType, getFilterValueId(filter))"
(keydown.enter)="handleFilterClick(filterType, getFilterValueId(filter))">
@@ -54,11 +55,6 @@
</div>
</cdk-virtual-scroll-viewport>
}
@if (truncatedFilters[filterType]) {
<div class="truncation-notice">
{{ t('showingFirst100') }}
</div>
}
}
}
</p-accordion-content>
@@ -1,8 +1,4 @@
import {ChangeDetectionStrategy, Component, effect, EventEmitter, inject, Input, OnDestroy, OnInit, Output, Signal, signal} from '@angular/core';
import {Subject, takeUntil} from 'rxjs';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {EntityType} from '../book-browser.component';
import {ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal, Signal} from '@angular/core';
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
import {CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
import {NgClass} from '@angular/common';
@@ -10,7 +6,6 @@ import {Badge} from 'primeng/badge';
import {FormsModule} from '@angular/forms';
import {SelectButton} from 'primeng/selectbutton';
import {BookFilterMode, DEFAULT_VISIBLE_FILTERS, UserService, VisibleFilterType} from '../../../../settings/user-management/user.service';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
import {BookFilterService} from './book-filter.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@@ -33,57 +28,32 @@ interface FilterModeOption {
TranslocoDirective
]
})
export class BookFilterComponent implements OnInit, OnDestroy {
@Input() set entity(value: Library | Shelf | MagicShelf | null | undefined) {
this.entitySignal.set(value ?? null);
}
@Input() set entityType(value: EntityType | undefined) {
this.entityTypeSignal.set(value ?? EntityType.ALL_BOOKS);
}
@Input() resetFilter$!: Subject<void>;
@Input() showFilter = false;
export class BookFilterComponent {
readonly showFilter = input(false);
@Output() filterSelected = new EventEmitter<Record<string, unknown> | null>();
@Output() filterModeChanged = new EventEmitter<BookFilterMode>();
readonly filterSelected = output<Record<string, unknown> | null>();
readonly filterModeChanged = output<BookFilterMode>();
private readonly filterService = inject(BookFilterService);
private readonly userService = inject(UserService);
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
private readonly entitySignal = signal<Library | Shelf | MagicShelf | null>(null);
private readonly entityTypeSignal = signal<EntityType>(EntityType.ALL_BOOKS);
private readonly activeFiltersSignal = signal<Record<string, unknown[]> | null>(null);
private readonly filterModeSignal = signal<BookFilterMode>('and');
/** 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[];
activeFilters: Record<string, unknown[]> = {};
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
this.entitySignal,
this.entityTypeSignal,
this.activeFiltersSignal,
this.filterModeSignal
);
filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
visibleFilterTypes: FilterType[] = [];
expandedPanels: number[] = [];
truncatedFilters: Record<string, boolean> = {};
readonly activeFilters = signal<Record<string, unknown[]>>({});
readonly expandedPanels = signal<number[]>([]);
private _selectedFilterMode: BookFilterMode = 'and';
private _visibleFilters: VisibleFilterType[] = [...DEFAULT_VISIBLE_FILTERS];
private readonly visibleFilters = signal<VisibleFilterType[]>([...DEFAULT_VISIBLE_FILTERS]);
readonly visibleFilterTypes = computed(() => {
const vf = this.visibleFilters();
return vf.filter(f => this.filterTypes.includes(f as FilterType)) as FilterType[];
});
readonly filterLabelKeys = FILTER_LABEL_KEYS;
private readonly userSettingsEffect = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this._visibleFilters = user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
this.updateVisibleFilterTypes();
});
getFilterLabel(type: FilterType): string {
const key = this.filterLabelKeys[type];
return key ? this.t.translate(key) : type;
}
readonly filterModeOptions: FilterModeOption[] = [
{label: 'AND', value: 'and'},
{label: 'OR', value: 'or'},
@@ -91,31 +61,29 @@ export class BookFilterComponent implements OnInit, OnDestroy {
{label: '1', value: 'single'}
];
get selectedFilterMode(): BookFilterMode {
return this._selectedFilterMode;
}
private readonly _selectedFilterMode = signal<BookFilterMode>('and');
readonly selectedFilterMode = this._selectedFilterMode.asReadonly();
set selectedFilterMode(mode: BookFilterMode) {
if (mode === this._selectedFilterMode) return;
this._selectedFilterMode = mode;
this.filterModeSignal.set(mode);
private readonly syncUserSettings = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this.visibleFilters.set(user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS]);
});
onFilterModeChange(mode: BookFilterMode): void {
if (mode === this._selectedFilterMode()) return;
this._selectedFilterMode.set(mode);
this.filterModeChanged.emit(mode);
this.emitFilters();
}
ngOnInit(): void {
this.updateVisibleFilterTypes();
this.updateExpandedPanels();
this.subscribeToReset();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
getFilterLabel(type: FilterType): string {
const key = this.filterLabelKeys[type];
return key ? this.t.translate(key) : type;
}
handleFilterClick(filterType: string, value: unknown): void {
if (this._selectedFilterMode === 'single') {
if (this._selectedFilterMode() === 'single') {
this.handleSingleMode(filterType, value);
} else {
this.handleMultiMode(filterType, value);
@@ -124,35 +92,34 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
setFilters(filters: Record<string, unknown>): void {
this.activeFilters = {};
const result: Record<string, unknown[]> = {};
for (const [key, value] of Object.entries(filters)) {
const values = Array.isArray(value) ? value : [value];
this.activeFilters[key] = values.map(v => this.filterService.processFilterValue(key, v));
result[key] = values.map(v => this.filterService.processFilterValue(key, v));
}
this.activeFilters.set(result);
this.emitFilters();
}
clearActiveFilter(): void {
this.activeFilters = {};
this.expandedPanels = [];
this.activeFiltersSignal.set(null);
this.activeFilters.set({});
this.expandedPanels.set([]);
this.filterSelected.emit(null);
}
onExpandedPanelsChange(value: string | number | string[] | number[] | null | undefined): void {
if (Array.isArray(value)) {
this.expandedPanels = value.map(Number);
const panels = value.map(Number);
if (JSON.stringify(panels) !== JSON.stringify(this.expandedPanels())) {
this.expandedPanels.set(panels);
}
}
}
onFiltersChanged(): void {
this.updateExpandedPanels();
getVirtualScrollHeight(itemCount: number): number {
return Math.min(itemCount * 28, 440);
}
getVirtualScrollHeight = (itemCount: number): number => Math.min(itemCount * 28, 440);
trackByFilterType = (_: number, type: FilterType): string => type;
trackByFilter = (_: number, f: Filter): unknown => this.getFilterValueId(f);
getFilterValueId(f: Filter): unknown {
@@ -170,45 +137,41 @@ export class BookFilterComponent implements OnInit, OnDestroy {
return String(value ?? '');
}
private updateVisibleFilterTypes(): void {
this.visibleFilterTypes = this._visibleFilters.filter(
vf => this.filterTypes.includes(vf as FilterType)
) as FilterType[];
}
private subscribeToReset(): void {
this.resetFilter$?.pipe(takeUntil(this.destroy$)).subscribe(() => this.clearActiveFilter());
isActive(filterType: string, filterId: unknown): boolean {
const active = this.activeFilters()[filterType];
if (!active) return false;
return active.some(v => v === filterId || String(v) === String(filterId));
}
private handleSingleMode(filterType: string, value: unknown): void {
const id = this.extractId(value);
const current = this.activeFilters[filterType];
const current = this.activeFilters()[filterType];
const isSame = current?.length === 1 && this.valuesMatch(current[0], id);
this.activeFilters = isSame ? {} : {[filterType]: [id]};
this.activeFilters.set(isSame ? {} : {[filterType]: [id]});
}
private handleMultiMode(filterType: string, value: unknown): void {
const id = this.extractId(value);
const current = {...this.activeFilters()};
const arr = [...(current[filterType] ?? [])];
if (!this.activeFilters[filterType]) {
this.activeFilters[filterType] = [];
}
const arr = this.activeFilters[filterType];
const index = arr.findIndex(v => this.valuesMatch(v, id));
if (index > -1) {
arr.splice(index, 1);
if (arr.length === 0) delete this.activeFilters[filterType];
if (arr.length === 0) {
delete current[filterType];
} else {
current[filterType] = arr;
}
} else {
arr.push(id);
current[filterType] = [...arr, id];
}
this.activeFilters.set(current);
}
private extractId(value: unknown): unknown {
return typeof value === 'object' && value !== null && 'id' in value
? (value as { id: unknown }).id
? (value as {id: unknown}).id
: value;
}
@@ -217,17 +180,16 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
private emitFilters(): void {
const hasFilters = Object.keys(this.activeFilters).length > 0;
const filtersToEmit = hasFilters ? {...this.activeFilters} : null;
this.activeFiltersSignal.set(filtersToEmit);
this.filterSelected.emit(filtersToEmit);
}
const filters = this.activeFilters();
const hasFilters = Object.keys(filters).length > 0;
this.filterSelected.emit(hasFilters ? {...filters} : null);
private updateExpandedPanels(): void {
// Update expanded panels to show panels with active filters
const panels = new Set<number>();
this.visibleFilterTypes.forEach((type, i) => {
if (this.activeFilters[type]?.length) panels.add(i);
const types = this.visibleFilterTypes();
types.forEach((type, i) => {
if (filters[type]?.length) panels.add(i);
});
this.expandedPanels = [...panels];
this.expandedPanels.set([...panels]);
}
}
@@ -58,6 +58,10 @@ describe('book-filter.config', () => {
expect(FILTER_EXTRACTORS.contentRating(makeBook({
metadata: {bookId: 1, contentRating: 'EVERYONE'}
}))).toEqual([{id: 'EVERYONE', name: CONTENT_RATING_LABELS['EVERYONE']}]);
expect(FILTER_EXTRACTORS.ageRating(makeBook({
metadata: {bookId: 1, ageRating: 12}
}))).toEqual([{id: 10, name: '10+', sortIndex: 2}]);
});
it('builds comic creator filters with role-aware labels', () => {
@@ -79,10 +79,10 @@ export const FILE_SIZE_RANGES: readonly RangeConfig[] = [
{id: 1, label: '1–10 MB', min: 1024, max: 10240, sortIndex: 1},
{id: 2, label: '10–50 MB', min: 10240, max: 51200, sortIndex: 2},
{id: 3, label: '50–100 MB', min: 51200, max: 102400, sortIndex: 3},
{id: 4, label: '250–500 MB', min: 256000, max: 512000, sortIndex: 4},
{id: 4, label: '100–500 MB', min: 102400, max: 512000, sortIndex: 4},
{id: 5, label: '0.5–1 GB', min: 512000, max: 1048576, sortIndex: 5},
{id: 6, label: '1–2 GB', min: 1048576, max: 2097152, sortIndex: 6},
{id: 7, label: '5+ GB', min: 5242880, max: Infinity, sortIndex: 7}
{id: 7, label: '2+ GB', min: 2097152, max: Infinity, sortIndex: 7}
];
export const PAGE_COUNT_RANGES: readonly RangeConfig[] = [
@@ -106,13 +106,13 @@ export const MATCH_SCORE_RANGES: readonly RangeConfig[] = [
];
export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [
{id: 0, min: 0, max: 1, label: 'All Ages', sortIndex: 0},
{id: 6, min: 6, max: 7, label: '6+', sortIndex: 1},
{id: 10, min: 10, max: 11, label: '10+', sortIndex: 2},
{id: 13, min: 13, max: 14, label: '13+', sortIndex: 3},
{id: 16, min: 16, max: 17, label: '16+', sortIndex: 4},
{id: 18, min: 18, max: 19, label: '18+', sortIndex: 5},
{id: 21, min: 21, max: 22, label: '21+', sortIndex: 6}
{id: 0, min: 0, max: 6, label: 'All Ages', sortIndex: 0},
{id: 6, min: 6, max: 10, label: '6+', sortIndex: 1},
{id: 10, min: 10, max: 13, label: '10+', sortIndex: 2},
{id: 13, min: 13, max: 16, label: '13+', sortIndex: 3},
{id: 16, min: 16, max: 18, label: '16+', sortIndex: 4},
{id: 18, min: 18, max: 21, label: '18+', sortIndex: 5},
{id: 21, min: 21, max: Infinity, label: '21+', sortIndex: 6}
];
export const CONTENT_RATING_LABELS: Readonly<Record<string, string>> = {
@@ -129,6 +129,7 @@ export const ratingOptions10 = RATING_OPTIONS_10;
export const fileSizeRanges = FILE_SIZE_RANGES;
export const pageCountRanges = PAGE_COUNT_RANGES;
export const matchScoreRanges = MATCH_SCORE_RANGES;
export const ageRatingRanges = AGE_RATING_OPTIONS;
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
@@ -193,12 +194,6 @@ const extractStringsAsFilters = (values: string[] | undefined): FilterValue[] =>
const extractSingleString = (value: string | undefined | null): FilterValue[] =>
value ? [{id: value, name: value}] : [];
const findExactAgeRating = (ageRating: number | null | undefined): FilterValue[] => {
if (ageRating == null) return [];
const match = AGE_RATING_OPTIONS.find(r => r.id === ageRating);
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
};
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
author: (book) => extractStringsAsFilters(book.metadata?.authors),
category: (book) => extractStringsAsFilters(book.metadata?.categories),
@@ -231,7 +226,7 @@ export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>,
language: (book) => extractSingleString(book.metadata?.language),
pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES),
mood: (book) => extractStringsAsFilters(book.metadata?.moods),
ageRating: (book) => findExactAgeRating(book.metadata?.ageRating),
ageRating: (book) => findInRange(book.metadata?.ageRating, AGE_RATING_OPTIONS),
contentRating: (book) => {
const rating = book.metadata?.contentRating;
if (!rating) return [];
@@ -3,96 +3,38 @@ 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 {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';
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 {
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';
const MAX_FILTER_ITEMS = 100;
import {ReadStatus} from '../../../model/book.model';
@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',
]);
/** 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 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);
});
get filterSignals(): Record<FilterType, Signal<Filter[]>> {
if (!this._filterSignals) {
this._filterSignals = this.buildFilterSignals();
}
// 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);
});
}
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 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) || `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
}
return signals;
return this._filterSignals;
}
filterBooksByEntity(
@@ -130,6 +72,78 @@ 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['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':
@@ -152,9 +166,78 @@ export class BookFilterService {
bookCount: lang.count,
}));
case 'readStatus':
return this.countedToFilters(options.readStatuses);
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 '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 [];
}
@@ -167,53 +250,20 @@ export class BookFilterService {
}));
}
private buildAndSortFilters(
books: Book[],
extractor: (book: Book) => FilterValue[],
sortMode: SortMode
private rangedFilters(
items: CountedOption[] | undefined,
ranges: readonly {id: number; label: string; sortIndex: number}[]
): Filter[] {
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);
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
};
});
}
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 {
@@ -5,6 +5,7 @@ import {
doesBookMatchFilter,
doesBookMatchReadStatus,
filterBooksByFilters,
isAgeRatingInRange,
isFileSizeInRange,
isMatchScoreInRange,
isPageCountInRange,
@@ -63,6 +64,8 @@ describe('sidebar-filter', () => {
expect(isFileSizeInRange(undefined, 1)).toBe(false);
expect(isFileSizeInRange(1500, 1)).toBe(true);
expect(isPageCountInRange(230, '3')).toBe(true);
expect(isAgeRatingInRange(16, 16)).toBe(true);
expect(isAgeRatingInRange(12, 10)).toBe(true);
expect(isMatchScoreInRange(87, 2)).toBe(true);
expect(isMatchScoreInRange(87, 9)).toBe(false);
expect(doesBookMatchReadStatus(makeBook(1), [ReadStatus.UNREAD])).toBe(true);
@@ -1,4 +1,4 @@
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
import {ageRatingRanges, fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
import {Book, ReadStatus} from '../../../model/book.model';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
@@ -41,6 +41,14 @@ export function isMatchScoreInRange(score: number | undefined | null, rangeId: s
return normalizedScore >= range.min && normalizedScore < range.max;
}
export function isAgeRatingInRange(ageRating: number | undefined | null, rangeId: string | number): boolean {
if (ageRating == null) return false;
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
const range = ageRatingRanges.find(r => r.id === numericId);
if (!range) return false;
return ageRating >= range.min && ageRating < range.max;
}
export function doesBookMatchReadStatus(book: Book, selected: unknown[]): boolean {
const status = book.readStatus ?? ReadStatus.UNSET;
return selected.includes(status);
@@ -122,10 +130,7 @@ export function doesBookMatchFilter(
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
: filterValues.every(val => book.metadata?.moods?.includes(val as string));
case 'ageRating':
return filterValues.some(val => {
const numVal = typeof val === 'string' ? Number(val) : val;
return book.metadata?.ageRating === numVal;
});
return filterValues.some(range => isAgeRatingInRange(book.metadata?.ageRating, range as string | number));
case 'contentRating':
return filterValues.includes(book.metadata?.contentRating);
case 'narrator':