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)';
}
}
}