Instead of Entity[] use EntityState

This commit is contained in:
aditya.chandel
2024-12-28 23:06:54 -07:00
parent da153d6c04
commit a5e321319a
17 changed files with 398 additions and 251 deletions
@@ -22,7 +22,7 @@
</div>
<div class="virtual-scroller-container">
<div class="book-card-container" *ngIf="books$ | async as books">
<div class="book-card-container" *ngIf="(bookState$ | async)?.books as books">
<virtual-scroller *ngIf="books.length > 0" class="virtual-scroller" #scroll [items]="books">
<div class="grid" #container>
<div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems">
@@ -5,7 +5,6 @@ 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 {Book} from '../../model/book.model';
import {ShelfService} from '../../service/shelf.service';
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
@@ -14,6 +13,7 @@ import {Shelf} from '../../model/shelf.model';
import {SortService} from '../../service/sort.service';
import {SortOptionsHelper} from '../../service/sort-options.helper';
import {SortOption} from '../../model/sort.model';
import {BookState} from '../../model/state/book-state.model';
@Component({
selector: 'app-books-browser',
@@ -22,7 +22,7 @@ import {SortOption} from '../../model/sort.model';
styleUrls: ['./books-browser.component.scss']
})
export class BooksBrowserComponent implements OnInit {
books$: Observable<Book[]> | undefined;
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | null> | undefined;
entityType$: Observable<string | null> | undefined;
bookTitle$ = new BehaviorSubject<string>('');
@@ -38,7 +38,6 @@ export class BooksBrowserComponent implements OnInit {
isDrawerVisible: boolean = false;
ref: DynamicDialogRef | undefined;
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
@@ -56,7 +55,7 @@ export class BooksBrowserComponent implements OnInit {
this.sortOptions = SortOptionsHelper.generateSortOptions();
const routeParam$ = this.getRouteParams();
this.books$ = routeParam$.pipe(
this.bookState$ = routeParam$.pipe(
switchMap(({libraryId, shelfId}) => this.fetchBooks(libraryId, shelfId)),
);
@@ -91,13 +90,17 @@ export class BooksBrowserComponent implements OnInit {
);
}
private fetchBooks(libraryId: number, shelfId: number): Observable<Book[]> {
private fetchBooks(libraryId: number, shelfId: number): Observable<BookState> {
if (libraryId) {
return this.fetchBooksByLibrary(libraryId);
} else if (shelfId) {
return this.fetchBooksByShelf(shelfId);
}
return of([]);
return of({
books: [],
loaded: false,
error: null
});
}
private fetchEntity(libraryId: number, shelfId: number): Observable<Library | Shelf | null> {
@@ -113,45 +116,89 @@ export class BooksBrowserComponent implements OnInit {
return of(null);
}
private fetchBooksByLibrary(libraryId: number): Observable<Book[]> {
return this.bookService.books$.pipe(
map(books => books.filter(book => book.libraryId === libraryId)),
map(books => this.sortService.applySort(books, this.selectedSort)),
switchMap(books => this.bookTitle$.pipe(
map(title => {
if (title && title.trim() !== '') {
return books.filter(book => book.metadata?.title?.toLowerCase().includes(title.toLowerCase()));
}
return books;
})
))
private fetchBooksByLibrary(libraryId: number): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.books) {
const filteredBooks = bookState.books.filter(book => book.libraryId === libraryId);
return this.sortService.applySort(filteredBooks, this.selectedSort);
} else {
return [];
}
}),
switchMap(books =>
this.bookTitle$.pipe(
map(title => {
if (title && title.trim() !== '') {
return books.filter(book => book.metadata?.title?.toLowerCase().includes(title.toLowerCase()));
}
return books;
})
)
),
map(filteredBooks => {
return {
books: filteredBooks,
loaded: true,
error: null
} as BookState;
})
);
}
private fetchBooksByShelf(shelfId: number): Observable<Book[]> {
return this.bookService.books$.pipe(
map(books => books.filter(book => book.shelves?.some(shelf => shelf.id === shelfId))),
map(books => this.sortService.applySort(books, this.selectedSort)),
switchMap(books => this.bookTitle$.pipe(
map(title => {
if (title && title.trim() !== '') {
return books.filter(book => book.metadata?.title?.toLowerCase().includes(title.toLowerCase()));
}
return books;
})
))
private fetchBooksByShelf(shelfId: number): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
if (bookState.books) {
const filteredBooks = bookState.books.filter(book =>
book.shelves?.some(shelf => shelf.id === shelfId)
);
return this.sortService.applySort(filteredBooks, this.selectedSort);
} else {
return [];
}
}),
switchMap(books =>
this.bookTitle$.pipe(
map(title => {
if (title && title.trim() !== '') {
return books.filter(book =>
book.metadata?.title?.toLowerCase().includes(title.toLowerCase())
);
}
return books;
})
)
),
map(filteredBooks => {
return {
books: filteredBooks,
loaded: true,
error: null
} as BookState;
})
);
}
private fetchLibrary(libraryId: number): Observable<Library | null> {
return this.libraryService.libraries$.pipe(
map(libraries => libraries.find(lib => lib.id === libraryId) || 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.shelves$.pipe(
map(shelves => shelves.find(shelf => shelf.id === shelfId) || null)
return this.shelfService.shelfState$.pipe(
map(shelfState => {
if (shelfState.shelves) {
return shelfState.shelves.find(shelf => shelf.id === shelfId) || null;
}
return null;
})
);
}
@@ -186,7 +233,7 @@ export class BooksBrowserComponent implements OnInit {
updateSortOption(sortOption: SortOption): void {
this.selectedSort = sortOption;
const routeParam$ = this.getRouteParams();
this.books$ = routeParam$.pipe(
this.bookState$ = routeParam$.pipe(
switchMap(({libraryId, shelfId}) => this.fetchBooks(libraryId, shelfId))
);
if (this.entityType === 'Library') {
@@ -255,7 +302,7 @@ export class BooksBrowserComponent implements OnInit {
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'none',
rejectIcon: 'none',
rejectButtonStyleClass: 'p-button-text',
acceptButtonStyleClass: 'p-button-text',
accept: () => {
this.libraryService.deleteLibrary(this.entity?.id!).subscribe({
complete: () => {
@@ -285,7 +332,7 @@ export class BooksBrowserComponent implements OnInit {
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'none',
rejectIcon: 'none',
rejectButtonStyleClass: 'p-button-text',
acceptButtonStyleClass: 'p-button-text',
accept: () => {
this.libraryService.refreshLibrary(this.entity?.id!).subscribe({
complete: () => {
@@ -328,7 +375,7 @@ export class BooksBrowserComponent implements OnInit {
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'none',
rejectIcon: 'none',
rejectButtonStyleClass: 'p-button-text',
acceptButtonStyleClass: 'p-button-text',
accept: () => {
this.shelfService.deleteShelf(this.entity?.id!).subscribe({
complete: () => {
@@ -352,5 +399,4 @@ export class BooksBrowserComponent implements OnInit {
},
];
}
}
@@ -1,6 +1,6 @@
<div class="dashboard-scroller-container">
<h2 class="dashboard-scroller-title">{{ title }}</h2>
<div *ngIf="(books$ | async)?.length === 0">
<div *ngIf="(bookState$ | async)?.books?.length === 0">
<h4>No books available.</h4>
</div>
<div class="infinite-scroller"
@@ -9,7 +9,7 @@
[infiniteScrollThrottle]="50"
#scrollContainer
[horizontal]="true">
<div class="infinite-scroller-a-book" *ngFor="let book of books$ | async">
<div class="infinite-scroller-a-book" *ngFor="let book of (bookState$ | async)?.books">
<app-book-card [book]="book" [isCheckboxEnabled]="false"></app-book-card>
</div>
</div>
@@ -1,11 +1,11 @@
import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
import {Book} from '../../model/book.model';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {AsyncPipe, NgForOf, NgIf} from '@angular/common';
import {BookCardComponent} from '../book-card/book-card.component';
import {Observable} from 'rxjs';
import {BookService} from '../../service/book.service';
import {map} from 'rxjs/operators';
import { Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BookService } from '../../service/book.service';
import { BookState } from '../../model/state/book-state.model';
import { BookCardComponent } from '../book-card/book-card.component';
import { InfiniteScrollDirective } from 'ngx-infinite-scroll';
import { AsyncPipe, NgForOf, NgIf } from '@angular/common';
@Component({
selector: 'app-dashboard-scroller',
@@ -25,31 +25,33 @@ export class DashboardScrollerComponent implements OnInit {
@Input() title: string = 'Last Read Books';
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
books$: Observable<Book[]> | undefined;
bookState$: Observable<BookState> | undefined;
constructor(private bookService: BookService) {
}
constructor(private bookService: BookService) {}
ngOnInit(): void {
if (this.bookListType === 'lastRead') {
this.books$ = this.bookService.books$.pipe((
map(books =>
books
.filter(book => book.lastReadTime)
.sort((a, b) => new Date(b.lastReadTime!).getTime() - new Date(a.lastReadTime!).getTime())
.slice(0, 25)
)
))
this.bookState$ = this.bookService.bookState$.pipe(
map((state: BookState) => ({
...state,
books: (state.books || [])
.filter(book => book.lastReadTime)
.sort((a, b) => new Date(b.lastReadTime!).getTime() - new Date(a.lastReadTime!).getTime())
.slice(0, 25)
}))
);
}
if (this.bookListType === 'latestAdded') {
this.books$ = this.bookService.books$.pipe((
map(books =>
books
this.bookState$ = this.bookService.bookState$.pipe(
map((state: BookState) => ({
...state,
books: (state.books || [])
.filter(book => book.addedOn)
.sort((a, b) => new Date(b.addedOn!).getTime() - new Date(a.addedOn!).getTime())
.slice(0, 25)
)
))
}))
);
}
}
}
@@ -1,12 +1,12 @@
import {Component} from '@angular/core';
import {Button} from 'primeng/button';
import {AsyncPipe, NgIf} from '@angular/common';
import {LibraryCreatorComponent} from '../library-creator/library-creator.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
import {LibraryService} from '../../service/library.service';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import { Component } from '@angular/core';
import { Button } from 'primeng/button';
import { AsyncPipe, NgIf } from '@angular/common';
import { LibraryCreatorComponent } from '../library-creator/library-creator.component';
import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
import { DashboardScrollerComponent } from '../dashboard-scroller/dashboard-scroller.component';
import { LibraryService } from '../../service/library.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
selector: 'app-home-page',
@@ -25,8 +25,8 @@ export class DashboardComponent {
ref: DynamicDialogRef | undefined;
constructor(private libraryService: LibraryService, public dialogService: DialogService) {
this.isLibrariesEmpty$ = this.libraryService.libraries$.pipe(
map(libraries => libraries.length === 0)
this.isLibrariesEmpty$ = this.libraryService.libraryState$.pipe(
map(state => !state.libraries || state.libraries.length === 0)
);
}
@@ -36,7 +36,7 @@ export class DashboardComponent {
modal: true,
width: '50%',
height: '50%',
style: {bottom: '15%'}
style: { bottom: '15%' }
});
}
}
@@ -2,7 +2,7 @@
<div class="flex">
<p-dropdown
[options]="(libraries$ | async) || []"
[options]="(libraryState$ | async)?.libraries || []"
optionLabel="name"
placeholder="Select Library"
[(ngModel)]="selectedLibrary">
@@ -9,6 +9,7 @@ import {ToastService} from '../../service/toast.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {LibraryService} from '../../service/library.service';
import {Observable} from 'rxjs';
import {LibraryState} from '../../model/state/library-state.model';
@Component({
selector: 'app-file-upload-v2',
@@ -23,7 +24,7 @@ import {Observable} from 'rxjs';
],
})
export class FileUploadComponent {
libraries$: Observable<Library[]>;
libraryState$: Observable<LibraryState>;
selectedLibrary: Library | null = null;
selectedPath: string = '';
selectedFileName: string = '';
@@ -35,7 +36,7 @@ export class FileUploadComponent {
private fileUploadService: FileUploadService,
private toastService: ToastService,
private dynamicDialogRef: DynamicDialogRef) {
this.libraries$ = this.libraryService.libraries$;
this.libraryState$ = this.libraryService.libraryState$;
}
triggerFileInput(fileInput: HTMLInputElement): void {
@@ -1,11 +1,11 @@
import {Component, computed, OnInit} from '@angular/core';
import {AppMenuitemComponent} from './app.menuitem.component';
import {AsyncPipe, NgForOf, NgIf} from '@angular/common';
import {MenuModule} from 'primeng/menu';
import {LibraryService} from '../../service/library.service';
import {async, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {ShelfService} from '../../service/shelf.service';
import { Component, OnInit } from '@angular/core';
import { AppMenuitemComponent } from './app.menuitem.component';
import { AsyncPipe, NgForOf, NgIf } from '@angular/common';
import { MenuModule } from 'primeng/menu';
import { LibraryService } from '../../service/library.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ShelfService } from '../../service/shelf.service';
@Component({
selector: 'app-menu',
@@ -17,36 +17,35 @@ export class AppMenuComponent implements OnInit {
libraryMenu$: Observable<any> | undefined;
shelfMenu$: Observable<any> | undefined;
constructor(private libraryService: LibraryService, private shelfService: ShelfService) {
}
constructor(private libraryService: LibraryService, private shelfService: ShelfService) {}
ngOnInit() {
this.libraryMenu$ = this.libraryService.libraries$.pipe(
map((libraries) => [
ngOnInit(): void {
this.libraryMenu$ = this.libraryService.libraryState$.pipe(
map((state) => [
{
label: 'Library',
separator: false,
items: libraries.map((library) => ({
items: state.libraries?.map((library) => ({
label: library.name,
icon: 'pi pi-' + library.icon,
routerLink: [`/library/${library.id}/books`],
bookCount$: this.libraryService.getBookCount(library.id ?? 0),
})),
})) || [],
},
])
);
this.shelfMenu$ = this.shelfService.shelves$.pipe(
map((shelves) => [
this.shelfMenu$ = this.shelfService.shelfState$.pipe(
map((state) => [
{
label: 'Shelves',
separator: false,
items: shelves.map((shelf) => ({
items: state.shelves?.map((shelf) => ({
label: shelf.name,
icon: 'pi pi-' + shelf.icon,
routerLink: [`/shelf/${shelf.id}/books`],
bookCount$: this.shelfService.getBookCount(shelf.id ?? 0),
})),
})) || [],
},
])
);
@@ -54,15 +53,14 @@ export class AppMenuComponent implements OnInit {
this.populateHome();
}
populateHome() {
populateHome(): void {
this.home = [
{
label: 'Home',
items: [
{label: 'Dashboard', icon: 'pi pi-fw pi-home', routerLink: ['/']}
{ label: 'Dashboard', icon: 'pi pi-fw pi-home', routerLink: ['/'] },
],
},
];
}
}
@@ -1,12 +1,11 @@
<div class="dialog-container">
<div class="checkbox-list">
<div *ngFor="let shelf of shelves$ | async" class="flex items-center">
<p-checkbox [inputId]="shelf.name" name="group" [value]="shelf" [(ngModel)]="selectedShelves"/>
<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>
<!-- Divider and Bottom Section -->
<div class="bottom-section">
<p-divider></p-divider>
<div class="bottom-container">
@@ -17,12 +16,13 @@
</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"/>
<input id="shelfName" type="text" pInputText [(ngModel)]="shelfName" />
</div>
<div class="field">
<label>Shelf Icon</label>
@@ -31,7 +31,7 @@
</div>
<div *ngIf="selectedIcon" class="mt-2 flex align-items-center">
<i [class]="selectedIcon" class="mr-2"></i>
<p-button label="Remove" icon="pi pi-times" [text]="true" [outlined]="true" severity="warning" (onClick)="clearSelectedIcon()"></p-button>
<p-button label="Remove" icon="pi pi-times" text="true" outlined="true" severity="warning" (onClick)="clearSelectedIcon()"></p-button>
</div>
</div>
</div>
@@ -1,13 +1,14 @@
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 '../icon-picker/icon-picker.component';
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 '../icon-picker/icon-picker.component';
import { ShelfState } from '../../model/state/shelf-state.model';
@Component({
selector: 'app-shelf-assigner',
@@ -16,7 +17,7 @@ import {IconPickerComponent} from '../icon-picker/icon-picker.component';
styleUrls: ['./shelf-assigner.component.scss']
})
export class ShelfAssignerComponent implements OnInit {
shelves$: Observable<Shelf[]>;
shelfState$: Observable<ShelfState>;
book: Book;
selectedShelves: Shelf[] = [];
displayShelfDialog: boolean = false;
@@ -24,6 +25,7 @@ export class ShelfAssignerComponent implements OnInit {
bookIds: Set<number> = new Set();
isMultiBooks: boolean = false;
selectedIcon: string | null = null;
@ViewChild(IconPickerComponent) iconPicker: IconPickerComponent | undefined;
constructor(
@@ -33,33 +35,37 @@ export class ShelfAssignerComponent implements OnInit {
private messageService: MessageService,
private bookService: BookService
) {
this.shelves$ = this.shelfService.shelves$;
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.shelves$.pipe(
map(shelves => shelves.filter(shelf => this.book.shelves?.some(bShelf => bShelf.id === shelf.id))),
tap(selectedShelves => this.selectedShelves = selectedShelves)
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 = {
const newShelf: Partial<Shelf> = {
name: this.shelfName,
icon: this.selectedIcon ? this.selectedIcon.replace('pi pi-', '') : 'heart'
};
this.shelfService.createShelf(newShelf).subscribe(
this.shelfService.createShelf(newShelf as Shelf).subscribe(
() => {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Shelf created: ' + this.shelfName});
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'});
this.messageService.add({ severity: 'error', summary: 'Error', detail: 'Failed to create shelf' });
console.error('Error creating shelf:', error);
}
);
@@ -75,11 +81,11 @@ export class ShelfAssignerComponent implements OnInit {
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.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.messageService.add({ severity: 'error', summary: 'Error', detail: 'Failed to update book shelves' });
this.dynamicDialogRef.close();
}
);
@@ -88,7 +94,7 @@ export class ShelfAssignerComponent implements OnInit {
private getIdsToUnAssign(book: Book, idsToAssign: Set<number | undefined>): Set<number> {
const idsToUnassign = new Set<number>();
book.shelves?.forEach(shelf => {
if (!idsToAssign.has(shelf.id!)) {
if (!idsToAssign.has(shelf.id)) {
idsToUnassign.add(shelf.id!);
}
});
@@ -120,5 +126,4 @@ export class ShelfAssignerComponent implements OnInit {
onIconSelected(icon: string) {
this.selectedIcon = icon;
}
}