feat(search): add ISBN & genre filters; disable author/category filters in drawer for performance

This commit is contained in:
aditya.chandel
2025-08-25 10:24:12 -06:00
committed by Aditya Chandel
parent 2be27f34ad
commit 0e4fb47580
8 changed files with 62 additions and 84 deletions
@@ -173,12 +173,12 @@
<i class="pi pi-search"></i>
</button>
<p-popover #searchDropdown [dismissable]="true" appendTo="body" [style]="{ width: '18rem' }">
<p-popover #searchDropdown [dismissable]="true" appendTo="body" [style]="{ width: '24rem' }">
<div class="relative w-full">
<input
type="text"
pInputText
placeholder="Title, Series or Author..."
placeholder="Title, Author, Series, Genre, or ISBN..."
[(ngModel)]="bookTitle"
(ngModelChange)="onSearchTermChange($event)"
class="w-full"
@@ -200,7 +200,7 @@
<input
type="text"
pInputText
placeholder="Title, Series or Author..."
placeholder="Title, Author, Series, Genre, or ISBN..."
[(ngModel)]="bookTitle"
(ngModelChange)="onSearchTermChange($event)"
class="search-input"
@@ -96,11 +96,12 @@
}
.search-input {
width: 100%;
min-width: 22rem;
padding-left: 30px;
height: 2.5rem;
line-height: 2.5rem;
font-size: 1rem;
box-sizing: border-box;
}
.mobile-filter-mask {
@@ -14,7 +14,7 @@
<div class="flex-1 overflow-y-auto pb-4 pr-1" style="overscroll-behavior: contain;">
<p-accordion [value]="expandedPanels">
@for (filterType of filterTypes; track filterType; let i = $index) {
@for (filterType of filterTypes; track trackByFilterType(i, filterType); let i = $index) {
<p-accordion-panel [value]="i">
<p-accordion-header>
<span class="inline-flex items-center gap-1">
@@ -32,7 +32,7 @@
<div
class="max-h-[27.5rem] overflow-y-auto overscroll-contain pr-1"
style="overscroll-behavior: contain;">
@for (filter of filters; track filter) {
@for (filter of filters; track trackByFilter(j, filter); let j = $index) {
<div
class="cursor-pointer transition-colors duration-200 ease-in-out pb-1 flex items-center gap-2"
[ngClass]="{
@@ -1,6 +1,6 @@
import {Component, EventEmitter, inject, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {combineLatest, Observable, of, Subject, takeUntil} from 'rxjs';
import {distinctUntilChanged, map} from 'rxjs/operators';
import {Component, EventEmitter, ChangeDetectionStrategy, inject, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {combineLatest, Observable, of, Subject, debounceTime, distinctUntilChanged, takeUntil, shareReplay} from 'rxjs';
import {map} from 'rxjs/operators';
import {BookService} from '../../../service/book.service';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
@@ -133,6 +133,7 @@ function getReadStatusName(status?: ReadStatus | null): string {
selector: 'app-book-filter',
templateUrl: './book-filter.component.html',
styleUrls: ['./book-filter.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [
Accordion,
@@ -148,8 +149,10 @@ function getReadStatusName(status?: ReadStatus | null): string {
]
})
export class BookFilterComponent implements OnInit, OnDestroy {
private filterChangeSubject = new Subject<Record<string, any> | null>();
@Output() filterSelected = new EventEmitter<Record<string, any> | null>();
@Output() filterModeChanged = new EventEmitter<'and' | 'or'>();
@Output('filterMode') filterModeChanged = new EventEmitter<'and' | 'or'>();
@Input() entity$!: Observable<Library | Shelf | MagicShelf | null> | undefined;
@Input() entityType$!: Observable<EntityType> | undefined;
@@ -199,9 +202,10 @@ export class BookFilterComponent implements OnInit, OnDestroy {
.pipe(takeUntil(this.destroy$))
.subscribe(([sortMode]) => {
this.filterStreams = {
author: this.getFilterStream((book: Book) => book.metadata?.authors!.map(name => ({id: name, name})) || [], 'id', 'name', sortMode),
// Temporarily disabled until we can optimize for large libraries
/*author: this.getFilterStream((book: Book) => book.metadata?.authors!.map(name => ({id: name, name})) || [], 'id', 'name', sortMode),
category: this.getFilterStream((book: Book) => book.metadata?.categories!.map(name => ({id: name, name})) || [], 'id', 'name', sortMode),
series: this.getFilterStream((book) => (book.metadata?.seriesName ? [{id: book.metadata.seriesName, name: book.metadata.seriesName}] : []), 'id', 'name', sortMode),
series: this.getFilterStream((book) => (book.metadata?.seriesName ? [{id: book.metadata.seriesName, name: book.metadata.seriesName}] : []), 'id', 'name', sortMode),*/
publisher: this.getFilterStream((book) => (book.metadata?.publisher ? [{id: book.metadata.publisher, name: book.metadata.publisher}] : []), 'id', 'name', sortMode),
readStatus: this.getFilterStream((book: Book) => {
let status = book.readStatus;
@@ -226,6 +230,11 @@ export class BookFilterComponent implements OnInit, OnDestroy {
this.setExpandedPanels();
});
this.filterChangeSubject.pipe(
debounceTime(10),
takeUntil(this.destroy$)
).subscribe(value => this.filterSelected.emit(value));
if (this.resetFilter$) {
this.resetFilter$.pipe(takeUntil(this.destroy$)).subscribe(() => this.clearActiveFilter());
}
@@ -270,7 +279,8 @@ export class BookFilterComponent implements OnInit, OnDestroy {
a.value[nameKey].toString().localeCompare(b.value[nameKey].toString())
);
});
})
}),
shareReplay({bufferSize: 1, refCount: true})
);
}
@@ -281,6 +291,9 @@ export class BookFilterComponent implements OnInit, OnDestroy {
set selectedFilterMode(mode: 'and' | 'or') {
this._selectedFilterMode = mode;
this.filterModeChanged.emit(mode);
this.filterChangeSubject.next(
Object.keys(this.activeFilters).length ? {...this.activeFilters} : null
);
}
private filterBooksByEntityType(books: Book[], entity: any, entityType: EntityType): Book[] {
@@ -320,11 +333,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
this.activeFilters[filterType].push(value);
}
if (Object.keys(this.activeFilters).length === 0) {
this.filterSelected.emit(null);
} else {
this.filterSelected.emit({...this.activeFilters});
}
this.filterChangeSubject.next(Object.keys(this.activeFilters).length ? {...this.activeFilters} : null);
}
setFilters(filters: Record<string, any>) {
@@ -337,12 +346,12 @@ export class BookFilterComponent implements OnInit, OnDestroy {
this.activeFilters[key] = [value];
}
}
this.filterSelected.emit({...this.activeFilters});
this.filterChangeSubject.next({...this.activeFilters});
}
clearActiveFilter() {
this.activeFilters = {};
this.filterSelected.emit(null);
this.filterChangeSubject.next(null);
}
setExpandedPanels(): void {
@@ -356,6 +365,14 @@ export class BookFilterComponent implements OnInit, OnDestroy {
this.setExpandedPanels();
}
trackByFilterType(_: number, type: string): string {
return type;
}
trackByFilter(_: number, filter: Filter<any>): any {
return filter.value.id ?? filter.value;
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
@@ -1,7 +1,7 @@
import {BookFilter} from './BookFilter';
import {BookState} from '../../../model/state/book-state.model';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {map, debounceTime, distinctUntilChanged} from 'rxjs/operators';
export class HeaderFilter implements BookFilter {
@@ -13,6 +13,8 @@ export class HeaderFilter implements BookFilter {
str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
return this.searchTerm$.pipe(
debounceTime(500),
distinctUntilChanged(),
map(term => {
const normalizedTerm = normalize(term || '');
if (normalizedTerm && normalizedTerm.trim() !== '') {
@@ -20,10 +22,17 @@ export class HeaderFilter implements BookFilter {
const title = book.metadata?.title || '';
const series = book.metadata?.seriesName || '';
const authors = book.metadata?.authors || [];
const categories = book.metadata?.categories || [];
const isbn = book.metadata?.isbn10 || '';
const isbn13 = book.metadata?.isbn13 || '';
const matchesTitle = normalize(title).includes(normalizedTerm);
const matchesSeries = normalize(series).includes(normalizedTerm);
const matchesAuthor = authors.some(author => normalize(author).includes(normalizedTerm));
return matchesTitle || matchesSeries || matchesAuthor;
const matchesCategory = categories.some(category => normalize(category).includes(normalizedTerm));
const matchesIsbn = normalize(isbn).includes(normalizedTerm) || normalize(isbn13).includes(normalizedTerm);
return matchesTitle || matchesSeries || matchesAuthor || matchesCategory || matchesIsbn;
}) || null;
return {...bookState, books: filteredBooks};
}
@@ -7,7 +7,7 @@
pInputText
[(ngModel)]="searchQuery"
(input)="onSearchInputChange()"
placeholder="Search books by title or author..."
placeholder="Title, Author, Series, Genre, or ISBN..."
class="w-full pr-10"
/>
@if (searchQuery) {
@@ -22,29 +22,6 @@
}
</p-iconfield>
<!--<div class="sm:hidden flex items-center">
<p-button
icon="pi pi-search"
(click)="toggleSearchInputDropdown()"
[rounded]="true">
</p-button>
</div>
&lt;!&ndash; Dropdown input for small screens &ndash;&gt;
@if (isSearchDropdownOpen) {
<div class="absolute z-10 shadow-md rounded-md mt-2 w-56 sm:hidden">
<input
type="text"
pInputText
[(ngModel)]="searchQuery"
(input)="onSearchInputChange()"
(blur)="closeSearchDropdown()"
placeholder="Search books..."
class="w-full"
/>
</div>
}-->
<!-- Search results below small screen search input -->
@if (books.length > 0 || searchQuery) {
<div
@@ -1,6 +1,6 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {of, Subject, Subscription} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {BehaviorSubject, of, Subject, Subscription} from 'rxjs';
import {catchError, switchMap} from 'rxjs/operators';
import {Book} from '../../model/book.model';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
@@ -12,6 +12,7 @@ import {UrlHelperService} from '../../../utilities/service/url-helper.service';
import {Router} from '@angular/router';
import {IconField} from 'primeng/iconfield';
import {InputIcon} from 'primeng/inputicon';
import {HeaderFilter} from '../book-browser/filters/HeaderFilter';
@Component({
selector: 'app-book-searcher',
@@ -31,41 +32,29 @@ import {InputIcon} from 'primeng/inputicon';
export class BookSearcherComponent implements OnInit, OnDestroy {
searchQuery: string = '';
books: Book[] = [];
#searchSubject = new Subject<string>();
#searchSubject = new BehaviorSubject<string>('');
#subscription!: Subscription;
private bookService = inject(BookService);
private router = inject(Router);
protected urlHelper = inject(UrlHelperService);
isSearchDropdownOpen = false;
toggleSearchInputDropdown() {
this.isSearchDropdownOpen = !this.isSearchDropdownOpen;
}
closeSearchDropdown() {
this.isSearchDropdownOpen = false;
}
private headerFilter = new HeaderFilter(this.#searchSubject.asObservable());
ngOnInit(): void {
this.initializeSearch();
}
initializeSearch(): void {
this.#subscription = this.#searchSubject.pipe(
debounceTime(350),
distinctUntilChanged(),
switchMap((query) => {
const result = this.bookService.searchBooks(query);
return of(result);
}),
this.#subscription = this.bookService.bookState$.pipe(
switchMap(bookState => this.headerFilter.filter(bookState)),
catchError((error) => {
console.error('Error while searching books:', error);
return of([]);
return of({books: [], loaded: true, error: null});
})
).subscribe({
next: (result: Book[]) => this.books = result,
next: (filteredState) => {
this.books = this.searchQuery.trim() ? (filteredState.books || []) : [];
},
error: (error) => console.error('Subscription error:', error)
});
}
@@ -191,21 +191,6 @@ export class BookService {
this.updateLastReadTime(book.id);
}
searchBooks(query: string): Book[] {
if (query.length < 2) {
return [];
}
const normalize = (str: string): string => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
const normalizedQuery = normalize(query);
const state = this.bookStateSubject.value;
return (state.books || []).filter(book => {
const title = book.metadata?.title;
const authors = book.metadata?.authors || [];
return (title && normalize(title).includes(normalizedQuery)) ||
authors.some(author => normalize(author).includes(normalizedQuery));
});
}
getFileContent(bookId: number): Observable<Blob> {
return this.http.get<Blob>(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'});
}
@@ -331,7 +316,7 @@ export class BookService {
if (currentState.books) {
const updatedBooks = currentState.books.map(book => {
if (book.id === bookId) {
return { ...book, dateFinished: dateFinished || undefined };
return {...book, dateFinished: dateFinished || undefined};
}
return book;
});