WIP: Rearrange code

This commit is contained in:
aditya.chandel
2025-01-12 13:38:57 -07:00
parent 7df0052036
commit ef3556cb0c
77 changed files with 101 additions and 115 deletions
@@ -0,0 +1,93 @@
<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 by title..." [(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($event)"></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">
<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>
@@ -0,0 +1,109 @@
.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);
}
.header-right-items {
display: flex;
gap: 2rem;
align-items: center;
}
.virtual-scroller-container {
position: relative;
}
.no-books-text {
font-size: 1rem;
color: var(--text-color);
}
.no-books-container {
padding-top: 3rem;
display: flex;
justify-content: center;
align-items: center;
}
.virtual-scroller {
width: 100%;
height: calc(100vh - 11.5rem);
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
}
.virtual-scroller-item {
height: 220px;
width: 135px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
gap: 1.3rem;
overflow: hidden;
align-items: start;
}
.empty-message {
display: flex;
justify-content: space-around;
}
.book-browser-footer {
position: absolute;
bottom: 0;
left: 32%;
right: 32%;
display: flex;
justify-content: center;
padding: 1.1rem;
box-shadow: 0px -2px 10px rgba(0, 0, 0, 0.1);
z-index: 1;
border-radius: 10px 10px 0 0;
}
.book-browser-footer::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.85);
z-index: -1;
border-radius: 10px 10px 0 0;
border: 1px solid rgba(255, 255, 255, 0.5);
border-width: 1px 1px 0px 1px;
}
.book-browser-footer > * {
pointer-events: auto;
}
.book-browser-footer:hover::before {
pointer-events: none;
}
.footer-items-container {
display: flex;
justify-content: space-between;
gap: 2rem;
}
@@ -0,0 +1,337 @@
import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
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 {ShelfService} from '../../service/shelf.service';
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
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 {LibraryShelfMenuService} from '../../service/library-shelf-menu.service';
import {SelectButtonChangeEvent} from 'primeng/selectbutton';
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';
export enum EntityType {
LIBRARY = 'Library',
SHELF = 'Shelf',
ALL_BOOKS = 'All Books'
}
@Component({
selector: 'app-book-browser',
standalone: false,
templateUrl: './book-browser.component.html',
styleUrls: ['./book-browser.component.scss'],
animations: [
trigger('slideInOut', [
state('void', style({
transform: 'translateY(100%)'
})),
state('*', style({
transform: 'translateY(0)'
})),
transition(':enter', [
animate('0.1s ease-in')
]),
transition(':leave', [
animate('0.1s ease-out')
])
])
]
})
export class BookBrowserComponent implements OnInit {
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | null> | undefined;
entityType$: Observable<EntityType> | undefined;
bookTitle$ = new BehaviorSubject<string>('');
entity: Library | Shelf | null = null;
entityType: EntityType | undefined;
bookTitle: string = '';
entityOptions: MenuItem[] | undefined;
selectedBooks: Set<number> = new Set();
selectedSort: SortOption | null = null;
sortOptions: SortOption[] = [];
isDrawerVisible: boolean = false;
dynamicDialogRef: DynamicDialogRef | undefined;
EntityType = EntityType;
stateOptions: any[] = [{label: 'Grid', value: 'grid'}, {label: 'Table', value: 'table'}];
value: string = 'table';
@ViewChild(BookTableComponent) bookTableComponent!: BookTableComponent;
constructor(
private activatedRoute: ActivatedRoute,
private messageService: MessageService,
private libraryService: LibraryService,
private bookService: BookService,
private shelfService: ShelfService,
private dialogService: DialogService,
private sortService: SortService,
private libraryShelfMenuService: LibraryShelfMenuService) {
}
ngOnInit(): void {
this.sortOptions = SortService.generateSortOptions();
const isAllBooksRoute = this.activatedRoute.snapshot.routeConfig?.path === 'all-books';
if (isAllBooksRoute) {
this.entityType = EntityType.ALL_BOOKS;
this.entityType$ = of(EntityType.ALL_BOOKS);
this.bookState$ = this.fetchAllBooks();
} else {
const routeEntityInfo$ = this.getEntityInfoFromRoute();
this.bookState$ = routeEntityInfo$.pipe(
switchMap(({entityId, entityType}) => this.fetchBooksByEntity(entityId, entityType)),
);
this.entity$ = routeEntityInfo$.pipe(
switchMap(({entityId, entityType}) => this.fetchEntity(entityId, entityType))
);
this.entityType$ = routeEntityInfo$.pipe(
map(({entityType}) => entityType)
);
this.entity$.subscribe(entity => {
this.entity = entity;
this.entityOptions = this.libraryShelfMenuService.initializeLibraryMenuItems(entity);
this.setSelectedSortFromEntity(entity);
});
}
this.activatedRoute.paramMap.subscribe(() => {
this.bookTitle$.next('');
this.bookTitle = '';
});
}
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)) {
return {entityId: libraryId, entityType: EntityType.LIBRARY};
} else if (!isNaN(shelfId)) {
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) {
this.libraryShelfMenuService.initializeLibraryMenuItems(this.entity);
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.filterBooksByTitle(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.filterBooksByTitle(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 filterBooksByTitle(bookState: BookState): Observable<BookState> {
return this.bookTitle$.pipe(
map(title => {
if (title && title.trim() !== '') {
const filteredBooks = bookState.books?.filter(book =>
book.metadata?.title?.toLowerCase().includes(title.toLowerCase())
) || null;
return {...bookState, books: filteredBooks};
}
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;
this.bookTableComponent.clearSelectedBooks();
}
viewChanged(event: SelectButtonChangeEvent) {
this.selectedBooks.clear();
this.isDrawerVisible = false;
}
unshelfBooks() {
if (this.entity) {
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id])).subscribe(
() => {
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'});
}
);
}
}
updateSortOption(sortOption: SortOption): void {
this.selectedSort = sortOption;
if (this.entityType === EntityType.ALL_BOOKS) {
this.bookState$ = this.fetchAllBooks();
} else {
const routeParam$ = this.getEntityInfoFromRoute();
this.bookState$ = routeParam$.pipe(
switchMap(({entityId, entityType}) => this.fetchBooksByEntity(entityId, entityType))
);
}
if (this.entityType === EntityType.LIBRARY) {
this.libraryService.updateSort(this.entity?.id!, sortOption).subscribe();
} else if (this.entityType === EntityType.SHELF) {
this.shelfService.updateSort(this.entity?.id!, sortOption).subscribe();
}
}
private setSelectedSortFromEntity(entity: Library | Shelf | null): void {
if (entity?.sort) {
const {field, direction} = entity.sort;
this.selectedSort = this.sortOptions.find(option => option.field === field && option.direction === direction) || null;
} else {
this.selectedSort = null;
}
}
onBookTitleChange(newTitle: string): void {
this.bookTitle$.next(newTitle);
}
openShelfAssigner() {
this.dynamicDialogRef = this.dialogService.open(ShelfAssignerComponent, {
header: `Update Books Shelves`,
modal: true,
closable: true,
width: '30%',
height: '60%',
contentStyle: {overflow: 'auto'},
baseZIndex: 10,
style: {
position: 'absolute',
top: '15%',
},
data: {
isMultiBooks: true,
bookIds: this.selectedBooks
},
});
this.dynamicDialogRef.onClose.subscribe(() => {
this.selectedBooks.clear();
});
}
updateMetadata() {
this.dialogService.open(MetadataFetchOptionsComponent, {
header: 'Metadata Refresh Options',
modal: true,
closable: true,
data: {
bookIds: this.selectedBooks,
metadataRefreshType: MetadataRefreshType.BOOKS
}
})
}
}
@@ -0,0 +1,32 @@
<div class="book-card"
[class.selected]="isSelected"
(mouseover)="isHovered = true"
(mouseout)="isHovered = false">
<div class="cover-container">
<img
[src]="coverImageSrc(book)"
class="book-cover placeholder"
alt="Cover of {{ book.metadata?.title }}"
loading="lazy"/>
<p-checkbox
*ngIf="isCheckboxEnabled && (isHovered || isSelected)"
[(ngModel)]="isSelected"
binary="true"
class="select-checkbox"
(ngModelChange)="toggleSelection(isSelected || false)"></p-checkbox>
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book)"></p-button>
<p-button [rounded]="true" icon="pi pi-book" class="info-btn" (click)="readBook(book)"></p-button>
</div>
<div class="book-info">
<div class="book-title-container">
<h4 class="book-title">{{ book.metadata?.title }}</h4>
<p-menu #menu [model]="items" [popup]="true" appendTo="body"></p-menu>
<p-button
[text]="true"
(click)="menu.toggle($event)"
icon="pi pi-ellipsis-v">
</p-button>
</div>
</div>
</div>
@@ -0,0 +1,81 @@
.book-card {
background-color: var(--card-background);
border-radius: 8px;
position: relative;
overflow: hidden;
transition: border 0.2s;
&.selected {
border: 2px solid var(--primary-color);
}
}
.cover-container {
position: relative;
}
.book-title-container {
display: flex;
align-items: center;
justify-content: space-between;
}
.book-title {
flex-grow: 1;
font-size: 0.85rem;
color: var(--text-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
padding: 0 6px;
}
.book-cover {
width: 100%;
height: auto;
border-radius: 8px 8px 0 0;
transition: filter 0.2s ease-in-out;
}
.info-btn,
.read-btn {
position: absolute;
left: 50%;
transform: translateX(-50%);
display: none;
transition: opacity 0.2s ease-in-out;
}
.info-btn {
top: 25%;
}
.read-btn {
bottom: 25%;
}
.cover-container:hover .book-cover {
filter: blur(2px);
}
.cover-container:hover .info-btn,
.cover-container:hover .read-btn {
display: block;
}
.select-checkbox {
position: absolute;
top: 8px;
right: 8px;
display: none;
z-index: 1;
}
.cover-container:hover .select-checkbox {
display: block;
}
.book-card.selected .select-checkbox {
display: block;
}
@@ -0,0 +1,120 @@
import {Component, Input, OnInit} from '@angular/core';
import {Book} from '../../../model/book.model';
import {Button} from 'primeng/button';
import {Router} from '@angular/router';
import {MenuModule} from 'primeng/menu';
import {MenuItem} from 'primeng/api';
import {DialogService} from 'primeng/dynamicdialog';
import {ShelfAssignerComponent} from '../../shelf-assigner/shelf-assigner.component';
import {BookService} from '../../../service/book.service';
import {CheckboxModule} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {NgIf} from '@angular/common';
import {Observable} from 'rxjs';
import {BookMetadataCenterComponent} from '../../../../metadata/book-metadata-center/book-metadata-center.component';
@Component({
selector: 'app-book-card',
templateUrl: './book-card.component.html',
styleUrls: ['./book-card.component.scss'],
imports: [
Button,
MenuModule,
CheckboxModule,
FormsModule,
NgIf,
],
})
export class BookCardComponent implements OnInit {
@Input() book!: Book;
@Input() isCheckboxEnabled: boolean = false;
@Input() onBookSelect?: (bookId: number, selected: boolean) => void;
@Input() isSelected: boolean = false;
items: MenuItem[] | undefined;
isHovered: boolean = false;
constructor(private bookService: BookService, private dialogService: DialogService) {
}
ngOnInit(): void {
this.initMenu();
}
coverImageSrc(book: Book): string {
return this.bookService.getBookCoverUrl(book.id);
}
readBook(book: Book): void {
this.bookService.readBook(book.id);
}
toggleSelection(selected: boolean): void {
if (this.isCheckboxEnabled) {
this.isSelected = selected;
if (this.onBookSelect) {
this.onBookSelect(this.book.id, selected);
}
}
}
private initMenu() {
this.items = [
{
label: 'Options',
items: [
{
label: 'Edit shelf',
icon: 'pi pi-folder',
command: () => this.openShelfDialog(this.book),
},
{
label: 'View metadata',
icon: 'pi pi-info-circle',
command: () => this.openBookDetailsDialog(this.book.id),
},
],
},
];
}
openBookDetailsDialog(bookId: number): void {
this.bookService.getBookByIdFromAPI(bookId, true).subscribe(({
next: (book) => {
this.dialogService.open(BookMetadataCenterComponent, {
header: 'Open book details',
modal: true,
closable: true,
width: '1200px',
height: '835px',
showHeader: false,
closeOnEscape: true,
data: {
book: book
}
});
},
error: (error) => {
console.error('Error fetching book:', error);
}
}))
}
private openShelfDialog(book: Book): void {
this.dialogService.open(ShelfAssignerComponent, {
header: `Update Shelves: ${book.metadata?.title}`,
modal: true,
width: '30%',
height: '70%',
contentStyle: {overflow: 'auto'},
baseZIndex: 10,
data: {
book: this.book
},
});
}
openBookInfo(book: Book): void {
this.openBookDetailsDialog(book.id)
}
}
@@ -0,0 +1,55 @@
<p-table
[value]="books"
[resizableColumns]="true"
showGridlines
stripedRows
[scrollable]="true"
[scrollHeight]="'calc(100vh - 160px)'"
[virtualScroll]="true"
[virtualScrollItemSize]="46"
[(selection)]="selectedBooks"
(onHeaderCheckboxToggle)="onHeaderCheckboxToggle($event)"
(onRowSelect)="onRowSelect($event)"
(onRowUnselect)="onRowUnselect($event)">
<ng-template #header>
<tr>
<th class="max-w-16">Cover</th>
<th pResizableColumn>Title</th>
<th pResizableColumn>Publisher</th>
<th>Published</th>
<th>ISBN</th>
<th>Language</th>
<th>Rating</th>
<th>Pages</th>
<th>Reviews</th>
<th>
<p-tableHeaderCheckbox/>
</th>
</tr>
</ng-template>
<ng-template #body let-book>
<tr style="height:46px">
<td (click)="openMetadataCenter(book.id)"><img [src]="getBookCoverUrl(book.id)" alt="Book Cover" class="size-7"/></td>
<td (click)="openMetadataCenter(book.id)" class="w-1/2 max-w-96 overflow-hidden truncate" [title]="book.metadata?.id">{{ book.metadata?.title }}</td>
<td class="w-1/6 max-w-40 overflow-hidden truncate">{{ book.metadata?.publisher }}</td>
<td class="w-1/12 max-w-30 overflow-hidden truncate">{{ book.metadata?.publishedDate }}</td>
<td class="w-1/12 max-w-32 overflow-hidden truncate">{{ book.metadata?.isbn10 }}</td>
<td class="w-1/12 max-w-28 overflow-hidden truncate">{{ book.metadata?.language }}</td>
<td class="w-1/12 max-w-30 overflow-hidden truncate">
<ng-container *ngIf="book.metadata">
<p-rating
[(ngModel)]="book.metadata.rating"
readonly
stars="5"
[style.--p-rating-icon-active-color]="getStarColor(book.metadata.rating)">
</p-rating>
</ng-container>
</td>
<td class="w-1/12 max-w-32 overflow-hidden truncate">{{ book.metadata?.pageCount }}</td>
<td class="w-1/12 max-w-32 overflow-hidden truncate">{{ book.metadata?.reviewCount }}</td>
<td class="max-w-16">
<p-tableCheckbox [value]="book"></p-tableCheckbox>
</td>
</tr>
</ng-template>
</p-table>
@@ -0,0 +1,6 @@
/*
.p-datatable-flex-scrollable .p-datatable-wrapper {
flex-basis: auto !important;
height: 0 !important;
}
*/
@@ -0,0 +1,114 @@
import {Component, EventEmitter, Input, OnChanges, Output} from '@angular/core';
import {TableModule} from 'primeng/table';
import {NgIf} from '@angular/common';
import {BookService} from '../../../service/book.service';
import {Rating} from 'primeng/rating';
import {FormsModule} from '@angular/forms';
import {BookMetadataCenterComponent} from '../../../../metadata/book-metadata-center/book-metadata-center.component';
import {DialogService} from 'primeng/dynamicdialog';
import {Book} from '../../../model/book.model';
import {SortOption} from '../../../model/sort.model';
@Component({
selector: 'app-book-table',
standalone: true,
templateUrl: './book-table.component.html',
imports: [
TableModule,
NgIf,
Rating,
FormsModule
],
styleUrl: './book-table.component.scss'
})
export class BookTableComponent implements OnChanges {
selectedBooks: Book[] = [];
selectedBookIds: Set<number> = new Set();
@Output() selectedBooksChange = new EventEmitter<Set<number>>();
@Input() books: Book[] = [];
@Input() sortOption: SortOption | null = null;
constructor(private bookService: BookService, private dialogService: DialogService) {
}
// Hack to set virtual-scroller height
ngOnChanges() {
let wrapperElements: HTMLCollection = document.getElementsByClassName('p-virtualscroller');
Array.prototype.forEach.call(wrapperElements, function (wrapperElement) {
wrapperElement.style["height"] = 'calc(100vh - 160px)';
});
}
clearSelectedBooks(): void {
this.selectedBookIds.clear();
this.selectedBooks = [];
this.selectedBooksChange.emit(this.selectedBookIds);
}
onRowSelect(event: any): void {
this.selectedBookIds.add(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
}
onRowUnselect(event: any): void {
this.selectedBookIds.delete(event.data.id);
this.selectedBooksChange.emit(this.selectedBookIds);
}
onHeaderCheckboxToggle(event: any): void {
if (event.checked) {
this.selectedBooks = [...this.books];
this.selectedBookIds = new Set(this.books.map(book => book.id));
} else {
this.clearSelectedBooks();
}
this.selectedBooksChange.emit(this.selectedBookIds);
}
getBookCoverUrl(bookId: number): string {
return this.bookService.getBookCoverUrl(bookId);
}
openMetadataCenter(id: number): void {
this.openBookDetailsDialog(id);
}
openBookDetailsDialog(bookId: number): void {
this.bookService.getBookByIdFromAPI(bookId, true).subscribe({
next: (book) => {
this.dialogService.open(BookMetadataCenterComponent, {
header: 'Open book details',
modal: true,
closable: true,
width: '1200px',
height: '835px',
showHeader: false,
closeOnEscape: true,
dismissableMask: true,
data: {
book: book
}
});
},
error: (error) => {
console.error('Error fetching book:', error);
}
});
}
getStarColor(rating: number): string {
if (rating >= 4.5) {
return 'rgb(34, 197, 94)';
} else if (rating >= 4) {
return 'rgb(52, 211, 153)';
} else if (rating >= 3.5) {
return 'rgb(234, 179, 8)';
} else if (rating >= 2.5) {
return 'rgb(249, 115, 22)';
} else {
return 'rgb(239, 68, 68)';
}
}
}
@@ -0,0 +1,30 @@
<div class="search-container">
<div class="search-input-wrapper">
<i class="pi pi-search search-icon"></i>
<input
style="width: 400px;"
type="text"
pInputText
[(ngModel)]="searchQuery"
(input)="onSearchInputChange()"
placeholder="Search books..."
class="search-input"
/>
<p-button *ngIf="searchQuery" icon="pi pi-times" (click)="clearSearch()" [text]="true" [rounded]="true" class="clear-btn" aria-label="Clear Search"></p-button>
</div>
<div class="search-dropdown layout-menu" [class.show]="(books.length > 0)">
<ng-container *ngIf="books.length > 0; else noResults">
<div class="search-dropdown-item" *ngFor="let book of books" (click)="onBookClick(book)">
<img [src]="getBookCoverUrl(book.id)" alt="Book Cover" class="search-book-cover" />
<span class="search-book-name">{{ book.metadata?.title }}</span>
</div>
</ng-container>
<ng-template #noResults>
<div class="search-dropdown-item">
<span>No results found</span>
</div>
</ng-template>
</div>
</div>
@@ -0,0 +1,84 @@
.search-container {
margin-left: 20px;
position: relative;
}
.search-input-wrapper {
position: relative;
width: 400px;
}
.search-icon {
position: absolute;
top: 50%;
left: 10px;
transform: translateY(-50%);
color: var(--text-color-secondary);
font-size: 1.0rem;
pointer-events: none;
}
.search-input {
width: 100%;
padding-left: 30px;
height: 2.5rem;
line-height: 2.5rem;
font-size: 1rem;
}
.clear-btn {
color: var(--text-color-secondary);
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
}
.search-dropdown {
position: absolute;
left: 0;
background-color: var(--code-background);
border: 1px solid var(--border-color);
border-radius: var(--card-border);
z-index: 1000;
max-height: 500px;
overflow-y: auto;
width: 600px;
opacity: 0;
height: 0;
transition: opacity 0.3s ease, height 0.3s ease;
}
.search-dropdown.show {
opacity: 1;
height: auto;
}
.search-dropdown-item {
display: flex;
align-items: center;
padding: 10px;
cursor: pointer;
transition: background-color 0.3s;
&:hover {
background-color: var(--surface-hover);
}
}
.search-book-cover {
width: 25px;
height: 37px;
object-fit: cover;
max-width: 100px;
max-height: 150px;
border-radius: 4px;
margin-right: 10px;
}
.search-book-name {
font-size: 14px;
font-weight: 500;
color: var(--text-color);
flex-grow: 1;
}
@@ -0,0 +1,100 @@
import {Component, OnDestroy, OnInit} from '@angular/core';
import {Subject, Subscription} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {Book} from '../../model/book.model';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {Router} from '@angular/router';
import {BookService} from '../../service/book.service';
import {BookMetadataCenterComponent} from '../../../metadata/book-metadata-center/book-metadata-center.component';
import {DialogService} from 'primeng/dynamicdialog';
import {Button} from 'primeng/button';
import {NgForOf, NgIf} from '@angular/common';
@Component({
selector: 'app-book-searcher',
templateUrl: './book-searcher.component.html',
imports: [
FormsModule,
InputTextModule,
Button,
NgIf,
NgForOf
],
styleUrls: ['./book-searcher.component.scss'],
standalone: true
})
export class BookSearcherComponent implements OnInit, OnDestroy {
searchQuery: string = '';
books: Book[] = [];
#searchSubject = new Subject<string>();
#subscription!: Subscription;
constructor(private bookService: BookService, private router: Router, private dialogService: DialogService) {}
ngOnInit(): void {
this.initializeSearch();
}
initializeSearch(): void {
this.#subscription = this.#searchSubject.pipe(
debounceTime(350),
distinctUntilChanged(),
switchMap((query) => this.bookService.searchBooks(query).pipe(
catchError((error) => {
console.error('Error while searching books:', error);
return [];
})
))
).subscribe({
next: (result: Book[]) => this.books = result,
error: (error) => console.error('Subscription error:', error)
});
}
onSearchInputChange(): void {
this.#searchSubject.next(this.searchQuery.trim());
}
onBookClick(book: Book): void {
this.clearSearch();
this.openBook(book.id);
}
openBook(bookId: number): void {
this.bookService.getBookByIdFromAPI(bookId, true).subscribe(({
next: (book) => {
this.dialogService.open(BookMetadataCenterComponent, {
header: 'Open book details',
modal: true,
closable: true,
width: '1200px',
height: '835px',
showHeader: false,
closeOnEscape: true,
data: {
book: book
}
});
},
error: (error) => {
console.error('Error fetching book:', error);
}
}))
}
getBookCoverUrl(bookId: number): string {
return this.bookService.getBookCoverUrl(bookId);
}
clearSearch(): void {
this.searchQuery = '';
this.books = [];
}
ngOnDestroy(): void {
if (this.#subscription) {
this.#subscription.unsubscribe();
}
}
}
@@ -0,0 +1,73 @@
<p-stepper [value]="1" class="basis-[50rem]">
<p-step-list>
<p-step [value]="1">Library Details</p-step>
<p-step [value]="2">Select Directory</p-step>
</p-step-list>
<p-step-panels>
<p-step-panel [value]="1">
<ng-template #content let-activateCallback="activateCallback">
<div class="flex flex-col h-48 stepper-content-custom">
<div class="border-2 border-dashed border-surface-200 dark:border-surface-700 rounded bg-surface-50 dark:bg-surface-950 flex-auto flex justify-center items-center font-medium">
<div class="library-name-icon-parent">
<div class="library-name-div">
<p>Library Name: </p>
<input type="text" pInputText [(ngModel)]="libraryName" placeholder="Enter library name..."/>
</div>
<div class="library-icon-div">
<p>Library Icon:</p>
<div *ngIf="!selectedIcon">
<p-button label="Select Icon" icon="pi pi-search" (onClick)="openIconPicker()"></p-button>
</div>
<div *ngIf="selectedIcon" class="selected-icon-container">
<i [class]="selectedIcon" style="font-size: 1.25rem; margin-right: 0.75rem;"></i>
<p-button icon="pi pi-times" (onClick)="clearSelectedIcon()" [rounded]="true" [text]="true" [outlined]="true" class="remove-icon-button" severity="danger"></p-button>
</div>
</div>
</div>
<app-icon-picker (iconSelected)="onIconSelected($event)"></app-icon-picker>
</div>
<div class="flex pt-6 justify-end">
<p-button label="Next" icon="pi pi-arrow-right" iconPos="right" [disabled]="!isLibraryDetailsValid()" (onClick)="validateLibraryNameAndProceed(activateCallback)" />
</div>
</div>
</ng-template>
</p-step-panel>
<p-step-panel [value]="2">
<ng-template #content let-activateCallback="activateCallback">
<div class="flex flex-col h-48 stepper-content-custom">
<div class="border-2 border-dashed border-surface-200 dark:border-surface-700 rounded bg-surface-50 dark:bg-surface-950 flex-auto flex justify-center items-center font-medium">
<div class="flex flex-col justify-center items-center w-100">
<p-button
severity="info"
label="Add book folders"
[outlined]="true"
(onClick)="show()">
</p-button>
<p-table [value]="folders" styleClass="p-datatable-striped" class="p-table-custom mt-4">
<ng-template pTemplate="body" let-folder let-i="rowIndex">
<tr>
<td class="tr-custom">{{ folder }}</td>
<td class="tr-custom td-x-custom">
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="danger"
(onClick)="removeFolder(i)"
/>
</td>
</tr>
</ng-template>
</p-table>
</div>
</div>
<div class="flex pt-6 justify-between">
<p-button label="Back" icon="pi pi-arrow-left" iconPos="right" (onClick)="activateCallback(1)" />
<p-button severity="success" label="Save" icon="pi pi-save" [disabled]="!isDirectorySelectionValid()" (onClick)="addLibrary()"></p-button>
</div>
</div>
</ng-template>
</p-step-panel>
</p-step-panels>
</p-stepper>
@@ -0,0 +1,95 @@
.library-name-icon-parent {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2.5rem;
}
.library-name-div {
display: flex;
align-items: center;
gap: 0.5rem;
}
.library-icon-div {
display: flex;
align-items: center;
gap: 0.5rem;
}
.library-name-div label,
.library-icon-div label {
margin-right: 0.5rem;
}
.library-name-div input {
width: 200px;
}
.library-icon-div p-button {
margin-left: 0.8rem;
}
.p-stepperPanel {
display: flex;
flex-direction: column;
padding: 1rem;
}
.p-stepperPanel .flex {
display: flex;
}
.p-stepperPanel .justify-content-end {
justify-content: flex-end;
}
.p-stepperPanel .mt-3 {
margin-top: 1rem;
}
.p-table-custom {
min-width: 35rem !important;
max-height: 11.25rem !important;
overflow: scroll;
}
.tr-custom {
padding: 0.25rem 0.5rem !important;
border: 0px !important;
}
.td-x-custom {
text-align: right;
}
.w-100 {
width: 100%;
}
.p-button {
margin-left: 0.5rem;
}
.selected-icon-container {
display: flex;
align-items: center;
margin-left: 1rem;
i {
color: var(--text-color);
}
.remove-icon-button {
margin-left: 0.5rem;
}
}
.stepper-content-custom {
height: 335px;
padding: 10px;
}
.p {
color: var(--text-color);
}
@@ -0,0 +1,119 @@
import {Component, ViewChild} from '@angular/core';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DirectoryPickerComponent} from '../../../utilities/directory-picker/directory-picker.component';
import {MessageService} from 'primeng/api';
import {Router} from '@angular/router';
import {LibraryService} from '../../service/library.service';
import {IconPickerComponent} from '../../../utilities/icon-picker/icon-picker.component';
import {take} from 'rxjs';
@Component({
selector: 'app-library-creator',
standalone: false,
templateUrl: './library-creator.component.html',
styleUrl: './library-creator.component.scss'
})
export class LibraryCreatorComponent {
@ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined;
libraryName: string = '';
folders: string[] = [];
ref: DynamicDialogRef | undefined;
selectedIcon: string | null = null;
constructor(
private dialogService: DialogService,
private dynamicDialogRef: DynamicDialogRef,
private libraryService: LibraryService,
private messageService: MessageService,
private router: Router) {
}
show() {
this.ref = this.dialogService.open(DirectoryPickerComponent, {
header: 'Select Media Directory',
modal: true,
width: '50%',
height: '75%',
contentStyle: {overflow: 'auto'},
baseZIndex: 10
});
this.ref.onClose.subscribe((selectedFolder: string) => {
if (selectedFolder) {
this.addFolder(selectedFolder);
}
});
}
addFolder(folder: string): void {
this.folders.push(folder);
}
removeFolder(index: number): void {
this.folders.splice(index, 1);
}
openIconPicker() {
if (this.iconPicker) {
this.iconPicker.open();
}
}
onIconSelected(icon: string) {
this.selectedIcon = icon;
}
clearSelectedIcon() {
this.selectedIcon = null;
}
isLibraryDetailsValid(): boolean {
return !!this.libraryName.trim() && !!this.selectedIcon;
}
isDirectorySelectionValid(): boolean {
return this.folders.length > 0;
}
addLibrary() {
const newLibrary = {
name: this.libraryName,
paths: this.folders,
icon: this.selectedIcon ? this.selectedIcon.replace('pi pi-', '') : 'heart'
};
this.libraryService.createLibrary(newLibrary).subscribe({
next: (createdLibrary) => {
this.router.navigate(
['/library', createdLibrary.id, 'books']
);
},
error: (err) => {
console.error('Failed to create library:', err);
}
});
this.dynamicDialogRef.close();
}
validateLibraryNameAndProceed(activateCallback: Function) {
if (this.libraryName.trim()) {
const libraryName = this.libraryName.trim();
this.libraryService.libraryState$
.pipe(take(1))
.subscribe(libraryState => {
const library = libraryState.libraries?.find(library => library.name === libraryName);
if (library) {
this.messageService.add({
severity: 'error',
summary: 'Library Name Exists',
detail: 'This library name is already taken.',
});
} else {
activateCallback(2);
}
});
}
}
}
@@ -0,0 +1,15 @@
<ngx-extended-pdf-viewer
[src]="getSrc()"
[handTool]="handTool"
[height]="'auto'"
[page]="page"
[rotation]="rotation"
[scrollMode]="scrollMode"
[sidebarVisible]="sidebarVisible"
[zoom]="zoom"
[spread]="spread"
(pageChange)="onPageChange($event)"
(zoomChange)="onZoomChange($event)"
(sidebarVisibleChange)="onSidebarVisibleChange($event)"
(spreadChange)="onSpreadChange($event)">
</ngx-extended-pdf-viewer>
@@ -0,0 +1,106 @@
import {Component, NgZone, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {NgxExtendedPdfViewerModule, ScrollModeType} from 'ngx-extended-pdf-viewer';
import {BookService} from '../../service/book.service';
@Component({
selector: 'app-pdf-viewer',
standalone: true,
imports: [NgxExtendedPdfViewerModule],
templateUrl: './pdf-viewer.component.html',
})
export class PdfViewerComponent implements OnInit, OnDestroy {
bookId!: number;
handTool = true;
page = 1;
rotation: 0 | 90 | 180 | 270 = 0;
scrollMode: ScrollModeType = ScrollModeType.page;
sidebarVisible = false;
spread: 'off' | 'even' | 'odd' = 'odd';
src = '';
zoom: number | string = 'page-fit';
private isInitialLoad = true;
constructor(
private bookService: BookService,
private zone: NgZone,
private route: ActivatedRoute
) {}
ngOnInit(): void {
this.route.paramMap.subscribe((params) => {
this.bookId = +params.get('bookId')!;
this.loadBook(this.bookId);
this.updateLastReadTime();
});
}
ngOnDestroy(): void {
this.updateLastReadTime();
}
private loadBook(bookId: number): void {
this.bookService.getBookById(bookId).subscribe((book) => {
this.zone.run(() => {
this.bookService.getBookSetting(bookId).subscribe((bookSetting) => {
const { pageNumber, zoom, sidebar_visible, spread } = bookSetting;
this.page = pageNumber || 1;
this.zoom = zoom || 'page-fit';
this.sidebarVisible = sidebar_visible || false;
this.spread = spread || 'odd';
this.isInitialLoad = false;
});
});
});
}
private updateViewerSetting(): void {
if (this.isInitialLoad) return;
const updatedViewerSetting = {
pageNumber: this.page,
zoom: this.zoom,
sidebar_visible: this.sidebarVisible,
spread: this.spread,
};
this.bookService.updateViewerSetting(updatedViewerSetting, this.bookId).subscribe();
}
private updateLastReadTime(): void {
this.bookService.updateLastReadTime(this.bookId).subscribe();
}
onPageChange(page: number): void {
console.log('page', page);
if (page !== this.page) {
this.page = page;
this.updateViewerSetting();
}
}
onZoomChange(zoom: string | number): void {
console.log('zoom', zoom);
if (zoom !== this.zoom) {
this.zoom = zoom;
this.updateViewerSetting();
}
}
onSidebarVisibleChange(visible: boolean): void {
console.log('sidebarVisible', visible);
if (visible !== this.sidebarVisible) {
this.sidebarVisible = visible;
this.updateViewerSetting();
}
}
onSpreadChange(spread: 'off' | 'even' | 'odd'): void {
if (spread !== this.spread) {
this.spread = spread;
this.updateViewerSetting();
}
}
getSrc(): string {
return this.bookService.getBookDataUrl(this.bookId);
}
}
@@ -0,0 +1,43 @@
<div class="dialog-container">
<div class="checkbox-list">
<div *ngFor="let shelf of (shelfState$ | async)?.shelves" class="flex items-center">
<p-checkbox [inputId]="shelf.name" name="group" [value]="shelf" [(ngModel)]="selectedShelves"></p-checkbox>
<label [for]="shelf.id" class="ml-2">{{ shelf.name }}</label>
</div>
</div>
<div class="bottom-section">
<p-divider></p-divider>
<div class="bottom-container">
<p-button outlined="true" label="Create Shelf" (onClick)="createShelfDialog()"></p-button>
<div>
<p-button class="spacing-right" severity="secondary" label="Cancel" (onClick)="closeDialog()"></p-button>
<p-button label="Save" (onClick)="updateBooksShelves()"></p-button>
</div>
</div>
</div>
<app-icon-picker (iconSelected)="onIconSelected($event)"></app-icon-picker>
<p-dialog [(visible)]="displayShelfDialog" header="Create Shelf" [modal]="true" [draggable]="false" [closable]="true" (onHide)="closeShelfDialog()" [style]="{ width: '400px', height: 'auto' }">
<div class="p-fluid">
<div class="field">
<label for="shelfName">Shelf Name</label>
<input id="shelfName" type="text" pInputText [(ngModel)]="shelfName" />
</div>
<div class="field">
<label>Shelf Icon</label>
<div *ngIf="!selectedIcon">
<p-button label="Select Icon" icon="pi pi-search" (onClick)="openIconPicker()"></p-button>
</div>
<div *ngIf="selectedIcon" class="mt-2 flex items-center">
<i [class]="selectedIcon" class="mr-2"></i>
<p-button label="Remove" icon="pi pi-times" text="true" outlined="true" severity="warn" (onClick)="clearSelectedIcon()"></p-button>
</div>
</div>
</div>
<ng-template pTemplate="footer">
<p-button label="Cancel" severity="secondary" (onClick)="closeShelfDialog()" class="p-button-text"></p-button>
<p-button label="Save" (onClick)="saveNewShelf()"></p-button>
</ng-template>
</p-dialog>
</div>
@@ -0,0 +1,49 @@
.dialog-container {
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100%;
}
.bottom-section {
margin-top: auto;
}
.bottom-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 1rem;
}
p-divider {
margin: 1rem 0;
border-color: var(--text-color-secondary);
}
.spacing-right {
margin-right: 1rem;
}
p-dialog .p-dialog-content {
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 1rem; /* Adds space between elements inside the dialog */
}
p-dialog .p-dialog-footer {
display: flex;
justify-content: flex-end;
}
.dialog-container .checkbox-list {
display: flex;
flex-direction: column;
gap: 1rem; /* Adds gap between each checkbox row */
padding: 1rem;
}
.checkbox-list .flex {
margin-bottom: 0.5rem; /* Optional: adds a smaller gap between each checkbox item */
}
@@ -0,0 +1,129 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog';
import { Book } from '../../model/book.model';
import { MessageService } from 'primeng/api';
import { ShelfService } from '../../service/shelf.service';
import { Observable } from 'rxjs';
import { BookService } from '../../service/book.service';
import { map, tap } from 'rxjs/operators';
import { Shelf } from '../../model/shelf.model';
import { IconPickerComponent } from '../../../utilities/icon-picker/icon-picker.component';
import { ShelfState } from '../../model/state/shelf-state.model';
@Component({
selector: 'app-shelf-assigner',
standalone: false,
templateUrl: './shelf-assigner.component.html',
styleUrls: ['./shelf-assigner.component.scss']
})
export class ShelfAssignerComponent implements OnInit {
shelfState$: Observable<ShelfState>;
book: Book;
selectedShelves: Shelf[] = [];
displayShelfDialog: boolean = false;
shelfName: string = '';
bookIds: Set<number> = new Set();
isMultiBooks: boolean = false;
selectedIcon: string | null = null;
@ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined;
constructor(
private shelfService: ShelfService,
private dynamicDialogConfig: DynamicDialogConfig,
private dynamicDialogRef: DynamicDialogRef,
private messageService: MessageService,
private bookService: BookService
) {
this.shelfState$ = this.shelfService.shelfState$;
this.book = this.dynamicDialogConfig.data.book;
this.bookIds = this.dynamicDialogConfig.data.bookIds;
this.isMultiBooks = this.dynamicDialogConfig.data.isMultiBooks;
}
ngOnInit(): void {
if (!this.isMultiBooks && this.book.shelves) {
this.shelfState$.pipe(
map(state => state.shelves || []),
tap(shelves => {
this.selectedShelves = shelves.filter(shelf =>
this.book.shelves?.some(bShelf => bShelf.id === shelf.id)
);
})
).subscribe();
}
}
saveNewShelf(): void {
const newShelf: Partial<Shelf> = {
name: this.shelfName,
icon: this.selectedIcon ? this.selectedIcon.replace('pi pi-', '') : 'heart'
};
this.shelfService.createShelf(newShelf as Shelf).subscribe(
() => {
this.messageService.add({ severity: 'info', summary: 'Success', detail: `Shelf created: ${this.shelfName}` });
this.displayShelfDialog = false;
},
error => {
this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Failed to create shelf' });
console.error('Error creating shelf:', error);
}
);
}
updateBooksShelves(): void {
const idsToAssign: Set<number | undefined> = new Set(this.selectedShelves.map(shelf => shelf.id));
const idsToUnassign: Set<number> = this.isMultiBooks ? new Set() : this.getIdsToUnAssign(this.book, idsToAssign);
const bookIds = this.isMultiBooks ? this.bookIds : new Set([this.book.id]);
this.updateBookShelves(bookIds, idsToAssign, idsToUnassign);
}
private updateBookShelves(bookIds: Set<number>, idsToAssign: Set<number | undefined>, idsToUnassign: Set<number>): void {
this.bookService.updateBookShelves(bookIds, idsToAssign, idsToUnassign).subscribe(
() => {
this.messageService.add({ severity: 'info', summary: 'Success', detail: 'Book shelves updated' });
this.dynamicDialogRef.close();
},
error => {
this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Failed to update book shelves' });
this.dynamicDialogRef.close();
}
);
}
private getIdsToUnAssign(book: Book, idsToAssign: Set<number | undefined>): Set<number> {
const idsToUnassign = new Set<number>();
book.shelves?.forEach(shelf => {
if (!idsToAssign.has(shelf.id)) {
idsToUnassign.add(shelf.id!);
}
});
return idsToUnassign;
}
createShelfDialog(): void {
this.displayShelfDialog = true;
}
closeShelfDialog(): void {
this.displayShelfDialog = false;
}
closeDialog(): void {
this.dynamicDialogRef.close();
}
openIconPicker() {
if (this.iconPicker) {
this.iconPicker.open();
}
}
clearSelectedIcon() {
this.selectedIcon = null;
}
onIconSelected(icon: string) {
this.selectedIcon = icon;
}
}