diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java index c85b256ec..948e0325b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookLoreUser.java @@ -60,6 +60,7 @@ public class BookLoreUser { private String sortDir; private String view; private Float coverSize; + private Boolean seriesCollapsed; } @Data @@ -80,6 +81,7 @@ public class BookLoreUser { private String sortKey; private String sortDir; private String view; + private Boolean seriesCollapse; } @Data diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultUserSettingsProvider.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultUserSettingsProvider.java index 7727e7465..b1fbee28b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultUserSettingsProvider.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/user/DefaultUserSettingsProvider.java @@ -96,6 +96,7 @@ public class DefaultUserSettingsProvider { .sortDir("ASC") .view("GRID") .coverSize(1.0F) + .seriesCollapsed(false) .build()) .overrides(null) .build(); diff --git a/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts b/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts new file mode 100644 index 000000000..576301e7b --- /dev/null +++ b/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts @@ -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): 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): 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): DynamicDialogRef { + return this.dialogService.open(MetadataFetchOptionsComponent, { + header: 'Metadata Refresh Options', + modal: true, + closable: true, + data: { + bookIds: Array.from(bookIds), + metadataRefreshType: MetadataRefreshType.BOOKS, + }, + }); + } +} diff --git a/booklore-ui/src/app/book/components/book-browser/CoverScaleManager.ts b/booklore-ui/src/app/book/components/book-browser/CoverScaleManager.ts new file mode 100644 index 000000000..451ec772e --- /dev/null +++ b/booklore-ui/src/app/book/components/book-browser/CoverScaleManager.ts @@ -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(); + 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.` + }); + } +} diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.html b/booklore-ui/src/app/book/components/book-browser/book-browser.component.html index c6e84cec3..7d079e05c 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.html +++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.html @@ -32,7 +32,6 @@
-
@if (isFilterActive) { @@ -43,7 +42,28 @@ } - +
+ + + + +
+
+ + + +
+
+
+
-
- {{ scaleFactor.toFixed(2) }}x + {{ coverScaleManager.scaleFactor.toFixed(2) }}x
@@ -78,9 +97,9 @@ tooltipPosition="top"> - + -
+
{{ item.label }} @if (item.icon) { @@ -108,7 +127,8 @@ placeholder="Title, Series or Author..." [(ngModel)]="bookTitle" (ngModelChange)="onSearchTermChange($event)" - class="search-input"/> + class="search-input" + /> @if (bookTitle) { + tooltipPosition="top" + />
@@ -159,8 +180,11 @@ @if (bookState?.books; as books) {
@if (currentViewMode === 'table' && books.length > 0) { - + } @if (currentViewMode === 'grid') { @@ -170,12 +194,13 @@ [ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}"> @for (book of scroll.viewPortItems; track book) {
@@ -249,5 +274,4 @@
-
diff --git a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts index ede120a83..4c0751850 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-browser.component.ts @@ -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(); + 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(); - 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 { - 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 { - 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 { - return this.fetchBooks(book => book.libraryId === libraryId); - } - - private fetchBooksByShelf(shelfId: number): Observable { - return this.fetchBooks(book => { - return book.shelves?.some(shelf => shelf.id === shelfId) ?? false; - }); - } - - private fetchAllBooks(): Observable { - return this.bookService.bookState$.pipe( - map(bookState => this.processBookState(bookState)), - switchMap(bookState => this.headerFilter(bookState)), - switchMap(bookState => this.sideBarFilter(bookState)) - ); - } - - private fetchUnshelvedBooks(): Observable { - 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 { - 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 { - 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 { - 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 { - 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 { - 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): 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(); - }, - 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 | 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 { + 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 { + 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 { + return this.bookService.bookState$.pipe( + map(bookState => this.processBookState(bookState)), + switchMap(bookState => this.applyBookFilters(bookState)) + ); + } + + private fetchUnshelvedBooks(): Observable { + 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 { + 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 { + 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 { + 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 { + 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): 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); + } } diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html index 4135a6d55..ff2ebcdb0 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html @@ -18,6 +18,12 @@
} + @if (book.seriesCount != null && book.seriesCount! > 1) { +
+ {{ book.seriesCount }} +
+ } + diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss index c905c2b1d..253f81089 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss @@ -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; } diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts index 4dccb0181..82e5ea7f3 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts @@ -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; diff --git a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts index b33ed2f69..9c718a543 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-filter/book-filter.component.ts @@ -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}] : []; diff --git a/booklore-ui/src/app/book/components/book-browser/filters/BookFilter.ts b/booklore-ui/src/app/book/components/book-browser/filters/BookFilter.ts new file mode 100644 index 000000000..978384997 --- /dev/null +++ b/booklore-ui/src/app/book/components/book-browser/filters/BookFilter.ts @@ -0,0 +1,6 @@ +import {BookState} from '../../../model/state/book-state.model'; +import {Observable} from 'rxjs'; + +export interface BookFilter { + filter(bookState: BookState): Observable; +} diff --git a/booklore-ui/src/app/book/components/book-browser/filters/HeaderFilter.ts b/booklore-ui/src/app/book/components/book-browser/filters/HeaderFilter.ts new file mode 100644 index 000000000..1733e6b96 --- /dev/null +++ b/booklore-ui/src/app/book/components/book-browser/filters/HeaderFilter.ts @@ -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) { + } + + filter(bookState: BookState): Observable { + 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; + }) + ); + } + +} diff --git a/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts b/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts new file mode 100644 index 000000000..d354304fe --- /dev/null +++ b/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts @@ -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(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 { + return this.seriesCollapse$.pipe( + map(isCollapsed => { + if (!isCollapsed || !bookState.books) return bookState; + + const seenSeries = new Set(); + 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'}.` + }); + } +} diff --git a/booklore-ui/src/app/book/components/book-browser/filters/SidebarFilter.ts b/booklore-ui/src/app/book/components/book-browser/filters/SidebarFilter.ts new file mode 100644 index 000000000..5515c89e9 --- /dev/null +++ b/booklore-ui/src/app/book/components/book-browser/filters/SidebarFilter.ts @@ -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, private selectedFilterMode$: Observable<'and' | 'or'>) { + } + + filter(bookState: BookState): Observable { + 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}; + }) + ); + } +} diff --git a/booklore-ui/src/app/book/components/book-browser/sorting/BookSorter.ts b/booklore-ui/src/app/book/components/book-browser/sorting/BookSorter.ts new file mode 100644 index 000000000..ec7b432c6 --- /dev/null +++ b/booklore-ui/src/app/book/components/book-browser/sorting/BookSorter.ts @@ -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 : '', + })); + } +} diff --git a/booklore-ui/src/app/book/model/book.model.ts b/booklore-ui/src/app/book/model/book.model.ts index 3033199c1..b13221aa8 100644 --- a/booklore-ui/src/app/book/model/book.model.ts +++ b/booklore-ui/src/app/book/model/book.model.ts @@ -16,6 +16,7 @@ export interface Book { cbxProgress?: CbxProgress; filePath?: string; fileSizeKb?: number; + seriesCount?: number | null; } export interface EpubProgress { diff --git a/booklore-ui/src/app/settings/user-management/user.service.ts b/booklore-ui/src/app/settings/user-management/user.service.ts index b3c2fd0db..4c3c7acd9 100644 --- a/booklore-ui/src/app/settings/user-management/user.service.ts +++ b/booklore-ui/src/app/settings/user-management/user.service.ts @@ -16,7 +16,8 @@ export interface EntityViewPreference { sortKey: string; sortDir: 'ASC' | 'DESC'; view: 'GRID' | 'TABLE'; - coverSize: number + coverSize: number; + seriesCollapsed: boolean; } export interface EntityViewPreferenceOverride { diff --git a/booklore-ui/src/app/settings/view-preferences-parent/view-preferences/view-preferences.component.ts b/booklore-ui/src/app/settings/view-preferences-parent/view-preferences/view-preferences.component.ts index 90779657f..22aa10983 100644 --- a/booklore-ui/src/app/settings/view-preferences-parent/view-preferences/view-preferences.component.ts +++ b/booklore-ui/src/app/settings/view-preferences-parent/view-preferences/view-preferences.component.ts @@ -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 } }; }); diff --git a/booklore-ui/src/assets/layout/styles/layout/variables/main/_dark.scss b/booklore-ui/src/assets/layout/styles/layout/variables/main/_dark.scss index 23f71fccb..a303eb599 100644 --- a/booklore-ui/src/assets/layout/styles/layout/variables/main/_dark.scss +++ b/booklore-ui/src/assets/layout/styles/layout/variables/main/_dark.scss @@ -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;