Add option to collapse books in a series

This commit is contained in:
aditya.chandel
2025-06-10 18:21:56 -06:00
committed by Aditya Chandel
parent 24eac9ea76
commit 6596c3298b
19 changed files with 745 additions and 512 deletions
@@ -0,0 +1,54 @@
import {inject, Injectable} from '@angular/core';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component';
import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
@Injectable({providedIn: 'root'})
export class BookDialogHelperService {
private dialogService = inject(DialogService);
openShelfAssigner(bookIds: Set<number>): DynamicDialogRef {
return this.dialogService.open(ShelfAssignerComponent, {
header: `Update Books' Shelves`,
modal: true,
closable: true,
contentStyle: {overflow: 'auto'},
baseZIndex: 10,
style: {
position: 'absolute',
top: '15%',
},
data: {
isMultiBooks: true,
bookIds,
},
});
}
openLockUnlockMetadataDialog(bookIds: Set<number>): DynamicDialogRef {
const count = bookIds.size;
return this.dialogService.open(LockUnlockMetadataDialogComponent, {
header: `Lock or Unlock Metadata for ${count} Selected Book${count > 1 ? 's' : ''}`,
modal: true,
closable: true,
data: {
bookIds: Array.from(bookIds),
},
});
}
openMetadataRefreshDialog(bookIds: Set<number>): DynamicDialogRef {
return this.dialogService.open(MetadataFetchOptionsComponent, {
header: 'Metadata Refresh Options',
modal: true,
closable: true,
data: {
bookIds: Array.from(bookIds),
metadataRefreshType: MetadataRefreshType.BOOKS,
},
});
}
}
@@ -0,0 +1,59 @@
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {inject, Injectable} from '@angular/core';
import {MessageService} from 'primeng/api';
import {UserService} from '../../../settings/user-management/user.service';
@Injectable({
providedIn: 'root'
})
export class CoverScaleManager {
private readonly baseWidth = 135;
private readonly baseHeight = 220;
private readonly messageService = inject(MessageService);
private readonly userService = inject(UserService);
private readonly scaleChangeSubject = new Subject<number>();
readonly scaleChange$ = this.scaleChangeSubject.asObservable();
scaleFactor = 1.0;
constructor() {
this.scaleChange$
.pipe(debounceTime(1000))
.subscribe(scale => this.persistScale(scale));
}
setScale(scale: number): void {
this.scaleFactor = scale;
this.scaleChangeSubject.next(scale);
}
get currentCardSize(): { width: number; height: number } {
return {
width: Math.round(this.baseWidth * this.scaleFactor),
height: Math.round(this.baseHeight * this.scaleFactor),
};
}
get gridColumnMinWidth(): string {
return `${this.currentCardSize.width}px`;
}
private persistScale(scale: number): void {
const user = this.userService.getCurrentUser();
const entityViewPreferences = user?.userSettings?.entityViewPreferences;
if (!user || !entityViewPreferences) {
return;
}
entityViewPreferences.global = entityViewPreferences.global ?? {};
entityViewPreferences.global.coverSize = scale;
this.userService.updateUserSetting(user.id, 'entityViewPreferences', entityViewPreferences);
this.messageService.add({
severity: 'success',
summary: 'Cover Size Saved',
detail: `Cover size set to ${scale.toFixed(2)}x.`
});
}
}
@@ -32,7 +32,6 @@
</div>
<div class="flex items-center gap-8">
<div class="flex flex-row items-center gap-6">
@if (isFilterActive) {
<a class="topbar-items topbar-item" (click)="clearFilter()">
@@ -43,7 +42,28 @@
</i>
</a>
}
<div>
<a
class="topbar-items topbar-item"
(click)="seriesCollapseOverlay.toggle($event)"
pTooltip="Series collapse settings"
tooltipPosition="top">
<i class="pi pi-cog"></i>
</a>
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
<div class="w-[220px] p-2">
<div class="flex items-center gap-2">
<p-checkbox
[binary]="true"
[ngModel]="seriesCollapseFilter.isSeriesCollapsed"
(onChange)="onSeriesCollapseCheckboxChange($event.checked)"
inputId="collapse-series-checkbox">
</p-checkbox>
<label for="collapse-series-checkbox">Collapse series</label>
</div>
</div>
</p-popover>
</div>
<div>
<a
class="topbar-items topbar-item"
@@ -52,11 +72,10 @@
tooltipPosition="top">
<i class="pi pi-th-large"></i>
</a>
<p-popover #sizeOverlay [dismissable]="true" appendTo="body">
<div style="width: 220px; padding: 8px;">
<p-slider
[(ngModel)]="scaleFactor"
[(ngModel)]="coverScaleManager.scaleFactor"
[min]="0.5"
[max]="1.5"
[step]="0.01"
@@ -64,7 +83,7 @@
(onChange)="updateScale()"
></p-slider>
<div style="text-align: center; margin-top: 8px;">
{{ scaleFactor.toFixed(2) }}x
{{ coverScaleManager.scaleFactor.toFixed(2) }}x
</div>
</div>
</p-popover>
@@ -78,9 +97,9 @@
tooltipPosition="top">
</i>
</a>
<p-menu #sortMenu [popup]="true" [model]="sortOptions" appendTo="body">
<p-menu #sortMenu [popup]="true" [model]="this.bookSorter.sortOptions" appendTo="body">
<ng-template pTemplate="item" let-item>
<div class="flex justify-between items-center px-4 py-2 cursor-pointer" (click)="sortBooks(item.field)">
<div class="flex justify-between items-center px-4 py-2 cursor-pointer" (click)="this.bookSorter.sortBooks(item.field)">
<span>{{ item.label }}</span>
@if (item.icon) {
<i [class]="item.icon"></i>
@@ -108,7 +127,8 @@
placeholder="Title, Series or Author..."
[(ngModel)]="bookTitle"
(ngModelChange)="onSearchTermChange($event)"
class="search-input"/>
class="search-input"
/>
@if (bookTitle) {
<p-button
icon="pi pi-times"
@@ -130,7 +150,8 @@
[rounded]="true"
(click)="toggleFilterSidebar()"
pTooltip="Toggle filter sidebar"
tooltipPosition="top"/>
tooltipPosition="top"
/>
</div>
</div>
@@ -159,8 +180,11 @@
@if (bookState?.books; as books) {
<div class="book-card-container">
@if (currentViewMode === 'table' && books.length > 0) {
<app-book-table [books]="books" (selectedBooksChange)="onSelectedBooksChange($event)"
[sortOption]="selectedSort!"></app-book-table>
<app-book-table
[books]="books"
(selectedBooksChange)="onSelectedBooksChange($event)"
[sortOption]="this.bookSorter.selectedSort!"
></app-book-table>
}
@if (currentViewMode === 'grid') {
<virtual-scroller class="virtual-scroller" #scroll [items]="books">
@@ -170,12 +194,13 @@
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
@for (book of scroll.viewPortItems; track book) {
<div
class="virtual-scroller-item"
class="virtual-scroller-item relative"
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
<app-book-card
[book]="book"
[isCheckboxEnabled]="true"
[onBookSelect]="handleBookSelect.bind(this)"
[isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed"
[isSelected]="selectedBooks.has(book.id)">
</app-book-card>
</div>
@@ -249,5 +274,4 @@
</div>
<app-book-filter [entity$]="entity$" [entityType$]="entityType$" [resetFilter$]="resetFilterSubject"></app-book-filter>
</div>
@@ -4,10 +4,9 @@ import {MenuItem, MessageService, PrimeTemplate} from 'primeng/api';
import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service';
import {debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
import {BehaviorSubject, combineLatest, forkJoin, Observable, of, Subject} from 'rxjs';
import {BehaviorSubject, combineLatest, Observable, of, Subject} from 'rxjs';
import {ShelfService} from '../../service/shelf.service';
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
import {Shelf} from '../../model/shelf.model';
import {SortService} from '../../service/sort.service';
@@ -17,8 +16,6 @@ import {Book} from '../../model/book.model';
import {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {BookTableComponent} from './book-table/book-table.component';
import {animate, state, style, transition, trigger} from '@angular/animations';
import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dialog/metadata-fetch-options/metadata-fetch-options.component';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import {Button} from 'primeng/button';
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
@@ -27,14 +24,20 @@ import {ProgressSpinner} from 'primeng/progressspinner';
import {Menu} from 'primeng/menu';
import {InputText} from 'primeng/inputtext';
import {FormsModule} from '@angular/forms';
import {BookFilterComponent, isFileSizeInRange, isPageCountInRange, isRatingInRange} from './book-filter/book-filter.component';
import {BookFilterComponent} from './book-filter/book-filter.component';
import {Tooltip} from 'primeng/tooltip';
import {Fluid} from 'primeng/fluid';
import {EntityViewPreferences, UserService} from '../../../settings/user-management/user.service';
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component';
import {OverlayPanelModule} from 'primeng/overlaypanel';
import {Slider} from 'primeng/slider';
import {Popover} from 'primeng/popover';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {SideBarFilter} from './filters/SidebarFilter';
import {HeaderFilter} from './filters/HeaderFilter';
import {CoverScaleManager} from './CoverScaleManager';
import {BookSorter} from './sorting/BookSorter';
import {BookDialogHelperService} from './BookDialogHelperService';
import {Checkbox} from 'primeng/checkbox';
export enum EntityType {
LIBRARY = 'Library',
@@ -67,7 +70,8 @@ const SORT_DIRECTION = {
standalone: true,
templateUrl: './book-browser.component.html',
styleUrls: ['./book-browser.component.scss'],
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, Slider, Popover],
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, Slider, Popover, Checkbox],
providers: [SeriesCollapseFilter],
animations: [
trigger('slideInOut', [
state('void', style({
@@ -110,117 +114,71 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
selectedFilterMode = new BehaviorSubject<'and' | 'or'>('and');
protected resetFilterSubject = new Subject<void>();
entityViewPreferences!: EntityViewPreferences;
protected userService = inject(UserService);
protected coverScaleManager = inject(CoverScaleManager);
private activatedRoute = inject(ActivatedRoute);
private messageService = inject(MessageService);
private libraryService = inject(LibraryService);
private bookService = inject(BookService);
private shelfService = inject(ShelfService);
private dialogService = inject(DialogService);
private dialogHelperService = inject(BookDialogHelperService);
private sortService = inject(SortService);
private router = inject(Router);
private cdr = inject(ChangeDetectorRef);
private changeDetectorRef = inject(ChangeDetectorRef);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
sortOptions: any[] = [
{label: 'Title', icon: '', field: 'title', command: () => this.sortBooks('title')},
{label: 'Title + Series', icon: '', field: 'titleSeries', command: () => this.sortBooks('titleSeries')},
{label: 'Author', icon: '', field: 'author', command: () => this.sortBooks('author')},
{label: 'Last Read', field: 'lastReadTime', command: () => this.sortBooks('lastReadTime')},
{label: 'Added On', field: 'addedOn', command: () => this.sortBooks('addedOn')},
{label: 'File Size', icon: '', field: 'fileSizeKb', command: () => this.sortBooks('fileSizeKb')},
{label: 'Locked', icon: '', field: 'locked', command: () => this.sortBooks('locked')},
{label: 'Publisher', icon: '', field: 'publisher', command: () => this.sortBooks('publisher')},
{label: 'Published Date', icon: '', field: 'publishedDate', command: () => this.sortBooks('publishedDate')},
{label: 'Amazon Rating', icon: '', field: 'amazonRating', command: () => this.sortBooks('amazonRating')},
{label: 'Amazon #', icon: '', field: 'amazonReviewCount', command: () => this.sortBooks('amazonReviewCount')},
{label: 'Goodreads Rating', icon: '', field: 'goodreadsRating', command: () => this.sortBooks('goodreadsRating')},
{label: 'Goodreads #', icon: '', field: 'goodreadsReviewCount', command: () => this.sortBooks('goodreadsReviewCount')},
{label: 'Hardcover Rating', icon: '', field: 'hardcoverRating', command: () => this.sortBooks('hardcoverRating')},
{label: 'Hardcover #', icon: '', field: 'hardcoverReviewCount', command: () => this.sortBooks('hardcoverReviewCount')},
{label: 'Pages', icon: '', field: 'pageCount', command: () => this.sortBooks('pageCount')}
];
protected seriesCollapseFilter = new SeriesCollapseFilter();
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
private headerFilter = new HeaderFilter(this.searchTerm$);
protected bookSorter = new BookSorter((selectedSort) => this.applySortOption(selectedSort));
selectedSort: SortOption | undefined = undefined;
currentViewMode: string | undefined = undefined;
lastAppliedSort: SortOption | null = null;
filterVisibility = true;
entityViewPreferences!: EntityViewPreferences;
baseWidth = 135;
baseHeight = 220;
scaleFactor = 1.0;
private settingFiltersFromUrl = false;
get currentCardSize() {
return {
width: Math.round(this.baseWidth * this.scaleFactor),
height: Math.round(this.baseHeight * this.scaleFactor)
};
return this.coverScaleManager.currentCardSize;
}
get gridColumnMinWidth(): string {
return `${this.currentCardSize.width}px`;
return this.coverScaleManager.gridColumnMinWidth;
}
updateScale(): void {
this.scaleChange$.next(this.scaleFactor);
this.coverScaleManager.setScale(this.coverScaleManager.scaleFactor);
}
private scaleChange$ = new Subject<number>();
ngOnInit(): void {
this.scaleChange$.pipe(debounceTime(1000)).subscribe(scale => {
const user = this.userService.getCurrentUser();
if (!user || !this.entityViewPreferences) return;
this.entityViewPreferences.global = this.entityViewPreferences.global ?? {};
this.entityViewPreferences.global.coverSize = scale;
this.userService.updateUserSetting(user.id, 'entityViewPreferences', this.entityViewPreferences);
this.messageService.add({
severity: 'success',
summary: 'Cover Size Saved',
detail: `Cover size set to ${scale.toFixed(2)}x.`
});
});
this.coverScaleManager.scaleChange$.pipe(debounceTime(1000)).subscribe();
this.bookService.loadBooks();
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
if (currentPath === 'all-books') {
this.entityType = EntityType.ALL_BOOKS;
this.entityType$ = of(EntityType.ALL_BOOKS);
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
const entityType = currentPath === 'all-books' ? EntityType.ALL_BOOKS : EntityType.UNSHELVED;
this.entityType = entityType;
this.entityType$ = of(entityType);
this.entity$ = of(null);
} else if (currentPath === 'unshelved-books') {
this.entityType = EntityType.UNSHELVED;
this.entityType$ = of(EntityType.UNSHELVED);
this.entity$ = of(null);
} else {
const routeEntityInfo$ = this.getEntityInfoFromRoute();
this.entityType$ = routeEntityInfo$.pipe(map(info => info.entityType));
this.entity$ = routeEntityInfo$.pipe(
switchMap(({entityId, entityType}) => this.fetchEntity(entityId, entityType))
);
this.entityType$ = routeEntityInfo$.pipe(
map(({entityType}) => entityType)
);
this.entity$?.subscribe((entity) => {
if (!entity) {
this.entityOptions = [];
return;
}
if (this.isLibrary(entity)) {
this.entity = entity;
this.entityOptions = this.libraryShelfMenuService.initializeLibraryMenuItems(entity);
} else {
this.entity = entity;
this.entityOptions = this.libraryShelfMenuService.initializeShelfMenuItems(entity);
}
this.entity$.subscribe(entity => {
this.entity = entity ?? null;
this.entityOptions = entity
? this.isLibrary(entity)
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
: [];
});
}
@@ -232,379 +190,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
}
private isLibrary(entity: Library | Shelf): entity is Library {
return (entity as Library).paths !== undefined;
}
toggleTableGrid(): void {
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
this.router.navigate([], {
queryParams: {
view: this.currentViewMode,
[QUERY_PARAMS.FROM]: 'toggle'
},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
get viewIcon(): string {
return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table';
}
private getEntityInfoFromRoute(): Observable<{ entityId: number; entityType: EntityType }> {
return this.activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
if (!isNaN(libraryId)) {
this.entityType = EntityType.LIBRARY;
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
this.entityType = EntityType.SHELF;
return {entityId: shelfId, entityType: EntityType.SHELF};
} else {
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
})
);
}
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | null> {
if (entityType == EntityType.LIBRARY) {
return this.fetchLibrary(entityId);
} else if (EntityType.SHELF) {
return this.fetchShelf(entityId);
}
return of(null);
}
private fetchBooksByEntity(entityId: number, entityType: EntityType): Observable<BookState> {
if (entityType == EntityType.LIBRARY) {
return this.fetchBooksByLibrary(entityId);
} else if (entityType == EntityType.SHELF) {
return this.fetchBooksByShelf(entityId);
} else {
return this.fetchAllBooks();
}
}
private fetchBooksByLibrary(libraryId: number): Observable<BookState> {
return this.fetchBooks(book => book.libraryId === libraryId);
}
private fetchBooksByShelf(shelfId: number): Observable<BookState> {
return this.fetchBooks(book => {
return book.shelves?.some(shelf => shelf.id === shelfId) ?? false;
});
}
private fetchAllBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.headerFilter(bookState)),
switchMap(bookState => this.sideBarFilter(bookState))
);
}
private fetchUnshelvedBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
const unshelvedBooks = (bookState.books || []).filter(book =>
!book.shelves || book.shelves.length === 0
);
return {
...bookState,
books: unshelvedBooks
};
}),
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.headerFilter(bookState)),
switchMap(bookState => this.sideBarFilter(bookState))
);
}
private sideBarFilter(bookState: BookState): Observable<BookState> {
return combineLatest([this.selectedFilter, this.selectedFilterMode]).pipe(
map(([activeFilters, mode]) => {
if (!activeFilters) return bookState;
const filteredBooks = (bookState.books || []).filter(book => {
const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => {
if (!Array.isArray(filterValues) || filterValues.length === 0) {
return mode === 'or';
}
switch (filterType) {
case 'author':
return mode === 'and'
? filterValues.every(val => book.metadata?.authors?.includes(val))
: filterValues.some(val => book.metadata?.authors?.includes(val));
case 'category':
return mode === 'and'
? filterValues.every(val => book.metadata?.categories?.includes(val))
: filterValues.some(val => book.metadata?.categories?.includes(val));
case 'publisher':
return mode === 'and'
? filterValues.every(val => book.metadata?.publisher === val)
: filterValues.some(val => book.metadata?.publisher === val);
case 'series':
return mode === 'and'
? filterValues.every(val => book.metadata?.seriesName === val)
: filterValues.some(val => book.metadata?.seriesName === val);
case 'amazonRating':
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range));
case 'goodreadsRating':
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range));
case 'hardcoverRating':
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range));
case 'publishedDate':
return filterValues.includes(new Date(book.metadata?.publishedDate || '').getFullYear());
case 'fileSize':
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range));
case 'shelfStatus':
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
return filterValues.includes(shelved);
case 'pageCount':
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range));
case 'language':
return filterValues.includes(book.metadata?.language);
default:
return false;
}
});
return mode === 'and' ? matches.every(m => m) : matches.some(m => m);
});
return {...bookState, books: filteredBooks};
})
);
}
private headerFilter(bookState: BookState): Observable<BookState> {
return this.searchTerm$.pipe(
map(term => {
if (term && term.trim() !== '') {
const filteredBooks = bookState.books?.filter(book => {
const matchesTitle = book.metadata?.title?.toLowerCase().includes(term.toLowerCase());
const matchesSeries = book.metadata?.seriesName?.toLowerCase().includes(term.toLowerCase());
const matchesAuthor = book.metadata?.authors.some(author =>
author.toLowerCase().includes(term.toLowerCase())
);
return matchesTitle || matchesSeries || matchesAuthor;
}) || null;
return {...bookState, books: filteredBooks};
}
return bookState;
})
);
}
private fetchBooks(bookFilter: (book: Book) => boolean): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.loaded && !bookState.error) {
const filteredBooks = bookState.books?.filter(bookFilter) || [];
const sortedBooks = this.sortService.applySort(filteredBooks, this.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}),
switchMap(bookState => this.headerFilter(bookState)),
switchMap(bookState => this.sideBarFilter(bookState))
);
}
private processBookState(bookState: BookState): BookState {
if (bookState.loaded && !bookState.error) {
const sortedBooks = this.sortService.applySort(bookState.books || [], this.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
);
}
private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
handleBookSelect(bookId: number, selected: boolean): void {
if (selected) {
this.selectedBooks.add(bookId);
} else {
this.selectedBooks.delete(bookId);
}
this.isDrawerVisible = this.selectedBooks.size > 0;
}
onSelectedBooksChange(selectedBookIds: Set<number>): void {
this.selectedBooks = new Set(selectedBookIds);
this.isDrawerVisible = this.selectedBooks.size > 0;
}
deselectAllBooks(): void {
this.selectedBooks.clear();
this.isDrawerVisible = false;
if (this.bookTableComponent) {
this.bookTableComponent.clearSelectedBooks();
}
}
unshelfBooks() {
if (this.entity) {
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id])).subscribe(
{
next: () => {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Books shelves updated'});
this.selectedBooks = new Set<number>();
},
error: () => {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update books shelves'});
}
}
);
}
}
applySortOption(sortOption: SortOption): void {
if (this.entityType === EntityType.ALL_BOOKS) {
this.bookState$ = this.fetchAllBooks();
} else if (this.entityType === EntityType.UNSHELVED) {
this.bookState$ = this.fetchUnshelvedBooks();
} else {
const routeParam$ = this.getEntityInfoFromRoute();
this.bookState$ = routeParam$.pipe(
switchMap(({entityId, entityType}) => this.fetchBooksByEntity(entityId, entityType))
);
}
}
onSearchTermChange(term: string): void {
this.searchTerm$.next(term);
}
clearSearch(): void {
this.bookTitle = '';
this.onSearchTermChange('');
this.resetFilters();
}
resetFilters() {
this.resetFilterSubject.next();
}
openShelfAssigner() {
this.dynamicDialogRef = this.dialogService.open(ShelfAssignerComponent, {
header: `Update Books' Shelves`,
modal: true,
closable: true,
contentStyle: {overflow: 'auto'},
baseZIndex: 10,
style: {
position: 'absolute',
top: '15%',
},
data: {
isMultiBooks: true,
bookIds: this.selectedBooks
},
});
}
updateMetadata() {
this.dialogService.open(MetadataFetchOptionsComponent, {
header: 'Metadata Refresh Options',
modal: true,
closable: true,
data: {
bookIds: Array.from(this.selectedBooks),
metadataRefreshType: MetadataRefreshType.BOOKS
}
})
}
toggleFilterSidebar() {
this.bookFilterComponent.showFilters = !this.bookFilterComponent.showFilters;
this.router.navigate([], {
queryParams: {
[QUERY_PARAMS.SIDEBAR]: this.bookFilterComponent.showFilters.toString()
},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
get isFilterActive(): boolean {
return this.selectedFilter.value !== null;
}
clearFilter() {
if (this.selectedFilter.value !== null) {
this.selectedFilter.next(null);
}
this.clearSearch();
}
sortBooks(field: string): void {
const existingSort = this.sortOptions.find(opt => opt.field === field);
if (!existingSort) return;
if (this.selectedSort?.field === field) {
this.selectedSort = {
...this.selectedSort,
direction: this.selectedSort.direction === SortDirection.ASCENDING
? SortDirection.DESCENDING
: SortDirection.ASCENDING
};
} else {
this.selectedSort = {
label: existingSort.label,
field: existingSort.field,
direction: SortDirection.ASCENDING
};
}
this.updateSortOptions();
this.applySortOption(this.selectedSort);
/*this.router.navigate([], {
queryParams: {
sort: this.selectedSort.field,
direction: this.selectedSort.direction === SortDirection.ASCENDING
? SORT_DIRECTION.ASCENDING
: SORT_DIRECTION.DESCENDING
},
queryParamsHandling: 'merge',
replaceUrl: true
});*/
}
updateSortOptions() {
const directionIcon = this.selectedSort!.direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
this.sortOptions = this.sortOptions.map((option) => ({
...option,
icon: option.field === this.selectedSort!.field ? directionIcon : '',
}));
}
private settingFiltersFromUrl = false;
ngAfterViewInit() {
combineLatest({
paramMap: this.activatedRoute.queryParamMap,
@@ -657,7 +242,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.entityViewPreferences = user.userSettings?.entityViewPreferences;
const globalPrefs = this.entityViewPreferences?.global;
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined;
this.scaleFactor = user.userSettings.entityViewPreferences?.global?.coverSize ?? 1.0;
this.coverScaleManager.scaleFactor = user.userSettings.entityViewPreferences?.global?.coverSize ?? 1.0;
const override = this.entityViewPreferences?.overrides?.find(o =>
o.entityType?.toUpperCase() === currentEntityTypeStr &&
@@ -675,9 +260,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
? SortDirection.DESCENDING
: SortDirection.ASCENDING;
const matchedSort = this.sortOptions.find(opt => opt.field === userSortKey) || this.sortOptions.find(opt => opt.field === sortParam);
const matchedSort = this.bookSorter.sortOptions.find(opt => opt.field === userSortKey) || this.bookSorter.sortOptions.find(opt => opt.field === sortParam);
this.selectedSort = matchedSort ? {
this.bookSorter.selectedSort = matchedSort ? {
label: matchedSort.label,
field: matchedSort.field,
direction: userSortDir ?? (
@@ -700,17 +285,17 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.bookFilterComponent.showFilters = sidebarParam === 'true' || (sidebarParam === null && this.filterVisibility);
this.updateSortOptions();
this.bookSorter.updateSortOptions();
if (this.lastAppliedSort?.field !== this.selectedSort.field || this.lastAppliedSort?.direction !== this.selectedSort.direction) {
this.lastAppliedSort = {...this.selectedSort};
this.applySortOption(this.selectedSort);
if (this.lastAppliedSort?.field !== this.bookSorter.selectedSort.field || this.lastAppliedSort?.direction !== this.bookSorter.selectedSort.direction) {
this.lastAppliedSort = {...this.bookSorter.selectedSort};
this.applySortOption(this.bookSorter.selectedSort);
}
const queryParams: any = {
[QUERY_PARAMS.VIEW]: this.currentViewMode,
[QUERY_PARAMS.SORT]: this.selectedSort.field,
[QUERY_PARAMS.DIRECTION]: this.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING,
[QUERY_PARAMS.SORT]: this.bookSorter.selectedSort.field,
[QUERY_PARAMS.DIRECTION]: this.bookSorter.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING,
[QUERY_PARAMS.SIDEBAR]: this.bookFilterComponent.showFilters.toString(),
[QUERY_PARAMS.FILTER]: Object.entries(parsedFilters).map(([k, v]) => `${k}:${v.join('|')}`).join(',')
};
@@ -725,7 +310,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
}
this.cdr.detectChanges();
this.changeDetectorRef.detectChanges();
});
this.bookFilterComponent.filterSelected.subscribe((filters: Record<string, any> | null) => {
@@ -747,24 +332,246 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
}
capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
private isLibrary(entity: Library | Shelf): entity is Library {
return (entity as Library).paths !== undefined;
}
get viewIcon(): string {
return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table';
}
private getEntityInfoFromRoute(): Observable<{ entityId: number; entityType: EntityType }> {
return this.activatedRoute.paramMap.pipe(
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
if (!isNaN(libraryId)) {
this.entityType = EntityType.LIBRARY;
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
this.entityType = EntityType.SHELF;
return {entityId: shelfId, entityType: EntityType.SHELF};
} else {
this.entityType = EntityType.ALL_BOOKS;
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
}
})
);
}
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | null> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchLibrary(entityId);
case EntityType.SHELF:
return this.fetchShelf(entityId);
default:
return of(null);
}
}
private fetchBooksByEntity(entityId: number, entityType: EntityType): Observable<BookState> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchBooks(book => book.libraryId === entityId);
case EntityType.SHELF:
return this.fetchBooks(book =>
book.shelves?.some(shelf => shelf.id === entityId) ?? false
);
case EntityType.ALL_BOOKS:
default:
return this.fetchAllBooks();
}
}
private fetchAllBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchUnshelvedBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => ({
...bookState,
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
})),
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooks(bookFilter: (book: Book) => boolean): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.loaded && !bookState.error) {
const filteredBooks = bookState.books?.filter(bookFilter) || [];
const sortedBooks = this.sortService.applySort(filteredBooks, this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private applyBookFilters(bookState: BookState): Observable<BookState> {
return this.headerFilter.filter(bookState).pipe(
switchMap(filtered => this.sideBarFilter.filter(filtered)),
switchMap(filtered => this.seriesCollapseFilter.filter(filtered))
);
}
private processBookState(bookState: BookState): BookState {
if (bookState.loaded && !bookState.error) {
const sortedBooks = this.sortService.applySort(bookState.books || [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}
return bookState;
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
map(libraryState => {
if (libraryState.libraries) {
return libraryState.libraries.find(lib => lib.id === libraryId) || null;
}
return null;
})
);
}
private fetchShelf(shelfId: number): Observable<Shelf | null> {
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
handleBookSelect(bookId: number, selected: boolean): void {
if (selected) {
this.selectedBooks.add(bookId);
} else {
this.selectedBooks.delete(bookId);
}
this.isDrawerVisible = this.selectedBooks.size > 0;
}
onSelectedBooksChange(selectedBookIds: Set<number>): void {
this.selectedBooks = new Set(selectedBookIds);
this.isDrawerVisible = this.selectedBooks.size > 0;
}
deselectAllBooks(): void {
this.selectedBooks.clear();
this.isDrawerVisible = false;
if (this.bookTableComponent) {
this.bookTableComponent.clearSelectedBooks();
}
}
onSeriesCollapseCheckboxChange(value: boolean): void {
this.seriesCollapseFilter.setCollapsed(value);
}
applySortOption(sortOption: SortOption): void {
if (this.entityType === EntityType.ALL_BOOKS) {
this.bookState$ = this.fetchAllBooks();
} else if (this.entityType === EntityType.UNSHELVED) {
this.bookState$ = this.fetchUnshelvedBooks();
} else {
const routeParam$ = this.getEntityInfoFromRoute();
this.bookState$ = routeParam$.pipe(
switchMap(({entityId, entityType}) => this.fetchBooksByEntity(entityId, entityType))
);
}
}
onSearchTermChange(term: string): void {
this.searchTerm$.next(term);
}
clearSearch(): void {
this.bookTitle = '';
this.onSearchTermChange('');
this.resetFilters();
}
resetFilters() {
this.resetFilterSubject.next();
}
get hasSidebarFilters(): boolean {
return this.selectedFilter && Object.keys(this.selectedFilter.getValue() || {}).length > 0;
}
lockUnlockMetadata() {
const count = this.selectedBooks.size;
this.dynamicDialogRef = this.dialogService.open(LockUnlockMetadataDialogComponent, {
header: `Lock or Unlock Metadata for ${count} Selected Book${count > 1 ? 's' : ''}`,
modal: true,
closable: true,
data: {
bookIds: Array.from(this.selectedBooks)
get isFilterActive(): boolean {
return this.selectedFilter.value !== null;
}
clearFilter() {
if (this.selectedFilter.value !== null) {
this.selectedFilter.next(null);
}
this.clearSearch();
}
private capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
toggleFilterSidebar() {
this.bookFilterComponent.showFilters = !this.bookFilterComponent.showFilters;
this.router.navigate([], {
queryParams: {
[QUERY_PARAMS.SIDEBAR]: this.bookFilterComponent.showFilters.toString()
},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
toggleTableGrid(): void {
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
this.router.navigate([], {
queryParams: {
view: this.currentViewMode,
[QUERY_PARAMS.FROM]: 'toggle'
},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
unshelfBooks() {
if (!this.entity) return;
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id])).subscribe({
next: () => {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Books shelves updated'});
this.selectedBooks.clear();
},
error: () => {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update books shelves'});
}
});
}
openShelfAssigner(): void {
this.dynamicDialogRef = this.dialogHelperService.openShelfAssigner(this.selectedBooks);
}
lockUnlockMetadata(): void {
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks);
}
updateMetadata(): void {
this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks);
}
}
@@ -18,6 +18,12 @@
</div>
}
@if (book.seriesCount != null && book.seriesCount! > 1) {
<div class="series-count-overlay">
{{ book.seriesCount }}
</div>
}
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)"></p-button>
<p-button [hidden]="readButtonHidden" [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
@@ -148,6 +148,23 @@
z-index: 3;
}
.series-count-overlay {
position: absolute;
top: 4px;
right: 4px;
background-color: var(--primary-color);
color: var(--primary-text-color-dark);
font-size: 0.75rem;
padding: 1px 6px;
border-radius: 3px;
z-index: 3;
white-space: nowrap;
user-select: none;
font-weight: 600;
text-align: center;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.15);
}
::ng-deep .progress-incomplete .p-progressbar-value {
background-color: #3b82f6;
}
@@ -35,6 +35,7 @@ export class BookCardComponent implements OnInit {
@Input() isSelected: boolean = false;
@Input() bottomBarHidden: boolean = false;
@Input() readButtonHidden: boolean = false;
@Input() isSeriesCollapsed: boolean = false;
items: MenuItem[] | undefined;
isHovered: boolean = false;
@@ -44,27 +44,6 @@ export const pageCountRanges = [
{id: '1000plus', label: '1000+ pages', min: 1000, max: Infinity}
];
export function isRatingInRange(rating: number | undefined | null, rangeId: string): boolean {
if (rating == null) return false;
const range = ratingRanges.find(r => r.id === rangeId);
if (!range) return false;
return rating >= range.min && rating < range.max;
}
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string): boolean {
if (fileSizeKb == null) return false;
const range = fileSizeRanges.find(r => r.id === rangeId);
if (!range) return false;
return fileSizeKb >= range.min && fileSizeKb < range.max;
}
export function isPageCountInRange(pageCount: number | undefined, rangeId: string): boolean {
if (pageCount == null) return false;
const range = pageCountRanges.find(r => r.id === rangeId);
if (!range) return false;
return pageCount >= range.min && pageCount < range.max;
}
const getLanguageFilter = (book: Book) => {
const lang = book.metadata?.language;
return lang ? [{id: lang, name: lang}] : [];
@@ -0,0 +1,6 @@
import {BookState} from '../../../model/state/book-state.model';
import {Observable} from 'rxjs';
export interface BookFilter {
filter(bookState: BookState): Observable<BookState>;
}
@@ -0,0 +1,30 @@
import {BookFilter} from './BookFilter';
import {BookState} from '../../../model/state/book-state.model';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
export class HeaderFilter implements BookFilter {
constructor(private searchTerm$: Observable<any>) {
}
filter(bookState: BookState): Observable<BookState> {
return this.searchTerm$.pipe(
map(term => {
if (term && term.trim() !== '') {
const filteredBooks = bookState.books?.filter(book => {
const matchesTitle = book.metadata?.title?.toLowerCase().includes(term.toLowerCase());
const matchesSeries = book.metadata?.seriesName?.toLowerCase().includes(term.toLowerCase());
const matchesAuthor = book.metadata?.authors.some(author =>
author.toLowerCase().includes(term.toLowerCase())
);
return matchesTitle || matchesSeries || matchesAuthor;
}) || null;
return {...bookState, books: filteredBooks};
}
return bookState;
})
);
}
}
@@ -0,0 +1,90 @@
import { BookFilter } from './BookFilter';
import { Observable, BehaviorSubject } from 'rxjs';
import { BookState } from '../../../model/state/book-state.model';
import { map, debounceTime, filter, take } from 'rxjs/operators';
import { Book } from '../../../model/book.model';
import { inject, Injectable } from '@angular/core';
import { MessageService } from 'primeng/api';
import { UserService } from '../../../../settings/user-management/user.service';
@Injectable()
export class SeriesCollapseFilter implements BookFilter {
private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService);
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
private hasUserToggled = false;
constructor() {
this.userService.userState$
.pipe(filter(user => !!user), take(1))
.subscribe(user => {
const prefs = user.userSettings?.entityViewPreferences;
const initialCollapsed = prefs?.global?.seriesCollapsed ?? false;
this.seriesCollapseSubject.next(initialCollapsed);
});
this.seriesCollapse$
.pipe(debounceTime(500))
.subscribe(isCollapsed => {
if (this.hasUserToggled) {
this.persistCollapsePreference(isCollapsed);
}
});
}
get isSeriesCollapsed(): boolean {
return this.seriesCollapseSubject.value;
}
setCollapsed(value: boolean): void {
this.hasUserToggled = true;
this.seriesCollapseSubject.next(value);
}
filter(bookState: BookState): Observable<BookState> {
return this.seriesCollapse$.pipe(
map(isCollapsed => {
if (!isCollapsed || !bookState.books) return bookState;
const seenSeries = new Set<string>();
const collapsedBooks: Book[] = [];
for (const book of bookState.books) {
const name = book.metadata?.seriesName?.trim();
if (name && !seenSeries.has(name)) {
const count = bookState.books.filter(b => b.metadata?.seriesName?.trim() === name).length;
collapsedBooks.push({
...book,
seriesCount: count,
});
seenSeries.add(name);
} else if (!name) {
collapsedBooks.push(book);
}
}
return { ...bookState, books: collapsedBooks };
})
);
}
private persistCollapsePreference(isCollapsed: boolean): void {
const user = this.userService.getCurrentUser();
const prefs = user?.userSettings?.entityViewPreferences;
if (!user || !prefs) return;
prefs.global = prefs.global ?? {};
prefs.global.seriesCollapsed = isCollapsed;
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
this.messageService.add({
severity: 'success',
summary: 'Preference Saved',
detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}.`
});
}
}
@@ -0,0 +1,86 @@
import {Observable, combineLatest, of} from 'rxjs';
import {map} from 'rxjs/operators';
import {BookFilter} from './BookFilter';
import {BookState} from '../../../model/state/book-state.model';
import {fileSizeRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.component';
export function isRatingInRange(rating: number | undefined | null, rangeId: string): boolean {
if (rating == null) return false;
const range = ratingRanges.find(r => r.id === rangeId);
if (!range) return false;
return rating >= range.min && rating < range.max;
}
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string): boolean {
if (fileSizeKb == null) return false;
const range = fileSizeRanges.find(r => r.id === rangeId);
if (!range) return false;
return fileSizeKb >= range.min && fileSizeKb < range.max;
}
export function isPageCountInRange(pageCount: number | undefined, rangeId: string): boolean {
if (pageCount == null) return false;
const range = pageCountRanges.find(r => r.id === rangeId);
if (!range) return false;
return pageCount >= range.min && pageCount < range.max;
}
export class SideBarFilter implements BookFilter {
constructor(private selectedFilter$: Observable<any>, private selectedFilterMode$: Observable<'and' | 'or'>) {
}
filter(bookState: BookState): Observable<BookState> {
return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe(
map(([activeFilters, mode]) => {
if (!activeFilters) return bookState;
const filteredBooks = (bookState.books || []).filter(book => {
const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => {
if (!Array.isArray(filterValues) || filterValues.length === 0) {
return mode === 'or';
}
switch (filterType) {
case 'author':
return mode === 'and'
? filterValues.every(val => book.metadata?.authors?.includes(val))
: filterValues.some(val => book.metadata?.authors?.includes(val));
case 'category':
return mode === 'and'
? filterValues.every(val => book.metadata?.categories?.includes(val))
: filterValues.some(val => book.metadata?.categories?.includes(val));
case 'publisher':
return mode === 'and'
? filterValues.every(val => book.metadata?.publisher === val)
: filterValues.some(val => book.metadata?.publisher === val);
case 'series':
return mode === 'and'
? filterValues.every(val => book.metadata?.seriesName === val)
: filterValues.some(val => book.metadata?.seriesName === val);
case 'amazonRating':
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range));
case 'goodreadsRating':
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range));
case 'hardcoverRating':
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range));
case 'publishedDate':
return filterValues.includes(new Date(book.metadata?.publishedDate || '').getFullYear());
case 'fileSize':
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range));
case 'shelfStatus':
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
return filterValues.includes(shelved);
case 'pageCount':
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range));
case 'language':
return filterValues.includes(book.metadata?.language);
default:
return false;
}
});
return mode === 'and' ? matches.every(m => m) : matches.some(m => m);
});
return {...bookState, books: filteredBooks};
})
);
}
}
@@ -0,0 +1,69 @@
import {SortDirection, SortOption} from '../../../model/sort.model';
export class BookSorter {
selectedSort: SortOption | undefined = undefined;
sortOptions: SortOption[] = [
{ label: 'Title', field: 'title', direction: SortDirection.ASCENDING },
{ label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING },
{ label: 'Author', field: 'author', direction: SortDirection.ASCENDING },
{ label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING },
{ label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING },
{ label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING },
{ label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING },
{ label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING },
{ label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING },
{ label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING },
{ label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING },
{ label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING },
{ label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING },
{ label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING },
{ label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING },
{ label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING },
];
constructor(private applySortOption: (sort: SortOption) => void) {}
sortBooks(field: string): void {
const existingSort = this.sortOptions.find(opt => opt.field === field);
if (!existingSort) return;
if (this.selectedSort?.field === field) {
this.selectedSort = {
...this.selectedSort,
direction: this.selectedSort.direction === SortDirection.ASCENDING
? SortDirection.DESCENDING
: SortDirection.ASCENDING
};
} else {
this.selectedSort = {
label: existingSort.label,
field: existingSort.field,
direction: SortDirection.ASCENDING
};
}
this.updateSortOptions();
this.applySortOption(this.selectedSort);
/*this.router.navigate([], {
queryParams: {
sort: this.selectedSort.field,
direction: this.selectedSort.direction === SortDirection.ASCENDING
? SORT_DIRECTION.ASCENDING
: SORT_DIRECTION.DESCENDING
},
queryParamsHandling: 'merge',
replaceUrl: true
});*/
}
updateSortOptions() {
const directionIcon = this.selectedSort!.direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
this.sortOptions = this.sortOptions.map((option) => ({
...option,
icon: option.field === this.selectedSort!.field ? directionIcon : '',
}));
}
}
@@ -16,6 +16,7 @@ export interface Book {
cbxProgress?: CbxProgress;
filePath?: string;
fileSizeKb?: number;
seriesCount?: number | null;
}
export interface EpubProgress {
@@ -16,7 +16,8 @@ export interface EntityViewPreference {
sortKey: string;
sortDir: 'ASC' | 'DESC';
view: 'GRID' | 'TABLE';
coverSize: number
coverSize: number;
seriesCollapsed: boolean;
}
export interface EntityViewPreferenceOverride {
@@ -175,7 +175,8 @@ export class ViewPreferencesComponent implements OnInit {
sortKey: o.sort,
sortDir: o.sortDir,
view: o.view,
coverSize: existing?.coverSize ?? 1.0
coverSize: existing?.coverSize ?? 1.0,
seriesCollapsed: existing?.seriesCollapsed ?? false
}
};
});
@@ -1,12 +1,11 @@
:root[class="p-dark"] {
--primary-text-color: var(--p-primary-400);
--primary-text-color-dark: var(--p-primary-900);
--primary-color: var(--p-primary-color);
--primary-contrast-color: var(--p-primary-contrast-color);
--primary-hover-color: var(--p-primary-hover-color);
--text-color: var(--p-surface-0);
--text-secondary-color: var(--p-surface-400);
--glow-image: url(https://www.primefaces.org/cdn/primevue/images/layout/pattern.png), radial-gradient(50% 50% at center -25px, var(--p-primary-color) 0%, #000000 100%);
--glow-blend: hard-light, color-dodge;
--topbar-sticky-background: rgba(0, 0, 0, .3);
--mobile-menu-background: rgba(0, 0, 0, .3);
--card-border: 1px solid transparent;