WIP: Add filter sidebar

This commit is contained in:
aditya.chandel
2025-01-20 16:17:34 -07:00
parent 96bbdd4541
commit c51be158a9
6 changed files with 299 additions and 166 deletions
@@ -7,9 +7,9 @@ import com.adityachandel.booklore.repository.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.io.File;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@@ -18,6 +18,7 @@ import java.util.Set;
public class BookCreatorService {
private AuthorRepository authorRepository;
private CategoryRepository categoryRepository;
private BookRepository bookRepository;
private BookMetadataRepository bookMetadataRepository;
private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
@@ -52,6 +53,25 @@ public class BookCreatorService {
return bookEntity;
}
public void addCategoriesToBook(List<String> categories, BookEntity bookEntity) {
for (String category : categories) {
Optional<CategoryEntity> catOpt = categoryRepository.findByName(category);
CategoryEntity categoryEntity;
if (catOpt.isPresent()) {
categoryEntity = catOpt.get();
} else {
categoryEntity = CategoryEntity.builder()
.name(category)
.build();
categoryEntity = categoryRepository.save(categoryEntity);
}
if (bookEntity.getMetadata().getCategories() == null) {
bookEntity.getMetadata().setCategories(new ArrayList<>());
}
bookEntity.getMetadata().getCategories().add(categoryEntity);
}
}
public void addAuthorsToBook(Set<String> authors, BookEntity bookEntity) {
for (String authorStr : authors) {
Optional<AuthorEntity> authorOptional = authorRepository.findByName(authorStr);
@@ -138,6 +138,7 @@ public class EpubProcessor implements FileProcessor {
}
bookCreatorService.addAuthorsToBook(getAuthors(book), bookEntity);
bookCreatorService.addCategoriesToBook(epubMetadata.getSubjects(), bookEntity);
}
}
@@ -1,92 +1,139 @@
<div class="book-browser-header">
<div class="left-items">
<ng-container *ngIf="entityType$ | async as entityType">
<p *ngIf="entityType !== EntityType.ALL_BOOKS" class="entity-name text-2xl">
{{ entityType }}: {{ (entity$ | async)?.name }}
</p>
<p *ngIf="entityType === EntityType.ALL_BOOKS" class="entity-name text-2xl">
All Books
</p>
<div *ngIf="entityType !== EntityType.ALL_BOOKS">
<p-button icon="pi pi-ellipsis-v" [rounded]="true" [text]="true" severity="info" (click)="entitymenu.toggle($event)"></p-button>
<p-menu #entitymenu [model]="entityOptions" [popup]="true" appendTo="body"></p-menu>
</div>
</ng-container>
</div>
<div class="header-right-items">
<input type="text" pInputText placeholder="Search title or author..." [(ngModel)]="bookTitle" (ngModelChange)="onBookTitleChange($event)"/>
<p-select [options]="sortOptions" optionLabel="label" placeholder="Select Sorting" [(ngModel)]="selectedSort" (onChange)="updateSortOption($event.value)"></p-select>
<div *ngFor="let option of stateOptions" class="field-checkbox">
<p-radioButton [inputId]="option.key" [value]="option.value" [(ngModel)]="value" (onClick)="viewChanged()"></p-radioButton>
<label [for]="option.key" class="ml-2">{{ option.label }}</label>
</div>
</div>
</div>
<div *ngIf="bookState$ | async as bookState">
<div *ngIf="!bookState?.loaded && !bookState?.error">
<p-progressSpinner></p-progressSpinner>
</div>
<div class="virtual-scroller-container">
<div class="no-books-container" *ngIf="bookState?.error">
<p class="no-books-text">
{{ entityType === EntityType.LIBRARY ? "Failed to load library's books!" : "Failed to load shelf's books!" }}
</p>
</div>
<div class="no-books-container" *ngIf="!bookState?.error && bookState?.loaded && bookState?.books?.length === 0">
<p class="no-books-text">
{{ entityType === EntityType.LIBRARY ? "This library has no books!" : "This shelf has no books!" }}
</p>
</div>
<div class="book-card-container" *ngIf="bookState?.books as books">
<app-book-table *ngIf="value === 'table'&& books.length > 0" [books]="books" (selectedBooksChange)="onSelectedBooksChange($event)" [sortOption]="selectedSort"></app-book-table>
<virtual-scroller *ngIf="value === 'grid'" class="virtual-scroller" #scroll [items]="books">
<div class="grid grid-cols-12 gap-4" #container>
<div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems">
<app-book-card
[book]="book"
[isCheckboxEnabled]="true"
[onBookSelect]="handleBookSelect.bind(this)"
[isSelected]="selectedBooks.has(book.id)">
</app-book-card>
</div>
</div>
</virtual-scroller>
</div>
<div class="book-browser-footer" *ngIf="selectedBooks.size > 0" [@slideInOut]>
<div class="footer-items-container">
<div class="flex flex-row">
<div class="flex flex-col flex-grow">
<div class="book-browser-header flex justify-between items-center p-2 rounded-t-xl mb-4">
<div class="flex items-center">
<ng-container *ngIf="entityType$ | async as entityType">
<p-button *ngIf="entityType === EntityType.LIBRARY || entityType === EntityType.ALL_BOOKS"
icon="pi pi-book"
label="Assign Shelf"
severity="info"
(onClick)="openShelfAssigner()">
</p-button>
<p-button *ngIf="entityType === EntityType.SHELF"
icon="pi pi-minus-circle"
label="Unshelf"
severity="info"
(click)="unshelfBooks()">
</p-button>
<p-button
icon="pi pi-database"
label="Refresh Metadata"
severity="info"
(click)="updateMetadata()">
</p-button>
<p-button icon="pi pi-times"
label="Deselect All"
severity="warn"
(click)="deselectAllBooks()">
</p-button>
<p *ngIf="entityType !== EntityType.ALL_BOOKS" class="text-2xl">
{{ entityType }}: {{ (entity$ | async)?.name }}
</p>
<p *ngIf="entityType === EntityType.ALL_BOOKS" class="text-2xl">
All Books
</p>
<div *ngIf="entityType !== EntityType.ALL_BOOKS">
<p-button icon="pi pi-ellipsis-v" [rounded]="true" [text]="true" severity="info" (click)="entitymenu.toggle($event)"></p-button>
<p-menu #entitymenu [model]="entityOptions" [popup]="true" appendTo="body"></p-menu>
</div>
</ng-container>
</div>
<div class="flex items-center gap-8">
<input type="text" pInputText placeholder="Search title or author..." [(ngModel)]="bookTitle" (ngModelChange)="onBookTitleChange($event)"/>
<p-select [options]="sortOptions" optionLabel="label" placeholder="Select Sorting" [(ngModel)]="selectedSort" (onChange)="updateSortOption($event.value)"></p-select>
<div *ngFor="let option of stateOptions" class="field-checkbox">
<p-radioButton [inputId]="option.key" [value]="option.value" [(ngModel)]="value" (onClick)="viewChanged()"></p-radioButton>
<label [for]="option.key" class="ml-2">{{ option.label }}</label>
</div>
<p-button icon="pi pi-heart" [rounded]="true" severity="help" [outlined]="true" (click)="toggleFilters()"/>
</div>
</div>
<div *ngIf="bookState$ | async as bookState">
<div *ngIf="!bookState?.loaded && !bookState?.error">
<p-progressSpinner></p-progressSpinner>
</div>
<div class="virtual-scroller-container">
<div class="no-books-container" *ngIf="bookState?.error">
<p class="no-books-text">
{{ entityType === EntityType.LIBRARY ? "Failed to load library's books!" : "Failed to load shelf's books!" }}
</p>
</div>
<div class="no-books-container" *ngIf="!bookState?.error && bookState?.loaded && bookState?.books?.length === 0">
<p class="no-books-text">
{{ entityType === EntityType.LIBRARY ? "This library has no books!" : "This shelf has no books!" }}
</p>
</div>
<div class="book-card-container" *ngIf="bookState?.books as books">
<app-book-table *ngIf="value === 'table' && books.length > 0" [books]="books" (selectedBooksChange)="onSelectedBooksChange($event)"
[sortOption]="selectedSort"></app-book-table>
<virtual-scroller *ngIf="value === 'grid'" class="virtual-scroller" #scroll [items]="books">
<div class="grid grid-cols-12 gap-4" #container>
<div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems">
<app-book-card
[book]="book"
[isCheckboxEnabled]="true"
[onBookSelect]="handleBookSelect.bind(this)"
[isSelected]="selectedBooks.has(book.id)">
</app-book-card>
</div>
</div>
</virtual-scroller>
</div>
<div class="book-browser-footer" *ngIf="selectedBooks.size > 0" [@slideInOut]>
<div class="flex justify-between gap-8">
<ng-container *ngIf="entityType$ | async as entityType">
<p-button *ngIf="entityType === EntityType.LIBRARY || entityType === EntityType.ALL_BOOKS"
icon="pi pi-book"
label="Assign Shelf"
severity="info"
(onClick)="openShelfAssigner()">
</p-button>
<p-button *ngIf="entityType === EntityType.SHELF"
icon="pi pi-minus-circle"
label="Unshelf"
severity="info"
(click)="unshelfBooks()">
</p-button>
<p-button
icon="pi pi-database"
label="Refresh Metadata"
severity="info"
(click)="updateMetadata()">
</p-button>
<p-button icon="pi pi-times"
label="Deselect All"
severity="warn"
(click)="deselectAllBooks()">
</p-button>
</ng-container>
</div>
</div>
</div>
</div>
</div>
<div *ngIf="showFilters" class="w-[225px] ml-4 h-[calc(100vh-6.5rem)] rounded-xl book-browser-filters">
<p class="text-xl p-4">Filters:</p>
<p-accordion value="0">
<p-accordion-panel value="0">
<p-accordion-header>Authors</p-accordion-header>
<p-accordion-content class="h-[35rem] !overflow-y-auto">
<div *ngIf="authorBookCount$ | async as authors">
<div *ngFor="let author of authors">
<p
class="cursor-pointer transition-colors duration-200 ease-in-out"
[ngClass]="{'text-[var(--primary-color)]': activeAuthor === author.author.name}"
(click)="authorClicked(author)">
<p-badge [value]="author.bookCount"></p-badge>
{{ author.author.name }}
</p>
</div>
</div>
</p-accordion-content>
</p-accordion-panel>
<p-accordion-panel value="1">
<p-accordion-header>Genres</p-accordion-header>
<p-accordion-content class="h-[35rem] !overflow-y-auto">
<div *ngIf="categoryBookCount$ | async as categories">
<div *ngFor="let category of categories">
<p
class="cursor-pointer transition-colors duration-200 ease-in-out"
[ngClass]="{'text-[var(--primary-color)]': activeCategory === category.category.name}"
(click)="categoryClicked(category)">
<p-badge [value]="category.bookCount"></p-badge>
{{ category.category.name }}
</p>
</div>
</div>
</p-accordion-content>
</p-accordion-panel>
</p-accordion>
</div>
</div>
@@ -1,29 +1,12 @@
.book-browser-header {
display: flex;
justify-content: space-between;
padding: 8px 16px;
background-color: var(--card-background);
border-radius: 12px 12px 0 0;
margin-bottom: 15px;
align-items: center;
.left-items {
display: flex;
align-items: center;
}
}
.p {
color: var(--text-color);
.book-browser-filters {
background-color: var(--card-background);
overflow: hidden;
}
.header-right-items {
display: flex;
gap: 2rem;
align-items: center;
}
.virtual-scroller-container {
position: relative;
}
@@ -61,11 +44,6 @@
align-items: start;
}
.empty-message {
display: flex;
justify-content: space-around;
}
.book-browser-footer {
position: absolute;
bottom: 0;
@@ -101,9 +79,3 @@
pointer-events: none;
}
.footer-items-container {
display: flex;
justify-content: space-between;
gap: 2rem;
}
@@ -4,7 +4,7 @@ import {MenuItem, MessageService} from 'primeng/api';
import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service';
import {map, switchMap} from 'rxjs/operators';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {BehaviorSubject, combineLatest, Observable, of} from 'rxjs';
import {ShelfService} from '../../service/shelf.service';
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
@@ -13,14 +13,14 @@ import {Shelf} from '../../model/shelf.model';
import {SortService} from '../../service/sort.service';
import {SortOption} from '../../model/sort.model';
import {BookState} from '../../model/state/book-state.model';
import {Book} from '../../model/book.model';
import {Author, Book, Category} 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, NgForOf, NgIf} from '@angular/common';
import {AsyncPipe, NgClass, NgForOf, NgIf} from '@angular/common';
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
import {BookCardComponent} from './book-card/book-card.component';
import {ProgressSpinner} from 'primeng/progressspinner';
@@ -29,6 +29,8 @@ import {RadioButton} from 'primeng/radiobutton';
import {Menu} from 'primeng/menu';
import {InputText} from 'primeng/inputtext';
import {FormsModule} from '@angular/forms';
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
import {Badge} from 'primeng/badge';
export enum EntityType {
LIBRARY = 'Library',
@@ -41,7 +43,7 @@ export enum EntityType {
standalone: true,
templateUrl: './book-browser.component.html',
styleUrls: ['./book-browser.component.scss'],
imports: [Button, NgIf, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Select, RadioButton, Menu, NgForOf, InputText, FormsModule, BookTableComponent],
imports: [Button, NgIf, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Select, RadioButton, Menu, NgForOf, InputText, FormsModule, BookTableComponent, AccordionHeader, AccordionContent, AccordionPanel, Accordion, Badge, NgClass],
animations: [
trigger('slideInOut', [
state('void', style({
@@ -75,9 +77,11 @@ export class BookBrowserComponent implements OnInit {
isDrawerVisible: boolean = false;
dynamicDialogRef: DynamicDialogRef | undefined;
EntityType = EntityType;
showFilters: boolean = false;
stateOptions: any[] = [{label: 'Grid', value: 'grid'}, {label: 'Table', value: 'table'}];
value: string = 'table';
value: string = 'grid';
@ViewChild(BookTableComponent) bookTableComponent!: BookTableComponent;
@@ -90,6 +94,13 @@ export class BookBrowserComponent implements OnInit {
private sortService = inject(SortService);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
authorBookCount$: Observable<{ author: Author; bookCount: number; }[]> | undefined = this.bookService.authorBookCount$;
categoryBookCount$: Observable<{ category: Category; bookCount: number; }[]> | undefined = this.bookService.categoryBookCount$;
toggleFilters() {
this.showFilters = !this.showFilters;
}
ngOnInit(): void {
this.bookService.loadBooks();
this.sortOptions = SortService.generateSortOptions();
@@ -99,6 +110,7 @@ export class BookBrowserComponent implements OnInit {
this.entityType = EntityType.ALL_BOOKS;
this.entityType$ = of(EntityType.ALL_BOOKS);
this.bookState$ = this.fetchAllBooks();
} else {
const routeEntityInfo$ = this.getEntityInfoFromRoute();
@@ -178,7 +190,75 @@ export class BookBrowserComponent implements OnInit {
private fetchAllBooks(): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => this.processBookState(bookState)),
switchMap(bookState => this.filterBooks(bookState))
switchMap(bookState => this.filterBooks(bookState)),
switchMap(bookState => this.newFilter(bookState))
);
}
author = new BehaviorSubject<number | null>(null);
category = new BehaviorSubject<number | null>(null);
activeAuthor: string | null = null;
activeCategory: string | null = null;
authorClicked(author: { author: Author; bookCount: number }) {
this.activeAuthor = author.author.name;
if (this.author.value === author.author.id) {
this.author.next(null);
this.activeAuthor = null;
} else {
this.category.next(null);
this.activeCategory = null;
this.author.next(author.author.id);
}
}
categoryClicked(category: { category: Category; bookCount: number }) {
this.activeCategory = category.category.name;
if (this.category.value === category.category.id) {
this.category.next(null);
this.activeCategory = null;
} else {
this.author.next(null);
this.activeAuthor = null;
this.category.next(category.category.id);
}
}
private newFilter(bookState: BookState): Observable<BookState> {
return combineLatest([this.author, this.category]).pipe(
map(([authorId, categoryId]) => {
let filteredBooks = bookState.books || [];
if (authorId !== null) {
filteredBooks = filteredBooks.filter(book =>
book.metadata?.authors.some(author => author.id === authorId)
);
} else if (categoryId !== null) {
filteredBooks = filteredBooks.filter(book =>
book.metadata?.categories?.some(category => category.id === categoryId)
);
}
return {...bookState, books: filteredBooks};
})
);
}
private filterBooks(bookState: BookState): Observable<BookState> {
return this.bookOrAuthor$.pipe(
map(title => {
if (title && title.trim() !== '') {
const filteredBooks = bookState.books?.filter(book => {
const matchesTitle = book.metadata?.title?.toLowerCase().includes(title.toLowerCase());
const matchesAuthor = book.metadata?.authors.some(author =>
author.name.toLowerCase().includes(title.toLowerCase())
);
return matchesTitle || matchesAuthor;
}) || null;
return {...bookState, books: filteredBooks};
}
return bookState;
})
);
}
@@ -204,23 +284,6 @@ export class BookBrowserComponent implements OnInit {
return bookState;
}
private filterBooks(bookState: BookState): Observable<BookState> {
return this.bookOrAuthor$.pipe(
map(title => {
if (title && title.trim() !== '') {
const filteredBooks = bookState.books?.filter(book => {
const matchesTitle = book.metadata?.title?.toLowerCase().includes(title.toLowerCase());
const matchesAuthor = book.metadata?.authors.some(author =>
author.name.toLowerCase().includes(title.toLowerCase())
);
return matchesTitle || matchesAuthor;
}) || null;
return {...bookState, books: filteredBooks};
}
return bookState;
})
);
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraryState$.pipe(
@@ -261,7 +324,7 @@ export class BookBrowserComponent implements OnInit {
deselectAllBooks(): void {
this.selectedBooks.clear();
this.isDrawerVisible = false;
if(this.bookTableComponent) {
if (this.bookTableComponent) {
this.bookTableComponent.clearSelectedBooks();
}
}
@@ -350,4 +413,5 @@ export class BookBrowserComponent implements OnInit {
})
}
}
@@ -1,8 +1,8 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {catchError, map, switchMap, tap} from 'rxjs/operators';
import {Book, BookMetadata, BookSetting, BookType, EpubViewerSetting, PdfViewerSetting} from '../model/book.model';
import {catchError, distinctUntilChanged, map, tap} from 'rxjs/operators';
import {Author, Book, BookMetadata, BookSetting, Category} from '../model/book.model';
import {BookState} from '../model/state/book-state.model';
import {API_CONFIG} from '../../config/api-config';
@@ -20,6 +20,57 @@ export class BookService {
});
bookState$ = this.bookStateSubject.asObservable();
authorBookCount$: Observable<{ author: Author; bookCount: number }[]> = this.bookState$.pipe(
map((state) => {
const books = state.books || [];
const authorMap = new Map<number, { author: Author; bookCount: number }>();
books.forEach((book) => {
book.metadata?.authors.forEach((author) => {
if (!authorMap.has(author.id)) {
authorMap.set(author.id, {author, bookCount: 0});
}
const authorData = authorMap.get(author.id);
if (authorData) {
authorData.bookCount += 1;
}
});
});
return Array.from(authorMap.values()).sort((a, b) => {
if (b.bookCount !== a.bookCount) {
return b.bookCount - a.bookCount;
}
return a.author.name.localeCompare(b.author.name);
});
}),
distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr))
);
categoryBookCount$: Observable<{ category: Category; bookCount: number }[]> = this.bookState$.pipe(
map((state) => {
const books = state.books || [];
const categoryMap = new Map<number, { category: Category; bookCount: number }>();
books.forEach((book) => {
book.metadata?.categories.forEach((category) => {
if (!categoryMap.has(category.id)) {
categoryMap.set(category.id, {category, bookCount: 0});
}
let categoryData = categoryMap.get(category.id);
if (categoryData) {
categoryData.bookCount += 1;
}
});
});
return Array.from(categoryMap.values()).sort((a, b) => {
if (b.bookCount !== a.bookCount) {
return b.bookCount - a.bookCount;
}
return a.category.name.localeCompare(b.category.name);
});
}),
distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr))
)
private http = inject(HttpClient);
loadBooks(): void {
@@ -205,26 +256,4 @@ export class BookService {
const book = this.bookStateSubject.value.books?.find(book => book.id === bookId);
return book?.metadata ?? null;
}
updateBookMetadata(bookId: number | undefined, metadataField: string | undefined, value: any) {
if (!bookId || !metadataField) {
console.error("Invalid bookId or metadataField.");
return;
}
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
const updatedBook = {
...book,
metadata: {
...book.metadata,
[metadataField]: value
}
};
return updatedBook as Book;
}
return book;
});
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
}