Improve Angular project structure and code organization (#1328)
This commit is contained in:
+129
@@ -0,0 +1,129 @@
|
||||
<div class="flex flex-col gap-6 p-4 items-center justify-center w-full max-w-[700px]">
|
||||
<!-- Book Information -->
|
||||
<div class="w-full text-center">
|
||||
<h3 class="text-lg font-semibold mb-2">{{ book.metadata?.title || 'Unknown Title' }}</h3>
|
||||
<p class="text-sm text-gray-600">{{ book.filePath }}</p>
|
||||
</div>
|
||||
|
||||
<!-- File Type Selection -->
|
||||
<p-select
|
||||
[options]="fileTypeOptions"
|
||||
[(ngModel)]="fileType"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Select file type"
|
||||
class="w-full"
|
||||
[disabled]="isUploading"
|
||||
></p-select>
|
||||
|
||||
<!-- Description Field -->
|
||||
<div class="w-full">
|
||||
<label for="description" class="block text-sm font-medium mb-2">Description (Optional)</label>
|
||||
<p-textarea
|
||||
[(ngModel)]="description"
|
||||
rows="3"
|
||||
placeholder="Add a description for this file..."
|
||||
class="w-full"
|
||||
[disabled]="isUploading"
|
||||
></p-textarea>
|
||||
</div>
|
||||
|
||||
<!-- File Upload -->
|
||||
<p-fileupload class="w-full" name="file"
|
||||
[maxFileSize]="maxFileSizeBytes"
|
||||
[customUpload]="true"
|
||||
[multiple]="false"
|
||||
(onSelect)="onFilesSelect($event)"
|
||||
(uploadHandler)="uploadFiles($event)"
|
||||
[disabled]="isUploading">
|
||||
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
|
||||
<div class="flex flex-wrap items-center justify-center flex-1 gap-4">
|
||||
<div class="flex gap-4">
|
||||
<p-button (onClick)="choose($event, chooseCallback)"
|
||||
icon="pi pi-images"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
[disabled]="isChooseDisabled()"/>
|
||||
<p-button (onClick)="uploadEvent(uploadCallback)"
|
||||
icon="pi pi-cloud-upload"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
[disabled]="isUploadDisabled()"/>
|
||||
<p-button (onClick)="onClear(clearCallback)"
|
||||
icon="pi pi-times"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
severity="danger"
|
||||
[disabled]="!filesPresent() || isUploading"/>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
<ng-template #content let-files let-removeFileCallback="removeFileCallback">
|
||||
<div class="flex flex-col gap-8 px-4">
|
||||
@if (files?.length > 0) {
|
||||
<div>
|
||||
<div class="max-h-96 max-w-[22rem] md:max-w-none overflow-y-auto pr-2">
|
||||
<div class="flex flex-wrap">
|
||||
@for (uploadFile of this.files; track uploadFile; let i = $index) {
|
||||
<div class="flex justify-between items-center w-full gap-4">
|
||||
<div class="flex items-center gap-4 overflow-hidden flex-1">
|
||||
<p-badge [value]="uploadFile.status" [severity]="getBadgeSeverity(uploadFile.status)" class="shrink-0"/>
|
||||
<span class="font-semibold text-ellipsis whitespace-nowrap overflow-hidden flex-1">
|
||||
{{ uploadFile.file.name }}
|
||||
</span>
|
||||
<div class="shrink-0">{{ formatSize(uploadFile.file.size) }}</div>
|
||||
</div>
|
||||
@switch (uploadFile.status) {
|
||||
@case ('Pending') {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
(click)="onRemoveTemplatingFile($event, uploadFile.file, removeFileCallback, i)"
|
||||
severity="danger"
|
||||
[text]="true"/>
|
||||
}
|
||||
@case ('Uploading') {
|
||||
<i
|
||||
class="pi pi-spin pi-spinner p-3"
|
||||
style="color: slateblue"
|
||||
pTooltip="Uploading"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
}
|
||||
@case ('Uploaded') {
|
||||
<i
|
||||
class="pi pi-check p-3"
|
||||
style="color: green"
|
||||
pTooltip="Uploaded"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
}
|
||||
@case ('Failed') {
|
||||
<i
|
||||
class="pi pi-exclamation-triangle p-3"
|
||||
style="color: darkred"
|
||||
pTooltip="{{ uploadFile.errorMessage || 'Upload failed' }}"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
<ng-template #file></ng-template>
|
||||
<ng-template #empty>
|
||||
<div class="flex items-center justify-center flex-col text-center">
|
||||
<i class="pi pi-cloud-upload !border-2 !rounded-full !p-8 !text-4xl !text-muted-color"></i>
|
||||
<p class="mt-6 mb-2">Drag and drop a file here to upload.</p>
|
||||
<p class="mt-2 mb-2">
|
||||
Upload an additional file for <strong>{{ book.metadata?.title || 'this book' }}</strong>.
|
||||
</p>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-fileupload>
|
||||
</div>
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
:host ::ng-deep .p-fileupload-content p-progressbar {
|
||||
display: none !important;
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
|
||||
import { Select } from 'primeng/select';
|
||||
import { Button } from 'primeng/button';
|
||||
import { FileSelectEvent, FileUpload, FileUploadHandlerEvent } from 'primeng/fileupload';
|
||||
import { Badge } from 'primeng/badge';
|
||||
import { Tooltip } from 'primeng/tooltip';
|
||||
import { Subject, takeUntil } from 'rxjs';
|
||||
import { BookService } from '../../service/book.service';
|
||||
import { AppSettingsService } from '../../../../shared/service/app-settings.service';
|
||||
import { Book, AdditionalFileType } from '../../model/book.model';
|
||||
import { MessageService } from 'primeng/api';
|
||||
import { filter, take } from 'rxjs/operators';
|
||||
|
||||
interface FileTypeOption {
|
||||
label: string;
|
||||
value: AdditionalFileType;
|
||||
}
|
||||
|
||||
interface UploadingFile {
|
||||
file: File;
|
||||
status: 'Pending' | 'Uploading' | 'Uploaded' | 'Failed';
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-additional-file-uploader',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
Select,
|
||||
Button,
|
||||
FileUpload,
|
||||
Badge,
|
||||
Tooltip
|
||||
],
|
||||
templateUrl: './additional-file-uploader.component.html',
|
||||
styleUrls: ['./additional-file-uploader.component.scss']
|
||||
})
|
||||
export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
|
||||
book!: Book;
|
||||
files: UploadingFile[] = [];
|
||||
fileType: AdditionalFileType = AdditionalFileType.ALTERNATIVE_FORMAT;
|
||||
description: string = '';
|
||||
isUploading = false;
|
||||
maxFileSizeBytes?: number;
|
||||
|
||||
fileTypeOptions: FileTypeOption[] = [
|
||||
{ label: 'Alternative Format', value: AdditionalFileType.ALTERNATIVE_FORMAT },
|
||||
{ label: 'Supplementary File', value: AdditionalFileType.SUPPLEMENTARY }
|
||||
];
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
constructor(
|
||||
private dialogRef: DynamicDialogRef,
|
||||
private config: DynamicDialogConfig,
|
||||
private bookService: BookService,
|
||||
private appSettingsService: AppSettingsService,
|
||||
private messageService: MessageService,
|
||||
private cdr: ChangeDetectorRef
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.book = this.config.data.book;
|
||||
this.appSettingsService.appSettings$
|
||||
.pipe(
|
||||
filter(settings => settings != null),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(settings => {
|
||||
if (settings) {
|
||||
this.maxFileSizeBytes = (settings.maxFileUploadSizeInMb || 100) * 1024 * 1024;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
hasPendingFiles(): boolean {
|
||||
return this.files.some(f => f.status === 'Pending');
|
||||
}
|
||||
|
||||
filesPresent(): boolean {
|
||||
return this.files.length > 0;
|
||||
}
|
||||
|
||||
choose(_event: any, chooseCallback: () => void): void {
|
||||
chooseCallback();
|
||||
}
|
||||
|
||||
onClear(clearCallback: () => void): void {
|
||||
clearCallback();
|
||||
this.files = [];
|
||||
}
|
||||
|
||||
onFilesSelect(event: FileSelectEvent): void {
|
||||
const newFiles = event.currentFiles;
|
||||
// Only take the first file for single file upload
|
||||
if (newFiles.length > 0) {
|
||||
const file = newFiles[0];
|
||||
this.files = [{
|
||||
file,
|
||||
status: 'Pending'
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
onRemoveTemplatingFile(_event: any, _file: File, removeFileCallback: (event: any, index: number) => void, index: number): void {
|
||||
removeFileCallback(_event, index);
|
||||
}
|
||||
|
||||
uploadEvent(uploadCallback: () => void): void {
|
||||
uploadCallback();
|
||||
}
|
||||
|
||||
uploadFiles(event: FileUploadHandlerEvent): void {
|
||||
const filesToUpload = this.files.filter(f => f.status === 'Pending');
|
||||
|
||||
if (filesToUpload.length === 0) return;
|
||||
|
||||
this.isUploading = true;
|
||||
let pending = filesToUpload.length;
|
||||
|
||||
for (const uploadFile of filesToUpload) {
|
||||
uploadFile.status = 'Uploading';
|
||||
|
||||
this.bookService.uploadAdditionalFile(
|
||||
this.book.id,
|
||||
uploadFile.file,
|
||||
this.fileType,
|
||||
this.description || undefined
|
||||
).subscribe({
|
||||
next: () => {
|
||||
uploadFile.status = 'Uploaded';
|
||||
if (--pending === 0) {
|
||||
this.isUploading = false;
|
||||
this.dialogRef.close({ success: true });
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
uploadFile.status = 'Failed';
|
||||
uploadFile.errorMessage = err?.error?.message || 'Upload failed due to unknown error.';
|
||||
console.error('Upload failed for', uploadFile.file.name, err);
|
||||
if (--pending === 0) {
|
||||
this.isUploading = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
isChooseDisabled(): boolean {
|
||||
return this.isUploading;
|
||||
}
|
||||
|
||||
isUploadDisabled(): boolean {
|
||||
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles();
|
||||
}
|
||||
|
||||
formatSize(bytes: number): string {
|
||||
const k = 1024;
|
||||
const dm = 2;
|
||||
if (bytes < k) return `${bytes} B`;
|
||||
if (bytes < k * k) return `${(bytes / k).toFixed(dm)} KB`;
|
||||
return `${(bytes / (k * k)).toFixed(dm)} MB`;
|
||||
}
|
||||
|
||||
getBadgeSeverity(status: UploadingFile['status']): 'info' | 'warn' | 'success' | 'danger' {
|
||||
switch (status) {
|
||||
case 'Pending':
|
||||
return 'warn';
|
||||
case 'Uploading':
|
||||
return 'info';
|
||||
case 'Uploaded':
|
||||
return 'success';
|
||||
case 'Failed':
|
||||
return 'danger';
|
||||
default:
|
||||
return 'info';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {ShelfAssignerComponent} from '../shelf-assigner/shelf-assigner.component';
|
||||
import {LockUnlockMetadataDialogComponent} from './lock-unlock-metadata-dialog/lock-unlock-metadata-dialog.component';
|
||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {BulkMetadataUpdateComponent} from '../../../metadata/component/bulk-metadata-update-component/bulk-metadata-update-component';
|
||||
import {MultiBookMetadataEditorComponent} from '../../../metadata/component/multi-book-metadata-editor-component/multi-book-metadata-editor-component';
|
||||
import {MultiBookMetadataFetchComponent} from '../../../metadata/component/multi-book-metadata-fetch-component/multi-book-metadata-fetch-component';
|
||||
import {FileMoverComponent} from '../../../../shared/components/file-mover/file-mover-component';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookDialogHelperService {
|
||||
|
||||
private dialogService = inject(DialogService);
|
||||
|
||||
openShelfAssigner(bookIds: Set<number>): DynamicDialogRef {
|
||||
return this.dialogService.open(ShelfAssignerComponent, {
|
||||
header: `Update Books' Shelves`,
|
||||
modal: true,
|
||||
closable: true,
|
||||
contentStyle: {overflow: 'auto'},
|
||||
baseZIndex: 10,
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
},
|
||||
data: {
|
||||
isMultiBooks: true,
|
||||
bookIds,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openLockUnlockMetadataDialog(bookIds: Set<number>): DynamicDialogRef {
|
||||
const count = bookIds.size;
|
||||
return this.dialogService.open(LockUnlockMetadataDialogComponent, {
|
||||
header: `Lock or Unlock Metadata for ${count} Selected Book${count > 1 ? 's' : ''}`,
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openMetadataRefreshDialog(bookIds: Set<number>): DynamicDialogRef {
|
||||
return this.dialogService.open(MultiBookMetadataFetchComponent, {
|
||||
header: 'Metadata Refresh Options',
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookIds: Array.from(bookIds),
|
||||
metadataRefreshType: MetadataRefreshType.BOOKS,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openBulkMetadataEditDialog(bookIds: Set<number>): DynamicDialogRef {
|
||||
return this.dialogService.open(BulkMetadataUpdateComponent, {
|
||||
header: 'Bulk Edit Metadata',
|
||||
modal: true,
|
||||
closable: true,
|
||||
style: {
|
||||
width: '90vw',
|
||||
maxWidth: '1200px',
|
||||
position: 'absolute'
|
||||
},
|
||||
data: {
|
||||
bookIds: Array.from(bookIds)
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openMultibookMetadataEditorDialog(bookIds: Set<number>): DynamicDialogRef {
|
||||
return this.dialogService.open(MultiBookMetadataEditorComponent, {
|
||||
header: 'Bulk Edit Metadata',
|
||||
showHeader: false,
|
||||
modal: true,
|
||||
closable: true,
|
||||
closeOnEscape: true,
|
||||
dismissableMask: true,
|
||||
style: {
|
||||
width: '95vw',
|
||||
overflow: 'none',
|
||||
},
|
||||
data: {
|
||||
bookIds: Array.from(bookIds)
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openFileMoverDialog(selectedBooks: Set<number>) {
|
||||
const count = selectedBooks.size;
|
||||
return this.dialogService.open(FileMoverComponent, {
|
||||
header: `Organize Book Files (${count} book${count !== 1 ? 's' : ''})`,
|
||||
showHeader: true,
|
||||
maximizable: true,
|
||||
modal: true,
|
||||
closable: true,
|
||||
closeOnEscape: false,
|
||||
dismissableMask: false,
|
||||
style: {
|
||||
width: '85vw',
|
||||
height: '80vh',
|
||||
maxHeight: '95vh',
|
||||
maxWidth: '97.5vw'
|
||||
},
|
||||
data: {
|
||||
bookIds: selectedBooks
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
<div class="relative flex flex-row">
|
||||
<div class="flex flex-col w-full">
|
||||
|
||||
<div class="flex items-center justify-between w-full gap-4 py-2 px-2 md:px-4 rounded-t-xl md:mb-4 mb-2 bg-[var(--card-background)]">
|
||||
<div class="flex items-center min-w-0 max-w-full flex-shrink">
|
||||
@if (entityType$ | async; as entityType) {
|
||||
<p class="text-xl whitespace-nowrap overflow-hidden text-ellipsis w-full">
|
||||
@if (entityType === EntityType.ALL_BOOKS) {
|
||||
@if (currentFilterLabel && rawFilterParamFromUrl) {
|
||||
{{ currentFilterLabel }}
|
||||
} @else if (hasSidebarFilters || hasSearchTerm) {
|
||||
All Books (Filtered)
|
||||
} @else {
|
||||
All Books
|
||||
}
|
||||
} @else if (entityType === EntityType.UNSHELVED) {
|
||||
{{ (hasSidebarFilters || hasSearchTerm) ? 'Unshelved Books (Filtered)' : 'Unshelved Books' }}
|
||||
} @else {
|
||||
{{ entityType }}: {{ (entity$ | async)?.name }}{{ (hasSidebarFilters || hasSearchTerm) ? ' (Filtered)' : '' }}
|
||||
}
|
||||
</p>
|
||||
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
|
||||
(userState.user!.permissions.admin || userState.user!.permissions.canManipulateLibrary)) {
|
||||
<div class="ml-2 flex-shrink-0">
|
||||
<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>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-4 flex-shrink-0">
|
||||
<div class="flex flex-wrap items-center gap-4 md:gap-6">
|
||||
@if (isFilterActive) {
|
||||
<a class="topbar-items topbar-item" (click)="clearFilter()">
|
||||
<i
|
||||
class="pi pi-filter-slash"
|
||||
pTooltip="Clear applied filters"
|
||||
tooltipPosition="top"
|
||||
style="color: orange;">
|
||||
</i>
|
||||
</a>
|
||||
}
|
||||
|
||||
@if (currentViewMode === 'table') {
|
||||
<div>
|
||||
<a class="topbar-items topbar-item" (click)="columnPopover.toggle($event)">
|
||||
<i
|
||||
class="pi pi-eye"
|
||||
pTooltip="Visible columns"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
<p-popover #columnPopover [dismissable]="true" appendTo="body">
|
||||
<div class="w-[200px]">
|
||||
<p-multiSelect
|
||||
optionLabel="header"
|
||||
[options]="columnPreferenceService.allColumns"
|
||||
[(ngModel)]="visibleColumns"
|
||||
(ngModelChange)="onVisibleColumnsChange($event)"
|
||||
display="chip"
|
||||
placeholder="Select Columns"
|
||||
[style]="{ width: '100%' }"
|
||||
[filter]="true"
|
||||
[showClear]="true"
|
||||
></p-multiSelect>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 pt-4 pl-1">
|
||||
<p>Set as default?</p>
|
||||
<p-button
|
||||
label="Save"
|
||||
outlined
|
||||
size="small"
|
||||
(click)="columnPreferenceService.saveVisibleColumns(visibleColumns)"></p-button>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
}
|
||||
<div>
|
||||
<a
|
||||
class="topbar-items topbar-item"
|
||||
(click)="seriesCollapseOverlay.toggle($event)"
|
||||
pTooltip="Display settings"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-cog"></i>
|
||||
</a>
|
||||
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
|
||||
<div class="w-[220px] p-2 space-y-4 text-sm">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="collapse-series-checkbox" class="font-medium">Collapse series</label>
|
||||
<p-checkbox
|
||||
inputId="collapse-series-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="seriesCollapseFilter.isSeriesCollapsed"
|
||||
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
|
||||
</p-checkbox>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="font-medium text-sm">Grid item size</label>
|
||||
<p-slider
|
||||
[(ngModel)]="coverScalePreferenceService.scaleFactor"
|
||||
[min]="0.5"
|
||||
[max]="1.5"
|
||||
[step]="0.01"
|
||||
[style]="{ width: '100%' }"
|
||||
(onChange)="updateScale()">
|
||||
</p-slider>
|
||||
<div class="text-center">
|
||||
{{ coverScalePreferenceService.scaleFactor.toFixed(2) }}x
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<a class="topbar-items topbar-item" (click)="sortMenu.toggle($event)">
|
||||
<i
|
||||
class="pi pi-sort"
|
||||
pTooltip="Select sorting"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
<p-menu #sortMenu [popup]="true" [model]="this.bookSorter.sortOptions" appendTo="body">
|
||||
<ng-template pTemplate="item" let-item>
|
||||
<div class="flex justify-between items-center px-4 py-2 cursor-pointer" (click)="this.bookSorter.sortBooks(item.field)">
|
||||
<span>{{ item.label }}</span>
|
||||
@if (item.icon) {
|
||||
<i [class]="item.icon"></i>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-menu>
|
||||
</div>
|
||||
|
||||
<a class="topbar-items topbar-item" (click)="toggleTableGrid()">
|
||||
<i
|
||||
[ngClass]="viewIcon"
|
||||
pTooltip="Toggle between Grid and Table view"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- MOBILE SEARCH (only visible below md) -->
|
||||
<div class="relative md:hidden">
|
||||
<button
|
||||
type="button"
|
||||
class="topbar-items topbar-item"
|
||||
(click)="searchDropdown.toggle($event)"
|
||||
pTooltip="Search"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<i class="pi pi-search"></i>
|
||||
</button>
|
||||
|
||||
<p-popover #searchDropdown [dismissable]="true" appendTo="body" [style]="{ width: '24rem' }">
|
||||
<div class="relative w-full">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
placeholder="Title, Author, Series, Genre, or ISBN..."
|
||||
[(ngModel)]="bookTitle"
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
class="w-full"
|
||||
/>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
size="small"
|
||||
[rounded]="true"
|
||||
class="absolute right-2 top-1/2 -translate-y-1/2"
|
||||
(click)="clearSearch(); searchDropdown.hide()"
|
||||
></p-button>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
|
||||
<div class="hidden md:block relative">
|
||||
<i class="pi pi-search search-icon"></i>
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
placeholder="Title, Author, Series, Genre, or ISBN..."
|
||||
[(ngModel)]="bookTitle"
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
class="search-input"
|
||||
/>
|
||||
@if (bookTitle) {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
size="small"
|
||||
[rounded]="true"
|
||||
class="absolute right-2 top-1/2 -translate-y-1/2"
|
||||
(click)="clearSearch()"
|
||||
></p-button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<a class="topbar-items topbar-item" (click)="toggleSidebar()">
|
||||
<i
|
||||
[ngClass]="showFilter ? 'pi pi-angle-double-right' : 'pi pi-angle-double-left'"
|
||||
pTooltip="Toggle sidebar filters"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (bookState$ | async; as bookState) {
|
||||
<div>
|
||||
@if (!bookState?.loaded && !bookState?.error) {
|
||||
<div>
|
||||
<p-progressSpinner></p-progressSpinner>
|
||||
</div>
|
||||
}
|
||||
<div class="relative">
|
||||
@if (bookState?.error) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
{{ entityType === EntityType.LIBRARY ? "Failed to load library's books!" : "Failed to load shelf's books!" }}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
@if (!bookState?.error && bookState?.loaded && bookState?.books?.length === 0) {
|
||||
<div class="no-books-container">
|
||||
<p class="no-books-text">
|
||||
This collection has no books!
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
@if (bookState?.books; as books) {
|
||||
@if (currentViewMode === 'table' && books.length > 0) {
|
||||
<app-book-table
|
||||
[books]="books"
|
||||
(selectedBooksChange)="onSelectedBooksChange($event)"
|
||||
[sortOption]="this.bookSorter.selectedSort!"
|
||||
[visibleColumns]="visibleColumns"
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode === 'grid') {
|
||||
<virtual-scroller class="virtual-scroller" #scroll [items]="books">
|
||||
<div
|
||||
class="grid"
|
||||
#container
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
@for (book of scroll.viewPortItems; let i = $index; track book) {
|
||||
<div
|
||||
class="virtual-scroller-item relative"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||
<app-book-card
|
||||
[index]="i"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[readButtonHidden]="book.seriesCount ? true : false"
|
||||
[onBookSelect]="handleBookSelect.bind(this)"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="selectedBooks.has(book.id)">
|
||||
</app-book-card>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</virtual-scroller>
|
||||
}
|
||||
}
|
||||
@if (selectedBooks.size > 0) {
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
<div class="book-browser-footer bg-[var(--card-background)] bg-opacity-10" [@slideInOut]>
|
||||
<div class="flex justify-between items-center">
|
||||
<div class="flex">
|
||||
@if (entityType$ | async; as entityType) {
|
||||
<div class="flex gap-2 md:gap-6 pr-2">
|
||||
@if (userState.user!.permissions.canEditMetadata) {
|
||||
<p-menu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" class="hidden"/>
|
||||
<p-button
|
||||
(click)="menu.toggle($event)"
|
||||
pTooltip="Metadata actions"
|
||||
tooltipPosition="top"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
icon="pi pi-database">
|
||||
</p-button>
|
||||
}
|
||||
@if (entityType === EntityType.LIBRARY || entityType === EntityType.ALL_BOOKS || entityType === EntityType.UNSHELVED) {
|
||||
<p-button
|
||||
icon="pi pi-bookmark-fill"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
(onClick)="openShelfAssigner()"
|
||||
pTooltip="Assign to shelf"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (entityType === EntityType.SHELF) {
|
||||
<p-button
|
||||
icon="pi pi-bookmark"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
(click)="unshelfBooks()"
|
||||
pTooltip="Remove from shelf"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (userState.user!.permissions.canEditMetadata) {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-lock"
|
||||
severity="info"
|
||||
(click)="lockUnlockMetadata()"
|
||||
pTooltip="Lock/Unlock metadata"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-arrows-h"
|
||||
severity="info"
|
||||
(click)="moveFiles()"
|
||||
pTooltip="Organize Files"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
<div class="card flex justify-center">
|
||||
<p-button
|
||||
(click)="menu.toggle($event)"
|
||||
pTooltip="More actions"
|
||||
tooltipPosition="top"
|
||||
outlined="true"
|
||||
severity="info"
|
||||
icon="pi pi-ellipsis-v">
|
||||
</p-button>
|
||||
<p-tieredMenu #menu [model]="tieredMenuItems" [popup]="true" appendTo="body"/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<div class="flex gap-2 md:gap-6 px-2">
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-check-square"
|
||||
severity="success"
|
||||
(click)="selectAllBooks()"
|
||||
pTooltip="Select all books"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-times"
|
||||
severity="warn"
|
||||
(click)="deselectAllBooks()"
|
||||
pTooltip="Deselect all books"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (userState?.user?.permissions?.admin || userState?.user?.permissions?.canDeleteBook) {
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
(click)="confirmDeleteBooks()"
|
||||
pTooltip="Delete selected books"
|
||||
class="pl-2"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
|
||||
@if (this.showFilter) {
|
||||
<div
|
||||
class="mobile-filter-mask"
|
||||
(click)="toggleSidebar()">
|
||||
</div>
|
||||
<app-book-filter
|
||||
[showFilter]="showFilter"
|
||||
class="filter-overlay-container z-50 flex-shrink-0"
|
||||
[ngClass]="{ 'active': showFilter, 'ml-4': showFilter }"
|
||||
[entity$]="entity$"
|
||||
[entityType$]="entityType$"
|
||||
[resetFilter$]="resetFilterSubject"
|
||||
(filterSelected)="onFilterSelected($event)"
|
||||
(filterModeChanged)="onFilterModeChanged($event)">
|
||||
</app-book-filter>
|
||||
}
|
||||
|
||||
|
||||
</div>
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
.no-books-text {
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color);
|
||||
background: var(--card-background);
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.no-books-container {
|
||||
padding-top: 3rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.virtual-scroller {
|
||||
width: 100%;
|
||||
height: calc(100dvh - 10.9rem);
|
||||
padding: 1rem;
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.virtual-scroller {
|
||||
height: calc(100dvh - 9rem);
|
||||
}
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(1px, 1fr));
|
||||
gap: 1.3rem;
|
||||
align-items: start;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.virtual-scroller-item {
|
||||
transition: width 0.2s ease, height 0.2s ease;
|
||||
}
|
||||
|
||||
.book-browser-footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 10%;
|
||||
right: 10%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 1rem 0.5rem 0.5rem;
|
||||
z-index: 1;
|
||||
border-radius: 10px 10px 0 0;
|
||||
border: 1px solid rgba(255, 255, 255, 0.5);
|
||||
border-width: 1px 1px 0px 1px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.book-browser-footer {
|
||||
left: 0%;
|
||||
right: 0%;
|
||||
}
|
||||
}
|
||||
|
||||
.topbar-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
font-size: 5rem;
|
||||
border: 1px solid var(--border-color);
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
transition: outline-color .2s, border-color .2s;
|
||||
border-radius: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
outline-color: transparent;
|
||||
background-color: var(--card-background);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
|
||||
i, span {
|
||||
color: var(--primary-color);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 100;
|
||||
}
|
||||
}
|
||||
|
||||
.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 {
|
||||
min-width: 22rem;
|
||||
padding-left: 30px;
|
||||
height: 2.5rem;
|
||||
line-height: 2.5rem;
|
||||
font-size: 1rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.mobile-filter-mask {
|
||||
@media (max-width: 991px) {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 998;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
.filter-overlay-container {
|
||||
|
||||
@media (max-width: 991px) {
|
||||
width: 225px;
|
||||
position: fixed;
|
||||
top: 3.85rem;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: calc(100% - 3.85rem);
|
||||
background-color: var(--card-background);
|
||||
box-shadow: -2px 0 10px rgba(0, 0, 0, 0.15);
|
||||
transform: translateX(100%);
|
||||
transition: transform 0.3s ease;
|
||||
z-index: 1001;
|
||||
|
||||
&.active {
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
|
||||
&:not(.active) {
|
||||
width: 0 !important;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&.active {
|
||||
width: 225px;
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,762 @@
|
||||
import {Component, inject, OnInit, ViewChild} from '@angular/core';
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {ConfirmationService, MenuItem, MessageService, PrimeTemplate} from 'primeng/api';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {catchError, debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
|
||||
import {BehaviorSubject, combineLatest, Observable, of, Subject} from 'rxjs';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {SortService} from '../../service/sort.service';
|
||||
import {SortDirection, 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 {BookTableComponent} from './book-table/book-table.component';
|
||||
import {animate, state, style, transition, trigger} from '@angular/animations';
|
||||
import {Button} from 'primeng/button';
|
||||
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
|
||||
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
|
||||
import {BookCardComponent} from './book-card/book-card.component';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Menu} from 'primeng/menu';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {BookFilterComponent} from './book-filter/book-filter.component';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {EntityViewPreferences, UserService} from '../../../settings/user-management/user.service';
|
||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||
import {SideBarFilter} from './filters/SidebarFilter';
|
||||
import {HeaderFilter} from './filters/HeaderFilter';
|
||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||
import {BookSorter} from './sorting/BookSorter';
|
||||
import {BookDialogHelperService} from './BookDialogHelperService';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {Popover} from 'primeng/popover';
|
||||
import {Slider} from 'primeng/slider';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {TableColumnPreferenceService} from './table-column-preference-service';
|
||||
import {TieredMenu} from 'primeng/tieredmenu';
|
||||
import {BookMenuService} from '../../service/book-menu.service';
|
||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref-service';
|
||||
import {MetadataRefreshRequest} from '../../../metadata/model/request/metadata-refresh-request.model';
|
||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component';
|
||||
|
||||
export enum EntityType {
|
||||
LIBRARY = 'Library',
|
||||
SHELF = 'Shelf',
|
||||
MAGIC_SHELF = 'Magic Shelf',
|
||||
ALL_BOOKS = 'All Books',
|
||||
UNSHELVED = 'Unshelved Books',
|
||||
}
|
||||
|
||||
const QUERY_PARAMS = {
|
||||
VIEW: 'view',
|
||||
SORT: 'sort',
|
||||
DIRECTION: 'direction',
|
||||
FILTER: 'filter',
|
||||
SIDEBAR: 'sidebar',
|
||||
FROM: 'from',
|
||||
};
|
||||
|
||||
const VIEW_MODES = {
|
||||
GRID: 'grid',
|
||||
TABLE: 'table',
|
||||
};
|
||||
|
||||
const SORT_DIRECTION = {
|
||||
ASCENDING: 'asc',
|
||||
DESCENDING: 'desc',
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-browser',
|
||||
standalone: true,
|
||||
templateUrl: './book-browser.component.html',
|
||||
styleUrls: ['./book-browser.component.scss'],
|
||||
imports: [
|
||||
Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule,
|
||||
BookTableComponent, BookFilterComponent, Tooltip, NgClass, PrimeTemplate, NgStyle, Popover,
|
||||
Checkbox, Slider, Divider, MultiSelect, TieredMenu
|
||||
],
|
||||
providers: [SeriesCollapseFilter],
|
||||
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 {
|
||||
protected userService = inject(UserService);
|
||||
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
|
||||
protected columnPreferenceService = inject(TableColumnPreferenceService);
|
||||
protected sidebarFilterTogglePrefService = inject(SidebarFilterTogglePrefService);
|
||||
private activatedRoute = inject(ActivatedRoute);
|
||||
private messageService = inject(MessageService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private bookService = inject(BookService);
|
||||
private shelfService = inject(ShelfService);
|
||||
private dialogHelperService = inject(BookDialogHelperService);
|
||||
private bookMenuService = inject(BookMenuService);
|
||||
private sortService = inject(SortService);
|
||||
private router = inject(Router);
|
||||
private libraryShelfMenuService = inject(LibraryShelfMenuService);
|
||||
protected seriesCollapseFilter = inject(SeriesCollapseFilter);
|
||||
protected confirmationService = inject(ConfirmationService);
|
||||
protected magicShelfService = inject(MagicShelfService);
|
||||
protected bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
|
||||
bookState$: Observable<BookState> | undefined;
|
||||
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
|
||||
entityType$: Observable<EntityType> | undefined;
|
||||
searchTerm$ = new BehaviorSubject<string>('');
|
||||
selectedFilter = new BehaviorSubject<Record<string, any> | null>(null);
|
||||
selectedFilterMode = new BehaviorSubject<'and' | 'or'>('and');
|
||||
protected resetFilterSubject = new Subject<void>();
|
||||
entity: Library | Shelf | MagicShelf | null = null;
|
||||
entityType: EntityType | undefined;
|
||||
bookTitle = '';
|
||||
entityOptions: MenuItem[] | undefined;
|
||||
selectedBooks = new Set<number>();
|
||||
isDrawerVisible = false;
|
||||
dynamicDialogRef: DynamicDialogRef | undefined;
|
||||
EntityType = EntityType;
|
||||
currentFilterLabel: string | null = null;
|
||||
rawFilterParamFromUrl: string | null = null;
|
||||
hasSearchTerm = false;
|
||||
visibleColumns: { field: string; header: string }[] = [];
|
||||
entityViewPreferences: EntityViewPreferences | undefined;
|
||||
currentViewMode: string | undefined;
|
||||
lastAppliedSort: SortOption | null = null;
|
||||
private settingFiltersFromUrl = false;
|
||||
protected metadataMenuItems: MenuItem[] | undefined;
|
||||
protected tieredMenuItems: MenuItem[] | undefined;
|
||||
currentBooks: Book[] = [];
|
||||
lastSelectedIndex: number | null = null;
|
||||
showFilter = false;
|
||||
|
||||
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
|
||||
private headerFilter = new HeaderFilter(this.searchTerm$);
|
||||
protected bookSorter = new BookSorter(
|
||||
selectedSort => this.onManualSortChange(selectedSort)
|
||||
);
|
||||
|
||||
@ViewChild(BookTableComponent)
|
||||
bookTableComponent!: BookTableComponent;
|
||||
@ViewChild(BookFilterComponent, {static: false})
|
||||
bookFilterComponent!: BookFilterComponent;
|
||||
|
||||
get currentCardSize() {
|
||||
return this.coverScalePreferenceService.currentCardSize;
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return this.coverScalePreferenceService.gridColumnMinWidth;
|
||||
}
|
||||
|
||||
get viewIcon(): string {
|
||||
return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table';
|
||||
}
|
||||
|
||||
get hasSidebarFilters(): boolean {
|
||||
return !!this.selectedFilter.value && Object.keys(this.selectedFilter.value).length > 0;
|
||||
}
|
||||
|
||||
get isFilterActive(): boolean {
|
||||
return this.selectedFilter.value !== null;
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe();
|
||||
|
||||
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
|
||||
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
|
||||
const entityType = currentPath === 'all-books' ? EntityType.ALL_BOOKS : EntityType.UNSHELVED;
|
||||
this.entityType = entityType;
|
||||
this.entityType$ = of(entityType);
|
||||
this.entity$ = of(null);
|
||||
} else {
|
||||
const routeEntityInfo$ = this.getEntityInfoFromRoute();
|
||||
this.entityType$ = routeEntityInfo$.pipe(map(info => info.entityType));
|
||||
this.entity$ = routeEntityInfo$.pipe(
|
||||
switchMap(({entityId, entityType}) => this.fetchEntity(entityId, entityType))
|
||||
);
|
||||
this.entity$.subscribe(entity => {
|
||||
this.entity = entity ?? null;
|
||||
this.entityOptions = entity
|
||||
? this.isLibrary(entity)
|
||||
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
|
||||
: this.isMagicShelf(entity)
|
||||
? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity)
|
||||
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
this.activatedRoute.paramMap.subscribe(() => {
|
||||
this.searchTerm$.next('');
|
||||
this.bookTitle = '';
|
||||
this.deselectAllBooks();
|
||||
this.clearFilter();
|
||||
});
|
||||
|
||||
this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems(
|
||||
() => this.autoFetchMetadata(),
|
||||
() => this.fetchMetadata(),
|
||||
() => this.bulkEditMetadata(),
|
||||
() => this.multiBookEditMetadata(),
|
||||
);
|
||||
this.tieredMenuItems = this.bookMenuService.getTieredMenuItems(this.selectedBooks);
|
||||
|
||||
combineLatest([
|
||||
this.activatedRoute.paramMap,
|
||||
this.activatedRoute.queryParamMap,
|
||||
this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded))
|
||||
]).subscribe(([paramMap, queryParamMap, user]) => {
|
||||
|
||||
const viewParam = queryParamMap.get(QUERY_PARAMS.VIEW);
|
||||
const sortParam = queryParamMap.get(QUERY_PARAMS.SORT);
|
||||
const directionParam = queryParamMap.get(QUERY_PARAMS.DIRECTION);
|
||||
const filterParams = queryParamMap.get(QUERY_PARAMS.FILTER);
|
||||
|
||||
this.sidebarFilterTogglePrefService.showFilter$.subscribe(value => {
|
||||
this.showFilter = value;
|
||||
});
|
||||
|
||||
const parsedFilters: Record<string, string[]> = {};
|
||||
|
||||
if (filterParams) {
|
||||
this.settingFiltersFromUrl = true;
|
||||
|
||||
filterParams.split(',').forEach(pair => {
|
||||
const [key, ...valueParts] = pair.split(':');
|
||||
const value = valueParts.join(':');
|
||||
if (key && value) {
|
||||
parsedFilters[key] = value.split('|').map(v => v.trim()).filter(Boolean);
|
||||
}
|
||||
});
|
||||
|
||||
this.selectedFilter.next(parsedFilters);
|
||||
if (this.bookFilterComponent) {
|
||||
this.bookFilterComponent.setFilters?.(parsedFilters);
|
||||
this.bookFilterComponent.onFiltersChanged?.();
|
||||
}
|
||||
|
||||
const firstFilter = filterParams.split(',')[0];
|
||||
const [key, ...values] = firstFilter.split(':');
|
||||
const firstValue = values.join(':').split('|')[0];
|
||||
if (key && firstValue) {
|
||||
this.currentFilterLabel = this.capitalize(key) + ': ' + firstValue;
|
||||
} else {
|
||||
this.currentFilterLabel = 'All Books';
|
||||
}
|
||||
|
||||
this.rawFilterParamFromUrl = filterParams;
|
||||
this.settingFiltersFromUrl = false;
|
||||
} else {
|
||||
this.rawFilterParamFromUrl = null;
|
||||
this.currentFilterLabel = 'All Books';
|
||||
}
|
||||
|
||||
this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences;
|
||||
const globalPrefs = this.entityViewPreferences?.global;
|
||||
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined;
|
||||
this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor);
|
||||
this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference);
|
||||
this.visibleColumns = this.columnPreferenceService.visibleColumns;
|
||||
|
||||
const override = this.entityViewPreferences?.overrides?.find(o =>
|
||||
o.entityType?.toUpperCase() === currentEntityTypeStr &&
|
||||
o.entityId === this.entity?.id
|
||||
);
|
||||
|
||||
const effectivePrefs = override?.preferences ?? globalPrefs ?? {
|
||||
sortKey: 'addedOn',
|
||||
sortDir: 'ASC',
|
||||
view: 'GRID'
|
||||
};
|
||||
|
||||
const userSortKey = effectivePrefs.sortKey;
|
||||
const userSortDir = effectivePrefs.sortDir?.toUpperCase() === 'DESC'
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING;
|
||||
|
||||
const effectiveSortKey = sortParam || userSortKey;
|
||||
const effectiveSortDir = directionParam
|
||||
? (directionParam.toLowerCase() === SORT_DIRECTION.DESCENDING ? SortDirection.DESCENDING : SortDirection.ASCENDING)
|
||||
: userSortDir;
|
||||
|
||||
const matchedSort = this.bookSorter.sortOptions.find(opt => opt.field === effectiveSortKey);
|
||||
|
||||
this.bookSorter.selectedSort = matchedSort ? {
|
||||
label: matchedSort.label,
|
||||
field: matchedSort.field,
|
||||
direction: effectiveSortDir
|
||||
} : {
|
||||
label: 'Added On',
|
||||
field: 'addedOn',
|
||||
direction: SortDirection.DESCENDING
|
||||
};
|
||||
|
||||
const fromParam = queryParamMap.get(QUERY_PARAMS.FROM);
|
||||
this.currentViewMode = fromParam === 'toggle'
|
||||
? (viewParam === VIEW_MODES.TABLE || viewParam === VIEW_MODES.GRID
|
||||
? viewParam
|
||||
: VIEW_MODES.GRID)
|
||||
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
|
||||
|
||||
this.bookSorter.updateSortOptions();
|
||||
|
||||
if (this.lastAppliedSort?.field !== this.bookSorter.selectedSort.field || this.lastAppliedSort?.direction !== this.bookSorter.selectedSort.direction) {
|
||||
this.lastAppliedSort = {...this.bookSorter.selectedSort};
|
||||
this.applySortOption(this.bookSorter.selectedSort);
|
||||
}
|
||||
|
||||
const queryParams: any = {
|
||||
[QUERY_PARAMS.VIEW]: this.currentViewMode,
|
||||
[QUERY_PARAMS.SORT]: this.bookSorter.selectedSort.field,
|
||||
[QUERY_PARAMS.DIRECTION]: this.bookSorter.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING
|
||||
};
|
||||
|
||||
if (Object.keys(parsedFilters).length > 0) {
|
||||
queryParams[QUERY_PARAMS.FILTER] = Object.entries(parsedFilters).map(([k, v]) => `${k}:${v.join('|')}`).join(',');
|
||||
}
|
||||
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const changed = Object.keys(queryParams).some(k => currentParams[k] !== queryParams[k]);
|
||||
if (changed) {
|
||||
const mergedParams = {...currentParams, ...queryParams};
|
||||
this.router.navigate([], {
|
||||
queryParams: mergedParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
this.searchTerm$.subscribe(term => {
|
||||
this.hasSearchTerm = !!term && term.trim().length > 0;
|
||||
});
|
||||
}
|
||||
|
||||
onFilterSelected(filters: Record<string, any> | null): void {
|
||||
if (this.settingFiltersFromUrl) return;
|
||||
|
||||
this.selectedFilter.next(filters);
|
||||
this.rawFilterParamFromUrl = null;
|
||||
|
||||
const hasSidebarFilters = !!filters && Object.keys(filters).length > 0;
|
||||
this.currentFilterLabel = hasSidebarFilters ? 'All Books (Filtered)' : 'All Books';
|
||||
}
|
||||
|
||||
onFilterModeChanged(mode: 'and' | 'or'): void {
|
||||
this.selectedFilterMode.next(mode);
|
||||
}
|
||||
|
||||
toggleSidebar(): void {
|
||||
this.showFilter = !this.showFilter;
|
||||
this.sidebarFilterTogglePrefService.selectedShowFilter = this.showFilter;
|
||||
}
|
||||
|
||||
updateScale(): void {
|
||||
this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor);
|
||||
}
|
||||
|
||||
onVisibleColumnsChange(selected: any[]) {
|
||||
const allFields = this.bookTableComponent.allColumns.map(col => col.field);
|
||||
this.visibleColumns = selected.sort(
|
||||
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
|
||||
);
|
||||
}
|
||||
|
||||
onCheckboxClicked(event: { index: number; bookId: number; selected: boolean; shiftKey: boolean }) {
|
||||
const {index, bookId, selected, shiftKey} = event;
|
||||
if (!shiftKey || this.lastSelectedIndex === null) {
|
||||
if (selected) {
|
||||
this.selectedBooks.add(bookId);
|
||||
} else {
|
||||
this.selectedBooks.delete(bookId);
|
||||
}
|
||||
this.lastSelectedIndex = index;
|
||||
} else {
|
||||
const start = Math.min(this.lastSelectedIndex, index);
|
||||
const end = Math.max(this.lastSelectedIndex, index);
|
||||
const isUnselectingRange = !selected;
|
||||
for (let i = start; i <= end; i++) {
|
||||
const book = this.currentBooks[i];
|
||||
if (!book) continue;
|
||||
|
||||
if (isUnselectingRange) {
|
||||
this.selectedBooks.delete(book.id);
|
||||
} else {
|
||||
this.selectedBooks.add(book.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
selectAllBooks(): void {
|
||||
if (!this.currentBooks) return;
|
||||
for (const book of this.currentBooks) {
|
||||
this.selectedBooks.add(book.id);
|
||||
}
|
||||
if (this.bookTableComponent) {
|
||||
this.bookTableComponent.selectAllBooks();
|
||||
}
|
||||
}
|
||||
|
||||
deselectAllBooks(): void {
|
||||
this.selectedBooks.clear();
|
||||
this.isDrawerVisible = false;
|
||||
if (this.bookTableComponent) {
|
||||
this.bookTableComponent.clearSelectedBooks();
|
||||
}
|
||||
}
|
||||
|
||||
confirmDeleteBooks(): void {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete ${this.selectedBooks.size} book(s)?`,
|
||||
header: 'Confirm Deletion',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
accept: () => {
|
||||
this.bookService.deleteBooks(this.selectedBooks).subscribe(() => {
|
||||
this.selectedBooks.clear();
|
||||
});
|
||||
},
|
||||
reject: () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onSeriesCollapseCheckboxChange(value: boolean): void {
|
||||
this.seriesCollapseFilter.setCollapsed(value);
|
||||
}
|
||||
|
||||
onManualSortChange(sortOption: SortOption): void {
|
||||
this.applySortOption(sortOption);
|
||||
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const newParams = {
|
||||
...currentParams,
|
||||
sort: sortOption.field,
|
||||
direction: sortOption.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING
|
||||
};
|
||||
|
||||
this.router.navigate([], {
|
||||
queryParams: newParams,
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
applySortOption(sortOption: SortOption): void {
|
||||
if (this.entityType === EntityType.ALL_BOOKS) {
|
||||
this.bookState$ = this.fetchAllBooks();
|
||||
} else if (this.entityType === EntityType.UNSHELVED) {
|
||||
this.bookState$ = this.fetchUnshelvedBooks();
|
||||
} else {
|
||||
const routeParam$ = this.getEntityInfoFromRoute();
|
||||
this.bookState$ = routeParam$.pipe(
|
||||
switchMap(({entityId, entityType}) => this.fetchBooksByEntity(entityId, entityType))
|
||||
);
|
||||
}
|
||||
this.bookState$
|
||||
.pipe(
|
||||
filter(state => state.loaded && !state.error),
|
||||
map(state => state.books || [])
|
||||
)
|
||||
.subscribe(books => {
|
||||
this.currentBooks = books;
|
||||
});
|
||||
}
|
||||
|
||||
onSearchTermChange(term: string): void {
|
||||
this.searchTerm$.next(term);
|
||||
}
|
||||
|
||||
clearSearch(): void {
|
||||
this.bookTitle = '';
|
||||
this.onSearchTermChange('');
|
||||
this.resetFilters();
|
||||
}
|
||||
|
||||
resetFilters() {
|
||||
this.resetFilterSubject.next();
|
||||
}
|
||||
|
||||
clearFilter() {
|
||||
if (this.selectedFilter.value !== null) {
|
||||
this.selectedFilter.next(null);
|
||||
}
|
||||
this.clearSearch();
|
||||
}
|
||||
|
||||
toggleTableGrid(): void {
|
||||
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
view: this.currentViewMode,
|
||||
[QUERY_PARAMS.FROM]: 'toggle'
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
unshelfBooks() {
|
||||
if (!this.entity) return;
|
||||
this.bookService.updateBookShelves(this.selectedBooks, new Set(), new Set([this.entity.id])).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Books shelves updated'});
|
||||
this.selectedBooks.clear();
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update books shelves'});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
openShelfAssigner(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openShelfAssigner(this.selectedBooks);
|
||||
this.dynamicDialogRef.onClose.subscribe(() => {
|
||||
this.selectedBooks = new Set<number>();
|
||||
});
|
||||
}
|
||||
|
||||
lockUnlockMetadata(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
autoFetchMetadata(): void {
|
||||
const metadataRefreshRequest: MetadataRefreshRequest = {
|
||||
refreshType: MetadataRefreshType.BOOKS,
|
||||
bookIds: Array.from(this.selectedBooks),
|
||||
};
|
||||
this.bookService.autoRefreshMetadata(metadataRefreshRequest).subscribe();
|
||||
}
|
||||
|
||||
fetchMetadata(): void {
|
||||
this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
bulkEditMetadata(): void {
|
||||
this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
multiBookEditMetadata(): void {
|
||||
this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
moveFiles() {
|
||||
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
private isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
|
||||
return (entity as Library).paths !== undefined;
|
||||
}
|
||||
|
||||
private isMagicShelf(entity: any): entity is MagicShelf {
|
||||
return entity && 'filterJson' in entity;
|
||||
}
|
||||
|
||||
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);
|
||||
const magicShelfId = Number(params.get('magicShelfId') || NaN);
|
||||
|
||||
if (!isNaN(libraryId)) {
|
||||
this.entityType = EntityType.LIBRARY;
|
||||
return {entityId: libraryId, entityType: EntityType.LIBRARY};
|
||||
} else if (!isNaN(shelfId)) {
|
||||
this.entityType = EntityType.SHELF;
|
||||
return {entityId: shelfId, entityType: EntityType.SHELF};
|
||||
} else if (!isNaN(magicShelfId)) {
|
||||
this.entityType = EntityType.MAGIC_SHELF;
|
||||
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
|
||||
} else {
|
||||
this.entityType = EntityType.ALL_BOOKS;
|
||||
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | MagicShelf | null> {
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return this.fetchLibrary(entityId);
|
||||
case EntityType.SHELF:
|
||||
return this.fetchShelf(entityId);
|
||||
case EntityType.MAGIC_SHELF:
|
||||
return this.fetchMagicShelf(entityId);
|
||||
default:
|
||||
return of(null);
|
||||
}
|
||||
}
|
||||
|
||||
private fetchBooksByEntity(entityId: number, entityType: EntityType): Observable<BookState> {
|
||||
switch (entityType) {
|
||||
case EntityType.LIBRARY:
|
||||
return this.fetchBooks(book => book.libraryId === entityId);
|
||||
case EntityType.SHELF:
|
||||
return this.fetchBooks(book =>
|
||||
book.shelves?.some(shelf => shelf.id === entityId) ?? false
|
||||
);
|
||||
case EntityType.MAGIC_SHELF:
|
||||
return this.fetchBooksMagicShelfBooks(entityId);
|
||||
case EntityType.ALL_BOOKS:
|
||||
default:
|
||||
return this.fetchAllBooks();
|
||||
}
|
||||
}
|
||||
|
||||
private fetchAllBooks(): Observable<BookState> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(bookState => this.processBookState(bookState)),
|
||||
switchMap(bookState => this.applyBookFilters(bookState))
|
||||
);
|
||||
}
|
||||
|
||||
private fetchUnshelvedBooks(): Observable<BookState> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(bookState => ({
|
||||
...bookState,
|
||||
books: (bookState.books || []).filter(book => !book.shelves || book.shelves.length === 0)
|
||||
})),
|
||||
map(bookState => this.processBookState(bookState)),
|
||||
switchMap(bookState => this.applyBookFilters(bookState))
|
||||
);
|
||||
}
|
||||
|
||||
private fetchBooksMagicShelfBooks(magicShelfId: number): Observable<BookState> {
|
||||
return combineLatest([
|
||||
this.bookService.bookState$,
|
||||
this.magicShelfService.getShelf(magicShelfId)
|
||||
]).pipe(
|
||||
map(([bookState, magicShelf]) => {
|
||||
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
|
||||
return bookState;
|
||||
}
|
||||
const filteredBooks: Book[] | undefined = bookState.books?.filter(book =>
|
||||
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule)
|
||||
);
|
||||
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], this.bookSorter.selectedSort!);
|
||||
return {...bookState, books: sortedBooks};
|
||||
}),
|
||||
switchMap(bookState => this.applyBookFilters(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.bookSorter.selectedSort!);
|
||||
return {...bookState, books: sortedBooks};
|
||||
}
|
||||
return bookState;
|
||||
}),
|
||||
switchMap(bookState => this.applyBookFilters(bookState))
|
||||
);
|
||||
}
|
||||
|
||||
private shouldForceExpandSeries(): boolean {
|
||||
const queryParams = this.activatedRoute.snapshot.queryParams;
|
||||
const filterParam = queryParams[QUERY_PARAMS.FILTER];
|
||||
return (
|
||||
filterParam &&
|
||||
typeof filterParam === 'string' &&
|
||||
filterParam.split(',').some(pair => pair.trim().startsWith('series:'))
|
||||
);
|
||||
}
|
||||
|
||||
private applyBookFilters(bookState: BookState): Observable<BookState> {
|
||||
const forceExpandSeries = this.shouldForceExpandSeries();
|
||||
return this.headerFilter.filter(bookState).pipe(
|
||||
switchMap(filtered => this.sideBarFilter.filter(filtered)),
|
||||
switchMap(filtered => this.seriesCollapseFilter.filter(filtered, forceExpandSeries)),
|
||||
map(filtered =>
|
||||
(filtered.loaded && !filtered.error)
|
||||
? ({
|
||||
...filtered,
|
||||
books: this.sortService.applySort(filtered.books || [], this.bookSorter.selectedSort!)
|
||||
})
|
||||
: filtered
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private processBookState(bookState: BookState): BookState {
|
||||
if (bookState.loaded && !bookState.error) {
|
||||
const sortedBooks = this.sortService.applySort(bookState.books || [], this.bookSorter.selectedSort!);
|
||||
return {...bookState, books: sortedBooks};
|
||||
}
|
||||
return bookState;
|
||||
}
|
||||
|
||||
private fetchLibrary(libraryId: number): Observable<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;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private fetchMagicShelf(magicShelfId: number): Observable<MagicShelf | null> {
|
||||
return this.magicShelfService.shelvesState$.pipe(
|
||||
take(1),
|
||||
switchMap((state) => {
|
||||
const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null;
|
||||
if (cached) {
|
||||
return of(cached);
|
||||
}
|
||||
return this.magicShelfService.getShelf(magicShelfId).pipe(
|
||||
map(shelf => shelf ?? null),
|
||||
catchError(() => of(null))
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private capitalize(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
<div class="book-card"
|
||||
[class.selected]="isSelected"
|
||||
(mouseover)="isHovered = true"
|
||||
(mouseout)="isHovered = false"
|
||||
(click)="onCardClick($event)">
|
||||
|
||||
<div class="cover-container" [ngClass]="{ 'shimmer': !isImageLoaded, 'center-info-btn': readButtonHidden }">
|
||||
<div
|
||||
class="cover-container"
|
||||
[ngClass]="{
|
||||
'center-info-btn': readButtonHidden,
|
||||
'loaded': isImageLoaded
|
||||
}">
|
||||
<img
|
||||
[src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
|
||||
class="book-cover"
|
||||
[class.loaded]="isImageLoaded"
|
||||
alt="Cover of {{ displayTitle }}"
|
||||
loading="lazy"
|
||||
(load)="onImageLoad()"/>
|
||||
</div>
|
||||
|
||||
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
|
||||
<div class="series-number-overlay">
|
||||
#{{ book.metadata?.seriesNumber }}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (book.seriesCount && book.seriesCount! >= 1) {
|
||||
<div class="series-items-count-overlay">
|
||||
{{ book.seriesCount }}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (book.seriesCount && book.seriesCount! >= 1) {
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openSeriesInfo()"></p-button>
|
||||
} @else {
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)"></p-button>
|
||||
}
|
||||
|
||||
<p-button [hidden]="readButtonHidden" [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
|
||||
|
||||
@if (isCheckboxEnabled) {
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
class="select-checkbox"
|
||||
(click)="captureMouseEvent($event)"
|
||||
[ngModel]="isSelected"
|
||||
(onChange)="toggleSelection($event)">
|
||||
</p-checkbox>
|
||||
}
|
||||
|
||||
@if (progressPercentage !== null) {
|
||||
<p-progressBar
|
||||
[value]="progressPercentage"
|
||||
[showValue]="false"
|
||||
class="cover-progress-bar"
|
||||
[ngClass]="{ 'progress-complete': progressPercentage === 100, 'progress-incomplete': progressPercentage < 100 }">
|
||||
</p-progressBar>
|
||||
}
|
||||
@if (koProgressPercentage !== null) {
|
||||
<p-progressBar
|
||||
[value]="koProgressPercentage"
|
||||
[showValue]="false"
|
||||
[ngClass]="[
|
||||
progressPercentage == null ? 'cover-progress-bar-ko-only' : 'cover-progress-bar-ko-both',
|
||||
koProgressPercentage === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'
|
||||
]">
|
||||
</p-progressBar>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div [hidden]="bottomBarHidden">
|
||||
<div class="book-title-container flex items-center">
|
||||
@if (shouldShowStatusIcon()) {
|
||||
<div class="read-status-indicator"
|
||||
[ngClass]="getReadStatusClass()"
|
||||
[pTooltip]="'Status: ' + getReadStatusTooltip()"
|
||||
tooltipPosition="bottom">
|
||||
<i [class]="getReadStatusIcon()" style="font-size: 0.9rem"></i>
|
||||
</div>
|
||||
}
|
||||
<h4 class="book-title m-0 pl-2"
|
||||
tooltipPosition="bottom"
|
||||
[pTooltip]="'Title: ' + displayTitle">
|
||||
{{ displayTitle }}
|
||||
</h4>
|
||||
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body"></p-tieredmenu>
|
||||
<p-button
|
||||
class="custom-button-padding"
|
||||
size="small"
|
||||
[text]="true"
|
||||
(click)="onMenuToggle($event, menu)"
|
||||
icon="pi pi-ellipsis-v">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
.book-card {
|
||||
background-color: var(--card-background);
|
||||
border-radius: 8px 8px 8px 8px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
transition: border 0.2s;
|
||||
|
||||
&.selected {
|
||||
border: 2px solid var(--primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.cover-container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 5/7;
|
||||
background-color: var(--card-background);
|
||||
border-radius: 8px 8px 0 0;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background-color 0.3s ease;
|
||||
}
|
||||
|
||||
.cover-container.loaded {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 8px 8px 0 0;
|
||||
transition: opacity 0.3s ease-in;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.cover-container img.loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.cover-container::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: radial-gradient(circle, rgba(0, 0, 0, 0) 25%, rgba(0, 0, 0, 0.6) 100%);
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease-in-out;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.cover-container:hover::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.book-title-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.book-title {
|
||||
flex-grow: 1;
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.info-btn,
|
||||
.read-btn {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.3s ease, visibility 0.3s ease;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.info-btn {
|
||||
top: 21%;
|
||||
}
|
||||
|
||||
.read-btn {
|
||||
bottom: 21%;
|
||||
}
|
||||
|
||||
.cover-container:hover .info-btn,
|
||||
.cover-container:hover .read-btn {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.cover-container.center-info-btn .info-btn {
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.select-checkbox {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.2s ease, visibility 0.2s ease;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.select-checkbox .p-checkbox {
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.cover-container:hover .select-checkbox,
|
||||
.book-card.selected .select-checkbox {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.cover-progress-bar,
|
||||
.cover-progress-bar-ko-both,
|
||||
.cover-progress-bar-ko-only {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 2.5px;
|
||||
z-index: 1;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.cover-progress-bar {
|
||||
bottom: 2.5px;
|
||||
}
|
||||
|
||||
.cover-progress-bar-ko-both {
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.cover-progress-bar-ko-only {
|
||||
bottom: 2.5px;
|
||||
}
|
||||
|
||||
.series-number-overlay {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
padding: 1px 3px;
|
||||
border-radius: 3px;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.series-items-count-overlay {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
background-color: var(--primary-color);
|
||||
color: var(--primary-text-color-dark);
|
||||
font-size: 0.75rem;
|
||||
padding: 1px 6px;
|
||||
border-radius: 3px;
|
||||
z-index: 3;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
box-shadow: 0 0 4px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.read-status-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: bold;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
|
||||
.status-read {
|
||||
color: #22c55e;
|
||||
}
|
||||
|
||||
.status-reading {
|
||||
color: #3b82f6;
|
||||
}
|
||||
|
||||
.status-re-reading {
|
||||
color: #06b6d4;
|
||||
}
|
||||
|
||||
.status-partially-read {
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.status-paused {
|
||||
color: #eab308;
|
||||
}
|
||||
|
||||
.status-abandoned {
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.status-wont-read {
|
||||
color: #ec4899;
|
||||
}
|
||||
|
||||
::ng-deep .progress-incomplete .p-progressbar-value {
|
||||
background-color: #3b82f6;
|
||||
}
|
||||
|
||||
::ng-deep .progress-complete .p-progressbar-value {
|
||||
background-color: #22c55e;
|
||||
}
|
||||
|
||||
::ng-deep .progress-incomplete-ko .p-progressbar-value {
|
||||
background-color: #fbbf24;
|
||||
}
|
||||
|
||||
::ng-deep .progress-complete-ko .p-progressbar-value {
|
||||
background-color: #8b5cf6;
|
||||
}
|
||||
|
||||
::ng-deep p-progressbar {
|
||||
--p-progressbar-border-radius: 0 !important;
|
||||
}
|
||||
|
||||
::ng-deep .custom-button-padding .p-button {
|
||||
padding-block: 0.25rem !important;
|
||||
}
|
||||
+763
@@ -0,0 +1,763 @@
|
||||
import {Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
|
||||
import {TooltipModule} from "primeng/tooltip";
|
||||
import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model';
|
||||
import {Button} from 'primeng/button';
|
||||
import {MenuModule} from 'primeng/menu';
|
||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {ShelfAssignerComponent} from '../../shelf-assigner/shelf-assigner.component';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {CheckboxChangeEvent, CheckboxModule} from 'primeng/checkbox';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {MetadataRefreshRequest} from '../../../../metadata/model/request/metadata-refresh-request.model';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {filter, Subject} from 'rxjs';
|
||||
import {EmailService} from '../../../../settings/email/email.service';
|
||||
import {TieredMenu} from 'primeng/tieredmenu';
|
||||
import {BookSenderComponent} from '../../book-sender/book-sender.component';
|
||||
import {Router} from '@angular/router';
|
||||
import {ProgressBar} from 'primeng/progressbar';
|
||||
import {BookMetadataCenterComponent} from '../../../../metadata/component/book-metadata-center-component/book-metadata-center.component';
|
||||
import {take, takeUntil} from 'rxjs/operators';
|
||||
import {readStatusLabels} from '../book-filter/book-filter.component';
|
||||
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {BookDialogHelperService} from '../BookDialogHelperService';
|
||||
import {MetadataFetchOptionsComponent} from '../../../../metadata/component/metadata-options-dialog/metadata-fetch-options-component/metadata-fetch-options.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card',
|
||||
templateUrl: './book-card.component.html',
|
||||
styleUrls: ['./book-card.component.scss'],
|
||||
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgClass, TieredMenu, ProgressBar, TooltipModule],
|
||||
standalone: true
|
||||
})
|
||||
export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
|
||||
@Output() checkboxClick = new EventEmitter<{ index: number; bookId: number; selected: boolean; shiftKey: boolean }>();
|
||||
|
||||
@Input() index!: number;
|
||||
@Input() book!: Book;
|
||||
@Input() isCheckboxEnabled: boolean = false;
|
||||
@Input() onBookSelect?: (bookId: number, selected: boolean) => void;
|
||||
@Input() isSelected: boolean = false;
|
||||
@Input() bottomBarHidden: boolean = false;
|
||||
@Input() readButtonHidden: boolean = false;
|
||||
@Input() isSeriesCollapsed: boolean = false;
|
||||
|
||||
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
|
||||
|
||||
items: MenuItem[] | undefined;
|
||||
isHovered: boolean = false;
|
||||
isImageLoaded: boolean = false;
|
||||
isSubMenuLoading = false;
|
||||
private additionalFilesLoaded = false;
|
||||
|
||||
private bookService = inject(BookService);
|
||||
private dialogService = inject(DialogService);
|
||||
private userService = inject(UserService);
|
||||
private emailService = inject(EmailService);
|
||||
private messageService = inject(MessageService);
|
||||
private router = inject(Router);
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private confirmationService = inject(ConfirmationService);
|
||||
private bookDialogHelperService = inject(BookDialogHelperService);
|
||||
|
||||
private userPermissions: any;
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
private destroy$ = new Subject<void>();
|
||||
protected readStatusHelper = inject(ReadStatusHelper);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(userState => {
|
||||
this.userPermissions = userState.user?.permissions;
|
||||
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
this.initMenu();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['book'] && !changes['book'].firstChange) {
|
||||
this.additionalFilesLoaded = false;
|
||||
this.initMenu();
|
||||
}
|
||||
}
|
||||
|
||||
get progressPercentage(): number | null {
|
||||
if (this.book.epubProgress?.percentage != null) {
|
||||
return this.book.epubProgress.percentage;
|
||||
}
|
||||
if (this.book.pdfProgress?.percentage != null) {
|
||||
return this.book.pdfProgress.percentage;
|
||||
}
|
||||
if (this.book.cbxProgress?.percentage != null) {
|
||||
return this.book.cbxProgress.percentage;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
get koProgressPercentage(): number | null {
|
||||
if (this.book.koreaderProgress?.percentage != null) {
|
||||
return this.book.koreaderProgress.percentage;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
get displayTitle(): string | undefined {
|
||||
return (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title;
|
||||
// return (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata.seriesName : this.book.metadata?.title;
|
||||
}
|
||||
|
||||
onImageLoad(): void {
|
||||
this.isImageLoaded = true;
|
||||
}
|
||||
|
||||
readBook(book: Book): void {
|
||||
this.bookService.readBook(book.id);
|
||||
}
|
||||
|
||||
onMenuToggle(event: Event, menu: TieredMenu): void {
|
||||
menu.toggle(event);
|
||||
|
||||
// Load additional files if not already loaded and needed
|
||||
if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) {
|
||||
this.isSubMenuLoading = true;
|
||||
this.bookService.getBookByIdFromAPI(this.book.id, true).subscribe({
|
||||
next: (book) => {
|
||||
this.book = book;
|
||||
this.additionalFilesLoaded = true;
|
||||
this.isSubMenuLoading = false;
|
||||
this.initMenu();
|
||||
},
|
||||
error: () => {
|
||||
this.isSubMenuLoading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private needsAdditionalFilesData(): boolean {
|
||||
// Don't need to load if already loaded
|
||||
if (this.additionalFilesLoaded) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const hasNoAlternativeFormats = !this.book.alternativeFormats || this.book.alternativeFormats.length === 0;
|
||||
const hasNoSupplementaryFiles = !this.book.supplementaryFiles || this.book.supplementaryFiles.length === 0;
|
||||
return (this.hasDownloadPermission() || this.hasDeleteBookPermission()) &&
|
||||
hasNoAlternativeFormats && hasNoSupplementaryFiles;
|
||||
}
|
||||
|
||||
private initMenu() {
|
||||
this.items = [
|
||||
{
|
||||
label: 'Assign Shelf',
|
||||
icon: 'pi pi-folder',
|
||||
command: () => this.openShelfDialog()
|
||||
},
|
||||
{
|
||||
label: 'View Details',
|
||||
icon: 'pi pi-info-circle',
|
||||
command: () => {
|
||||
setTimeout(() => {
|
||||
if (this.metadataCenterViewMode === 'route') {
|
||||
this.router.navigate(['/book', this.book.id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
} else {
|
||||
this.dialogService.open(BookMetadataCenterComponent, {
|
||||
width: '95%',
|
||||
data: {bookId: this.book.id},
|
||||
modal: true,
|
||||
dismissableMask: true,
|
||||
showHeader: false
|
||||
});
|
||||
}
|
||||
}, 150);
|
||||
},
|
||||
},
|
||||
...this.getPermissionBasedMenuItems(),
|
||||
...this.moreMenuItems(),
|
||||
];
|
||||
}
|
||||
|
||||
private getPermissionBasedMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
if (this.hasDownloadPermission()) {
|
||||
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
|
||||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
|
||||
|
||||
if (hasAdditionalFiles) {
|
||||
const downloadItems = this.getDownloadMenuItems();
|
||||
items.push({
|
||||
label: 'Download',
|
||||
icon: 'pi pi-download',
|
||||
items: downloadItems
|
||||
});
|
||||
} else if (this.additionalFilesLoaded) {
|
||||
// Data has been loaded but no additional files exist
|
||||
items.push({
|
||||
label: 'Download',
|
||||
icon: 'pi pi-download',
|
||||
command: () => {
|
||||
this.bookService.downloadFile(this.book.id);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Data not loaded yet
|
||||
items.push({
|
||||
label: 'Download',
|
||||
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-download',
|
||||
items: [{label: 'Loading...', disabled: true}]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (this.hasDeleteBookPermission()) {
|
||||
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
|
||||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
|
||||
|
||||
if (hasAdditionalFiles) {
|
||||
const deleteItems = this.getDeleteMenuItems();
|
||||
items.push({
|
||||
label: 'Delete',
|
||||
icon: 'pi pi-trash',
|
||||
items: deleteItems
|
||||
});
|
||||
} else if (this.additionalFilesLoaded) {
|
||||
// Data has been loaded but no additional files exist - show delete book option
|
||||
items.push({
|
||||
label: 'Delete',
|
||||
icon: 'pi pi-trash',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete "${this.book.metadata?.title}"?`,
|
||||
header: 'Confirm Deletion',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Data not loaded yet
|
||||
items.push({
|
||||
label: 'Delete',
|
||||
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-trash',
|
||||
items: [{label: 'Loading...', disabled: true}]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (this.hasEmailBookPermission()) {
|
||||
items.push(
|
||||
{
|
||||
label: 'Send Book',
|
||||
icon: 'pi pi-envelope',
|
||||
items: [{
|
||||
label: 'Quick Send',
|
||||
icon: 'pi pi-envelope',
|
||||
command: () => {
|
||||
this.emailService.emailBookQuick(this.book.id).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'The book sending has been scheduled.',
|
||||
});
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || 'An error occurred while sending the book.';
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: errorMessage,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Custom Send',
|
||||
icon: 'pi pi-envelope',
|
||||
command: () => {
|
||||
this.dialogService.open(BookSenderComponent, {
|
||||
header: 'Send Book to Email',
|
||||
modal: true,
|
||||
closable: true,
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
},
|
||||
data: {
|
||||
bookId: this.book.id,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
if (this.hasEditMetadataPermission()) {
|
||||
items.push({
|
||||
label: 'Metadata',
|
||||
icon: 'pi pi-database',
|
||||
items: [
|
||||
{
|
||||
label: 'Search Metadata',
|
||||
icon: 'pi pi-sparkles',
|
||||
command: () => {
|
||||
setTimeout(() => {
|
||||
this.router.navigate(['/book', this.book.id], {
|
||||
queryParams: {tab: 'match'}
|
||||
})
|
||||
}, 150);
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Auto Fetch',
|
||||
icon: 'pi pi-bolt',
|
||||
command: () => {
|
||||
const metadataRefreshRequest: MetadataRefreshRequest = {
|
||||
refreshType: MetadataRefreshType.BOOKS,
|
||||
bookIds: [this.book.id],
|
||||
};
|
||||
this.bookService.autoRefreshMetadata(metadataRefreshRequest).subscribe();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Custom Fetch',
|
||||
icon: 'pi pi-sync',
|
||||
command: () => {
|
||||
this.dialogService.open(MetadataFetchOptionsComponent, {
|
||||
header: 'Metadata Refresh Options',
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookIds: [this.book!.id],
|
||||
metadataRefreshType: MetadataRefreshType.BOOKS,
|
||||
},
|
||||
});
|
||||
},
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private moreMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
if (this.hasEditMetadataPermission()) {
|
||||
items.push({
|
||||
label: 'More Actions',
|
||||
icon: 'pi pi-ellipsis-h',
|
||||
items: [
|
||||
{
|
||||
label: 'Organize File',
|
||||
icon: 'pi pi-arrows-h',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openFileMoverDialog(new Set([this.book.id]));
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Read Status',
|
||||
icon: 'pi pi-book',
|
||||
items: Object.entries(readStatusLabels).map(([status, label]) => ({
|
||||
label,
|
||||
command: () => {
|
||||
this.bookService.updateBookReadStatus(this.book.id, status as ReadStatus).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Read Status Updated',
|
||||
detail: `Marked as "${label}"`,
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Could not update read status.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}))
|
||||
},
|
||||
{
|
||||
label: 'Reset Booklore Progress',
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.bookService.resetProgress(this.book.id, ResetProgressTypes.BOOKLORE).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'Booklore reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Could not reset Booklore progress.',
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
label: 'Reset KOReader Progress',
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.bookService.resetProgress(this.book.id, ResetProgressTypes.KOREADER).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'KOReader reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Could not reset KOReader progress.',
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private openShelfDialog(): void {
|
||||
this.dialogService.open(ShelfAssignerComponent, {
|
||||
header: `Update Book's Shelves`,
|
||||
modal: true,
|
||||
closable: true,
|
||||
contentStyle: {overflow: 'auto'},
|
||||
baseZIndex: 10,
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
},
|
||||
data: {
|
||||
book: this.book,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openSeriesInfo(): void {
|
||||
const seriesName = this.book?.metadata?.seriesName;
|
||||
if (this.isSeriesCollapsed && seriesName) {
|
||||
const encodedSeriesName = encodeURIComponent(seriesName);
|
||||
this.router.navigate(['/series', encodedSeriesName]);
|
||||
} else {
|
||||
this.openBookInfo(this.book);
|
||||
}
|
||||
}
|
||||
|
||||
openBookInfo(book: Book): void {
|
||||
if (this.metadataCenterViewMode === 'route') {
|
||||
this.router.navigate(['/book', book.id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
} else {
|
||||
this.dialogService.open(BookMetadataCenterComponent, {
|
||||
width: '85%',
|
||||
data: {bookId: book.id},
|
||||
modal: true,
|
||||
dismissableMask: true,
|
||||
showHeader: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private getDownloadMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
// Add main book file first
|
||||
items.push({
|
||||
label: `${this.book.fileName || 'Book File'}`,
|
||||
icon: 'pi pi-file',
|
||||
command: () => {
|
||||
this.bookService.downloadFile(this.book.id);
|
||||
}
|
||||
});
|
||||
|
||||
// Add separator if there are additional files
|
||||
if (this.hasAdditionalFiles()) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
// Add alternative formats
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
|
||||
this.book.alternativeFormats.forEach(format => {
|
||||
const extension = this.getFileExtension(format.filePath);
|
||||
items.push({
|
||||
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.downloadAdditionalFile(this.book.id, format.id)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Add separator if both alternative formats and supplementary files exist
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
|
||||
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
// Add supplementary files
|
||||
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
this.book.supplementaryFiles.forEach(file => {
|
||||
const extension = this.getFileExtension(file.filePath);
|
||||
items.push({
|
||||
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.downloadAdditionalFile(this.book.id, file.id)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private getDeleteMenuItems(): MenuItem[] {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
// Add main book deletion
|
||||
items.push({
|
||||
label: 'Book',
|
||||
icon: 'pi pi-book',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete "${this.book.metadata?.title}"?`,
|
||||
header: 'Confirm Deletion',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Add separator if there are additional files
|
||||
if (this.hasAdditionalFiles()) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
// Add alternative formats
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
|
||||
this.book.alternativeFormats.forEach(format => {
|
||||
const extension = this.getFileExtension(format.filePath);
|
||||
items.push({
|
||||
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.deleteAdditionalFile(this.book.id, format.id, format.fileName || 'file')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Add separator if both alternative formats and supplementary files exist
|
||||
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
|
||||
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
// Add supplementary files
|
||||
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
|
||||
this.book.supplementaryFiles.forEach(file => {
|
||||
const extension = this.getFileExtension(file.filePath);
|
||||
items.push({
|
||||
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.deleteAdditionalFile(this.book.id, file.id, file.fileName || 'file')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
private hasAdditionalFiles(): boolean {
|
||||
return !!(this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
|
||||
!!(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
|
||||
}
|
||||
|
||||
private downloadAdditionalFile(bookId: number, fileId: number): void {
|
||||
this.bookService.downloadAdditionalFile(bookId, fileId);
|
||||
}
|
||||
|
||||
private deleteAdditionalFile(bookId: number, fileId: number, fileName: string): void {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete the additional file "${fileName}"?`,
|
||||
header: 'Confirm File Deletion',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
this.bookService.deleteAdditionalFile(bookId, fileId).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: `Additional file "${fileName}" deleted successfully`
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: `Failed to delete additional file: ${error.message || 'Unknown error'}`
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getFileExtension(filePath?: string): string | null {
|
||||
if (!filePath) return null;
|
||||
const parts = filePath.split('.');
|
||||
if (parts.length < 2) return null;
|
||||
return parts.pop()?.toUpperCase() || null;
|
||||
}
|
||||
|
||||
private getFileIcon(fileType: string | null): string {
|
||||
if (!fileType) return 'pi pi-file';
|
||||
switch (fileType.toLowerCase()) {
|
||||
case 'pdf':
|
||||
return 'pi pi-file-pdf';
|
||||
case 'epub':
|
||||
case 'mobi':
|
||||
case 'azw3':
|
||||
return 'pi pi-book';
|
||||
case 'cbz':
|
||||
case 'cbr':
|
||||
case 'cbx':
|
||||
return 'pi pi-image';
|
||||
default:
|
||||
return 'pi pi-file';
|
||||
}
|
||||
}
|
||||
|
||||
private getFileSizeInMB(fileInfo: AdditionalFile): string {
|
||||
const sizeKb = fileInfo?.fileSizeKb;
|
||||
return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-';
|
||||
}
|
||||
|
||||
private isAdmin(): boolean {
|
||||
return this.userPermissions?.admin ?? false;
|
||||
}
|
||||
|
||||
private hasEditMetadataPermission(): boolean {
|
||||
return this.isAdmin() || (this.userPermissions?.canEditMetadata ?? false);
|
||||
}
|
||||
|
||||
private hasDownloadPermission(): boolean {
|
||||
return this.isAdmin() || (this.userPermissions?.canDownload ?? false);
|
||||
}
|
||||
|
||||
private hasEmailBookPermission(): boolean {
|
||||
return this.isAdmin() || (this.userPermissions?.canEmailBook ?? false);
|
||||
}
|
||||
|
||||
private hasDeleteBookPermission(): boolean {
|
||||
return this.isAdmin() || (this.userPermissions?.canDeleteBook ?? false);
|
||||
}
|
||||
|
||||
private lastMouseEvent: MouseEvent | null = null;
|
||||
|
||||
captureMouseEvent(event: MouseEvent): void {
|
||||
this.lastMouseEvent = event;
|
||||
}
|
||||
|
||||
onCardClick(event: MouseEvent): void {
|
||||
if (!event.ctrlKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.toggleCardSelection(!this.isSelected)
|
||||
}
|
||||
|
||||
toggleCardSelection(selected: boolean): void {
|
||||
if (!this.isCheckboxEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isSelected = selected;
|
||||
const shiftKey = this.lastMouseEvent?.shiftKey ?? false;
|
||||
|
||||
this.checkboxClick.emit({
|
||||
index: this.index,
|
||||
bookId: this.book.id,
|
||||
selected: selected,
|
||||
shiftKey: shiftKey,
|
||||
});
|
||||
|
||||
if (this.onBookSelect) {
|
||||
this.onBookSelect(this.book.id, selected);
|
||||
}
|
||||
|
||||
this.lastMouseEvent = null;
|
||||
}
|
||||
|
||||
toggleSelection(event: CheckboxChangeEvent): void {
|
||||
this.toggleCardSelection(event.checked);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
getReadStatusIcon(): string {
|
||||
return this.readStatusHelper.getReadStatusIcon(this.book.readStatus);
|
||||
}
|
||||
|
||||
getReadStatusClass(): string {
|
||||
return this.readStatusHelper.getReadStatusClass(this.book.readStatus);
|
||||
}
|
||||
|
||||
getReadStatusTooltip(): string {
|
||||
return this.readStatusHelper.getReadStatusTooltip(this.book.readStatus);
|
||||
}
|
||||
|
||||
shouldShowStatusIcon(): boolean {
|
||||
return this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
<div class="h-[calc(100dvh-6.1rem)] rounded-xl bg-[var(--card-background)] flex flex-col">
|
||||
|
||||
<div class="flex items-center justify-between px-4 py-4">
|
||||
<span class="text font-semibold">Filter Mode</span>
|
||||
<p-selectButton
|
||||
[options]="filterModeOptions"
|
||||
[(ngModel)]="selectedFilterMode"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
class="text-sm"
|
||||
allowEmpty="false"
|
||||
styleClass="h-8"></p-selectButton>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto pb-4 pr-1" style="overscroll-behavior: contain;">
|
||||
<p-accordion [value]="expandedPanels">
|
||||
@for (filterType of filterTypes; track trackByFilterType(i, filterType); let i = $index) {
|
||||
<p-accordion-panel [value]="i">
|
||||
<p-accordion-header>
|
||||
<span class="inline-flex items-center gap-1">
|
||||
{{ filterLabels[filterType] || (filterType | titlecase) }}
|
||||
@if (activeFilters[filterType]?.length) {
|
||||
<span class="text-sm text-[var(--primary-color)]">
|
||||
({{ activeFilters[filterType].length }})
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
</p-accordion-header>
|
||||
|
||||
<p-accordion-content>
|
||||
@if (filterStreams[filterType] | async; as filters) {
|
||||
<div
|
||||
class="max-h-[27.5rem] overflow-y-auto overscroll-contain pr-1"
|
||||
style="overscroll-behavior: contain;">
|
||||
@for (filter of filters; track trackByFilter(j, filter); let j = $index) {
|
||||
<div
|
||||
class="filter-row cursor-pointer transition-colors duration-200 ease-in-out pb-1 flex flex-row items-center justify-between gap-2"
|
||||
[ngClass]="{
|
||||
'text-[var(--primary-color)]': activeFilters[filterType]?.includes(filter.value?.id || filter.value)
|
||||
}"
|
||||
(click)="handleFilterClick(filterType, filter.value?.id || filter.value)">
|
||||
{{ filter.value.name || filter.value }}
|
||||
<p-badge class="filter-value-badge" [value]="filter.bookCount"></p-badge>
|
||||
</div>
|
||||
}
|
||||
@if (truncatedFilters[filterType]) {
|
||||
<div class="text-xs text-gray-500 text-center pt-2 border-t border-gray-200">
|
||||
Showing first 250 items
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</p-accordion-content>
|
||||
</p-accordion-panel>
|
||||
}
|
||||
</p-accordion>
|
||||
|
||||
<div class="text-xs text-gray-500 text-center pt-4 px-4 mt-2">
|
||||
Note: Top 500 items are displayed per filter category
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
:host ::ng-deep p-accordion-header {
|
||||
--p-accordion-header-padding: 0.6rem 1rem;
|
||||
}
|
||||
|
||||
.filter-row {
|
||||
align-items: flex-start;
|
||||
}
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
import {ChangeDetectionStrategy, Component, EventEmitter, inject, Input, OnDestroy, OnInit, Output} from '@angular/core';
|
||||
import {combineLatest, Observable, of, shareReplay, Subject, takeUntil} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {Library} from '../../../model/library.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
import {EntityType} from '../book-browser.component';
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
|
||||
import {AsyncPipe, NgClass, TitleCasePipe} from '@angular/common';
|
||||
import {Badge} from 'primeng/badge';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {SelectButton} from 'primeng/selectbutton';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
|
||||
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
|
||||
|
||||
type Filter<T> = { value: T; bookCount: number };
|
||||
|
||||
export const ratingRanges = [
|
||||
{id: '0to1', label: '0 to 1', min: 0, max: 1, sortIndex: 0},
|
||||
{id: '1to2', label: '1 to 2', min: 1, max: 2, sortIndex: 1},
|
||||
{id: '2to3', label: '2 to 3', min: 2, max: 3, sortIndex: 2},
|
||||
{id: '3to4', label: '3 to 4', min: 3, max: 4, sortIndex: 3},
|
||||
{id: '4to4.5', label: '4 to 4.5', min: 4, max: 4.5, sortIndex: 4},
|
||||
{id: '4.5plus', label: '4.5+', min: 4.5, max: Infinity, sortIndex: 5}
|
||||
];
|
||||
|
||||
export const ratingOptions10 = Array.from({length: 10}, (_, i) => ({
|
||||
id: `${i + 1}`,
|
||||
label: `${i + 1}`,
|
||||
value: i + 1,
|
||||
sortIndex: i
|
||||
}));
|
||||
|
||||
export const fileSizeRanges = [
|
||||
{id: '<1mb', label: '< 1 MB', min: 0, max: 1024, sortIndex: 0},
|
||||
{id: '1to10mb', label: '1–10 MB', min: 1024, max: 10240, sortIndex: 1},
|
||||
{id: '10to50mb', label: '10–50 MB', min: 10240, max: 51200, sortIndex: 2},
|
||||
{id: '50to100mb', label: '50–100 MB', min: 51200, max: 102400, sortIndex: 3},
|
||||
{id: '250to500mb', label: '250–500 MB', min: 256000, max: 512000, sortIndex: 4},
|
||||
{id: '500mbto1gb', label: '0.5–1 GB', min: 512000, max: 1048576, sortIndex: 5},
|
||||
{id: '1to2gb', label: '1–2 GB', min: 1048576, max: 2097152, sortIndex: 6},
|
||||
{id: '5plusgb', label: '5+ GB', min: 5242880, max: Infinity, sortIndex: 7}
|
||||
];
|
||||
|
||||
export const pageCountRanges = [
|
||||
{id: '<50', label: '< 50 pages', min: 0, max: 50, sortIndex: 0},
|
||||
{id: '50to100', label: '50–100 pages', min: 50, max: 100, sortIndex: 1},
|
||||
{id: '100to200', label: '100–200 pages', min: 100, max: 200, sortIndex: 2},
|
||||
{id: '200to400', label: '200–400 pages', min: 200, max: 400, sortIndex: 3},
|
||||
{id: '400to600', label: '400–600 pages', min: 400, max: 600, sortIndex: 4},
|
||||
{id: '600to1000', label: '600–1000 pages', min: 600, max: 1000, sortIndex: 5},
|
||||
{id: '1000plus', label: '1000+ pages', min: 1000, max: Infinity, sortIndex: 6}
|
||||
];
|
||||
|
||||
export const matchScoreRanges = [
|
||||
{id: '0.95-1.0', min: 0.95, max: 1.01, label: 'Outstanding (95–100%)', sortIndex: 0},
|
||||
{id: '0.90-0.94', min: 0.90, max: 0.95, label: 'Excellent (90–94%)', sortIndex: 1},
|
||||
{id: '0.80-0.89', min: 0.80, max: 0.90, label: 'Great (80–89%)', sortIndex: 2},
|
||||
{id: '0.70-0.79', min: 0.70, max: 0.80, label: 'Good (70–79%)', sortIndex: 3},
|
||||
{id: '0.50-0.69', min: 0.50, max: 0.70, label: 'Fair (50–69%)', sortIndex: 4},
|
||||
{id: '0.30-0.49', min: 0.30, max: 0.50, label: 'Weak (30–49%)', sortIndex: 5},
|
||||
{id: '0.00-0.29', min: 0.00, max: 0.30, label: 'Poor (0–29%)', sortIndex: 6}
|
||||
];
|
||||
|
||||
function getLanguageFilter(book: Book): { id: string; name: string }[] {
|
||||
const lang = book.metadata?.language;
|
||||
return lang ? [{id: lang, name: lang}] : [];
|
||||
}
|
||||
|
||||
function getFileSizeRangeFilters(sizeKb?: number): { id: string; name: string; sortIndex?: number }[] {
|
||||
if (sizeKb == null) return [];
|
||||
const match = fileSizeRanges.find(r => sizeKb >= r.min && sizeKb < r.max);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
}
|
||||
|
||||
function getRatingRangeFilters(rating?: number): { id: string; name: string; sortIndex?: number }[] {
|
||||
if (rating == null) return [];
|
||||
const match = ratingRanges.find(r => rating >= r.min && rating < r.max);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
}
|
||||
|
||||
function getRatingRangeFilters10(rating?: number): { id: string; name: string; sortIndex?: number }[] {
|
||||
if (!rating || rating < 1 || rating > 10) return [];
|
||||
const idx = ratingOptions10.find(r => r.value === rating || +r.id === rating);
|
||||
return idx ? [{id: idx.id, name: idx.label, sortIndex: idx.sortIndex}] : [];
|
||||
}
|
||||
|
||||
function extractPublishedYearFilter(book: Book): { id: number; name: string }[] {
|
||||
const date = book.metadata?.publishedDate;
|
||||
if (!date) return [];
|
||||
const year = new Date(date).getFullYear();
|
||||
return [{id: year, name: year.toString()}];
|
||||
}
|
||||
|
||||
function getShelfStatusFilter(book: Book): { id: string; name: string }[] {
|
||||
const isShelved = book.shelves?.length! > 0;
|
||||
return [{id: isShelved ? 'shelved' : 'unshelved', name: isShelved ? 'Shelved' : 'Unshelved'}];
|
||||
}
|
||||
|
||||
function getPageCountRangeFilters(pageCount?: number): { id: string; name: string; sortIndex?: number }[] {
|
||||
if (pageCount == null) return [];
|
||||
const match = pageCountRanges.find(r => pageCount >= r.min && pageCount < r.max);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
}
|
||||
|
||||
function getMatchScoreRangeFilters(score?: number | null): { id: string; name: string; sortIndex?: number }[] {
|
||||
if (score == null) return [];
|
||||
const match = matchScoreRanges.find(r => score >= r.min && score < r.max);
|
||||
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
|
||||
}
|
||||
|
||||
export const readStatusLabels: Record<ReadStatus, string> = {
|
||||
[ReadStatus.UNREAD]: 'Unread',
|
||||
[ReadStatus.READING]: 'Reading',
|
||||
[ReadStatus.RE_READING]: 'Re-reading',
|
||||
[ReadStatus.PARTIALLY_READ]: 'Partially Read',
|
||||
[ReadStatus.PAUSED]: 'Paused',
|
||||
[ReadStatus.READ]: 'Read',
|
||||
[ReadStatus.WONT_READ]: 'Won’t Read',
|
||||
[ReadStatus.ABANDONED]: 'Abandoned',
|
||||
[ReadStatus.UNSET]: 'Unset'
|
||||
};
|
||||
|
||||
function getReadStatusName(status?: ReadStatus | null): string {
|
||||
return status != null ? readStatusLabels[status] ?? 'Unset' : 'Unset';
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-filter',
|
||||
templateUrl: './book-filter.component.html',
|
||||
styleUrls: ['./book-filter.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
standalone: true,
|
||||
imports: [
|
||||
Accordion,
|
||||
AccordionPanel,
|
||||
AccordionHeader,
|
||||
AccordionContent,
|
||||
NgClass,
|
||||
Badge,
|
||||
AsyncPipe,
|
||||
TitleCasePipe,
|
||||
FormsModule,
|
||||
SelectButton
|
||||
]
|
||||
})
|
||||
export class BookFilterComponent implements OnInit, OnDestroy {
|
||||
private filterChangeSubject = new Subject<Record<string, any> | null>();
|
||||
|
||||
@Output() filterSelected = new EventEmitter<Record<string, any> | null>();
|
||||
@Output() filterModeChanged = new EventEmitter<'and' | 'or'>();
|
||||
|
||||
@Input() entity$!: Observable<Library | Shelf | MagicShelf | null> | undefined;
|
||||
@Input() entityType$!: Observable<EntityType> | undefined;
|
||||
@Input() resetFilter$!: Subject<void>;
|
||||
@Input() showFilter: boolean = false;
|
||||
|
||||
activeFilters: Record<string, any> = {};
|
||||
filterStreams: Record<string, Observable<Filter<any>[]>> = {};
|
||||
truncatedFilters: Record<string, boolean> = {};
|
||||
filterTypes: string[] = [];
|
||||
filterModeOptions = [
|
||||
{label: 'AND', value: 'and'},
|
||||
{label: 'OR', value: 'or'}
|
||||
];
|
||||
private _selectedFilterMode: 'and' | 'or' = 'and';
|
||||
expandedPanels: number = 0;
|
||||
readonly filterLabels: Record<string, string> = {
|
||||
author: 'Author',
|
||||
category: 'Genre',
|
||||
series: 'Series',
|
||||
publisher: 'Publisher',
|
||||
readStatus: 'Read Status',
|
||||
personalRating: 'Personal Rating',
|
||||
matchScore: 'Metadata Match Score',
|
||||
amazonRating: 'Amazon Rating',
|
||||
goodreadsRating: 'Goodreads Rating',
|
||||
hardcoverRating: 'Hardcover Rating',
|
||||
publishedDate: 'Published Year',
|
||||
fileSize: 'File Size',
|
||||
shelfStatus: 'Shelf Status',
|
||||
pageCount: 'Page Count',
|
||||
language: 'Language'
|
||||
};
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
bookService = inject(BookService);
|
||||
userService = inject(UserService);
|
||||
bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
|
||||
ngOnInit(): void {
|
||||
combineLatest([
|
||||
this.entity$ ?? of(null),
|
||||
this.entityType$ ?? of(EntityType.ALL_BOOKS)
|
||||
])
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(([sortMode]) => {
|
||||
this.filterStreams = {
|
||||
author: this.getFilterStream((book: Book) => book.metadata?.authors!.map(name => ({id: name, name})) || [], 'id', 'name'),
|
||||
category: this.getFilterStream((book: Book) => book.metadata?.categories!.map(name => ({id: name, name})) || [], 'id', 'name'),
|
||||
series: this.getFilterStream((book) => (book.metadata?.seriesName ? [{id: book.metadata.seriesName, name: book.metadata.seriesName}] : []), 'id', 'name'),
|
||||
publisher: this.getFilterStream((book) => (book.metadata?.publisher ? [{id: book.metadata.publisher, name: book.metadata.publisher}] : []), 'id', 'name'),
|
||||
readStatus: this.getFilterStream((book: Book) => {
|
||||
let status = book.readStatus;
|
||||
if (status == null || !(status in readStatusLabels)) {
|
||||
status = ReadStatus.UNSET;
|
||||
}
|
||||
return [{id: status, name: getReadStatusName(status)}];
|
||||
}, 'id', 'name'),
|
||||
mood: this.getFilterStream((book: Book) => book.metadata?.moods!.map(name => ({id: name, name})) || [], 'id', 'name'),
|
||||
tag: this.getFilterStream((book: Book) => book.metadata?.tags!.map(name => ({id: name, name})) || [], 'id', 'name'),
|
||||
matchScore: this.getFilterStream((book: Book) => getMatchScoreRangeFilters(book.metadataMatchScore), 'id', 'name', 'sortIndex'),
|
||||
personalRating: this.getFilterStream((book: Book) => getRatingRangeFilters10(book.metadata?.personalRating!), 'id', 'name', 'sortIndex'),
|
||||
amazonRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.amazonRating!), 'id', 'name', 'sortIndex'),
|
||||
goodreadsRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.goodreadsRating!), 'id', 'name', 'sortIndex'),
|
||||
hardcoverRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.hardcoverRating!), 'id', 'name', 'sortIndex'),
|
||||
shelfStatus: this.getFilterStream(getShelfStatusFilter, 'id', 'name'),
|
||||
publishedDate: this.getFilterStream(extractPublishedYearFilter, 'id', 'name'),
|
||||
language: this.getFilterStream(getLanguageFilter, 'id', 'name'),
|
||||
fileSize: this.getFilterStream((book: Book) => getFileSizeRangeFilters(book.fileSizeKb), 'id', 'name', 'sortIndex'),
|
||||
pageCount: this.getFilterStream((book: Book) => getPageCountRangeFilters(book.metadata?.pageCount!), 'id', 'name', 'sortIndex'),
|
||||
};
|
||||
|
||||
this.filterTypes = Object.keys(this.filterStreams);
|
||||
this.setExpandedPanels();
|
||||
});
|
||||
|
||||
this.filterChangeSubject.pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(value => this.filterSelected.emit(value));
|
||||
|
||||
if (this.resetFilter$) {
|
||||
this.resetFilter$.pipe(takeUntil(this.destroy$)).subscribe(() => this.clearActiveFilter());
|
||||
}
|
||||
}
|
||||
|
||||
private getFilterStream<T>(
|
||||
extractor: (book: Book) => T[] | undefined,
|
||||
idKey: keyof T,
|
||||
nameKey: keyof T,
|
||||
sortMode: 'count' | 'alphabetical' | 'sortIndex' = 'count'
|
||||
): Observable<Filter<T[keyof T]>[]> {
|
||||
return combineLatest([
|
||||
this.bookService.bookState$,
|
||||
this.entity$ ?? of(null),
|
||||
this.entityType$ ?? of(EntityType.ALL_BOOKS)
|
||||
]).pipe(
|
||||
map(([state, entity, entityType]) => {
|
||||
const filteredBooks = this.filterBooksByEntityType(state.books || [], entity, entityType);
|
||||
const filterMap = new Map<any, Filter<any>>();
|
||||
|
||||
filteredBooks.forEach((book) => {
|
||||
(extractor(book) || []).forEach((item) => {
|
||||
const id = item[idKey];
|
||||
if (!filterMap.has(id)) {
|
||||
filterMap.set(id, {value: item, bookCount: 0});
|
||||
}
|
||||
filterMap.get(id)!.bookCount += 1;
|
||||
});
|
||||
});
|
||||
|
||||
const result = Array.from(filterMap.values());
|
||||
|
||||
const sorted = result.sort((a, b) => {
|
||||
if (sortMode === 'sortIndex') {
|
||||
return (a.value.sortIndex ?? 999) - (b.value.sortIndex ?? 999);
|
||||
}
|
||||
return (
|
||||
b.bookCount - a.bookCount ||
|
||||
a.value[nameKey].toString().localeCompare(b.value[nameKey].toString())
|
||||
);
|
||||
});
|
||||
|
||||
const isTruncated = sorted.length > 500;
|
||||
const truncated = sorted.slice(0, 500);
|
||||
|
||||
return {items: truncated, isTruncated};
|
||||
}),
|
||||
map(({items, isTruncated}) => {
|
||||
setTimeout(() => {
|
||||
const filterType = Object.keys(this.filterStreams).find(key =>
|
||||
this.filterStreams[key] === this.getFilterStream(extractor, idKey, nameKey)
|
||||
);
|
||||
if (filterType) {
|
||||
this.truncatedFilters[filterType] = isTruncated;
|
||||
}
|
||||
});
|
||||
return items;
|
||||
}),
|
||||
shareReplay({bufferSize: 1, refCount: true})
|
||||
);
|
||||
}
|
||||
|
||||
get selectedFilterMode(): 'and' | 'or' {
|
||||
return this._selectedFilterMode;
|
||||
}
|
||||
|
||||
set selectedFilterMode(mode: 'and' | 'or') {
|
||||
this._selectedFilterMode = mode;
|
||||
this.filterModeChanged.emit(mode);
|
||||
this.filterChangeSubject.next(
|
||||
Object.keys(this.activeFilters).length ? {...this.activeFilters} : null
|
||||
);
|
||||
}
|
||||
|
||||
private filterBooksByEntityType(books: Book[], entity: any, entityType: EntityType): Book[] {
|
||||
if (entityType === EntityType.LIBRARY && entity && 'id' in entity) {
|
||||
return books.filter((book) => book.libraryId === entity.id);
|
||||
}
|
||||
|
||||
if (entityType === EntityType.SHELF && entity && 'id' in entity) {
|
||||
return books.filter((book) => book.shelves?.some((shelf) => shelf.id === entity.id));
|
||||
}
|
||||
|
||||
if (entityType === EntityType.MAGIC_SHELF && entity && 'filterJson' in entity) {
|
||||
try {
|
||||
const groupRule = JSON.parse(entity.filterJson) as GroupRule;
|
||||
return books.filter((book) => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule));
|
||||
} catch (e) {
|
||||
console.warn('Invalid filterJson for MagicShelf:', e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
return books;
|
||||
}
|
||||
|
||||
handleFilterClick(filterType: string, value: any): void {
|
||||
if (!this.activeFilters[filterType]) {
|
||||
this.activeFilters[filterType] = [];
|
||||
}
|
||||
|
||||
const index = this.activeFilters[filterType].indexOf(value);
|
||||
if (index > -1) {
|
||||
this.activeFilters[filterType].splice(index, 1);
|
||||
if (this.activeFilters[filterType].length === 0) {
|
||||
delete this.activeFilters[filterType];
|
||||
}
|
||||
} else {
|
||||
this.activeFilters[filterType].push(value);
|
||||
}
|
||||
|
||||
this.filterChangeSubject.next(Object.keys(this.activeFilters).length ? {...this.activeFilters} : null);
|
||||
}
|
||||
|
||||
setFilters(filters: Record<string, any>) {
|
||||
this.activeFilters = {};
|
||||
|
||||
for (const [key, value] of Object.entries(filters)) {
|
||||
if (Array.isArray(value)) {
|
||||
this.activeFilters[key] = [...value];
|
||||
} else {
|
||||
this.activeFilters[key] = [value];
|
||||
}
|
||||
}
|
||||
this.filterChangeSubject.next({...this.activeFilters});
|
||||
}
|
||||
|
||||
clearActiveFilter() {
|
||||
this.activeFilters = {};
|
||||
this.filterChangeSubject.next(null);
|
||||
}
|
||||
|
||||
setExpandedPanels(): void {
|
||||
const firstActiveIndex = this.filterTypes.findIndex(
|
||||
type => this.activeFilters[type]?.length
|
||||
);
|
||||
this.expandedPanels = firstActiveIndex !== -1 ? firstActiveIndex : 0;
|
||||
}
|
||||
|
||||
onFiltersChanged(): void {
|
||||
this.setExpandedPanels();
|
||||
}
|
||||
|
||||
trackByFilterType(_: number, type: string): string {
|
||||
return type;
|
||||
}
|
||||
|
||||
trackByFilter(_: number, filter: Filter<any>): any {
|
||||
return filter.value.id ?? filter.value;
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
<p-table
|
||||
[value]="books"
|
||||
[columns]="visibleColumns"
|
||||
[dataKey]="'id'"
|
||||
[resizableColumns]="true"
|
||||
[reorderableColumns]="true"
|
||||
columnResizeMode="expand"
|
||||
[rowTrackBy]="trackByBookId"
|
||||
[metaKeySelection]="true"
|
||||
showGridlines
|
||||
stripedRows
|
||||
[scrollable]="true"
|
||||
[scrollHeight]="scrollHeight"
|
||||
[virtualScroll]="true"
|
||||
[virtualScrollItemSize]="46"
|
||||
[(selection)]="selectedBooks"
|
||||
(onHeaderCheckboxToggle)="onHeaderCheckboxToggle($event)"
|
||||
(onRowSelect)="onRowSelect($event)"
|
||||
(onRowUnselect)="onRowUnselect($event)"
|
||||
>
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th>
|
||||
<p-tableHeaderCheckbox/>
|
||||
</th>
|
||||
<th></th>
|
||||
<th class="max-w-14 min-w-14"></th>
|
||||
@for (col of visibleColumns; track col.field) {
|
||||
<th pResizableColumn>{{ col.header }}</th>
|
||||
}
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="body" let-book>
|
||||
@if (book.metadata; as metadata) {
|
||||
<tr style="height:46px">
|
||||
<td>
|
||||
<p-tableCheckbox [value]="book"/>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<p-button
|
||||
[icon]="isMetadataFullyLocked(metadata) ? 'pi pi-lock' : 'pi pi-lock-open'"
|
||||
[severity]="isMetadataFullyLocked(metadata) ? 'danger' : 'success'"
|
||||
[text]="true"
|
||||
[title]="isMetadataFullyLocked(metadata) ? 'Locked' : 'Unlocked'"
|
||||
size="small"
|
||||
[style]="{ width: '1.5rem', height: '1.5rem', padding: '0', fontSize: '0.75rem' }"
|
||||
(click)="toggleMetadataLock(metadata)">
|
||||
</p-button>
|
||||
</td>
|
||||
<td (click)="openMetadataCenter(book.id)" class="cursor-pointer">
|
||||
<img [attr.src]="urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn)" alt="Book Cover" class="size-7"/>
|
||||
</td>
|
||||
|
||||
@for (col of visibleColumns; track col.field) {
|
||||
@if (col.field === 'readStatus') {
|
||||
<td class="text-center min-w-[4rem] max-w-[4rem]">
|
||||
@if (shouldShowStatusIcon(book.readStatus)) {
|
||||
<div class="read-status-indicator"
|
||||
[ngClass]="getReadStatusClass(book.readStatus)"
|
||||
[pTooltip]="'Status: ' + getReadStatusTooltip(book.readStatus)"
|
||||
tooltipPosition="top">
|
||||
<i [class]="getReadStatusIcon(book.readStatus)"></i>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
} @else if (col.field === 'amazonRating' || col.field === 'goodreadsRating' || col.field === 'hardcoverRating') {
|
||||
<td class="min-w-[10rem] max-w-[10rem] overflow-hidden truncate">
|
||||
<span class="flex items-center gap-1">
|
||||
<p-rating
|
||||
[(ngModel)]="metadata[col.field]"
|
||||
readonly
|
||||
stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata[col.field])"
|
||||
></p-rating>
|
||||
@if (metadata[col.field] != null) {
|
||||
<span>({{ metadata[col.field]?.toFixed(1) }})</span>
|
||||
}
|
||||
</span>
|
||||
</td>
|
||||
} @else {
|
||||
<td [title]="getCellValue(metadata, book, col.field)"
|
||||
class="overflow-hidden truncate text-right min-w-[6rem] max-w-[12rem]">
|
||||
{{ getCellValue(metadata, book, col.field) }}
|
||||
</td>
|
||||
}
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</ng-template>
|
||||
</p-table>
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
.read-status-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 0.875rem;
|
||||
font-weight: bold;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.status-read {
|
||||
color: #22c55e;
|
||||
}
|
||||
|
||||
.status-reading {
|
||||
color: #3b82f6;
|
||||
}
|
||||
|
||||
.status-re-reading {
|
||||
color: #06b6d4;
|
||||
}
|
||||
|
||||
.status-partially-read {
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.status-paused {
|
||||
color: #eab308;
|
||||
}
|
||||
|
||||
.status-abandoned {
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.status-wont-read {
|
||||
color: #ec4899;
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
import {Component, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output} from '@angular/core';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {DatePipe, NgClass} from '@angular/common';
|
||||
import {Rating} from 'primeng/rating';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {TooltipModule} from "primeng/tooltip";
|
||||
import {Book, BookMetadata, ReadStatus} from '../../../model/book.model';
|
||||
import {SortOption} from '../../../model/sort.model';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Router} from '@angular/router';
|
||||
import {filter, Subject} from 'rxjs';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {BookMetadataCenterComponent} from '../../../../metadata/component/book-metadata-center-component/book-metadata-center.component';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {take, takeUntil} from 'rxjs/operators';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-table',
|
||||
standalone: true,
|
||||
templateUrl: './book-table.component.html',
|
||||
imports: [
|
||||
TableModule,
|
||||
Rating,
|
||||
FormsModule,
|
||||
Button,
|
||||
TooltipModule,
|
||||
NgClass
|
||||
],
|
||||
styleUrls: ['./book-table.component.scss'],
|
||||
providers: [DatePipe]
|
||||
})
|
||||
export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
selectedBooks: Book[] = [];
|
||||
selectedBookIds = new Set<number>();
|
||||
|
||||
@Output() selectedBooksChange = new EventEmitter<Set<number>>();
|
||||
@Input() books: Book[] = [];
|
||||
@Input() sortOption: SortOption | null = null;
|
||||
@Input() visibleColumns: any[] = [];
|
||||
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private bookService = inject(BookService);
|
||||
private messageService = inject(MessageService);
|
||||
private userService = inject(UserService);
|
||||
private dialogService = inject(DialogService);
|
||||
private router = inject(Router);
|
||||
private datePipe = inject(DatePipe);
|
||||
private readStatusHelper = inject(ReadStatusHelper);
|
||||
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
readonly allColumns = [
|
||||
{field: 'readStatus', header: '📖'},
|
||||
{field: 'title', header: 'Title'},
|
||||
{field: 'authors', header: 'Authors'},
|
||||
{field: 'publisher', header: 'Publisher'},
|
||||
{field: 'seriesName', header: 'Series'},
|
||||
{field: 'seriesNumber', header: 'Series #'},
|
||||
{field: 'categories', header: 'Genres'},
|
||||
{field: 'publishedDate', header: 'Published'},
|
||||
{field: 'lastReadTime', header: 'Last Read'},
|
||||
{field: 'addedOn', header: 'Added'},
|
||||
{field: 'fileSizeKb', header: 'File Size'},
|
||||
{field: 'language', header: 'Language'},
|
||||
{field: 'pageCount', header: 'Pages'},
|
||||
{field: 'amazonRating', header: 'Amazon'},
|
||||
{field: 'amazonReviewCount', header: 'AZ #'},
|
||||
{field: 'goodreadsRating', header: 'Goodreads'},
|
||||
{field: 'goodreadsReviewCount', header: 'GR #'},
|
||||
{field: 'hardcoverRating', header: 'Hardcover'},
|
||||
{field: 'hardcoverReviewCount', header: 'HC #'}
|
||||
];
|
||||
|
||||
scrollHeight = 'calc(100dvh - 160px)';
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(userState => {
|
||||
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
});
|
||||
|
||||
this.setScrollHeight();
|
||||
window.addEventListener('resize', this.setScrollHeight.bind(this));
|
||||
}
|
||||
|
||||
setScrollHeight() {
|
||||
const isMobile = window.innerWidth <= 768;
|
||||
this.scrollHeight = isMobile
|
||||
? 'calc(100dvh - 125px)'
|
||||
: 'calc(100dvh - 150px)';
|
||||
}
|
||||
|
||||
ngOnChanges() {
|
||||
const wrapperElements: HTMLCollection = document.getElementsByClassName('p-virtualscroller');
|
||||
Array.prototype.forEach.call(wrapperElements, function (wrapperElement) {
|
||||
wrapperElement.style["height"] = 'calc(100dvh - 160px)';
|
||||
});
|
||||
}
|
||||
|
||||
selectAllBooks(): void {
|
||||
this.selectedBookIds = new Set(this.books.map(book => book.id));
|
||||
this.selectedBooks = [...this.books];
|
||||
this.selectedBooksChange.emit(this.selectedBookIds);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
openMetadataCenter(id: number): void {
|
||||
if (this.metadataCenterViewMode === 'route') {
|
||||
this.router.navigate(['/book', id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
} else {
|
||||
this.dialogService.open(BookMetadataCenterComponent, {
|
||||
width: '95%',
|
||||
data: {bookId: id},
|
||||
modal: true,
|
||||
dismissableMask: true,
|
||||
showHeader: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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)';
|
||||
}
|
||||
}
|
||||
|
||||
getAuthorNames(authors: string[]): string {
|
||||
return authors?.join(', ') || '';
|
||||
}
|
||||
|
||||
getGenres(genres: string[]) {
|
||||
return genres?.join(', ') || '';
|
||||
}
|
||||
|
||||
trackByBookId(index: number, book: Book): number {
|
||||
return book.id;
|
||||
}
|
||||
|
||||
isMetadataFullyLocked(metadata: BookMetadata): boolean {
|
||||
const lockedKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
|
||||
if (lockedKeys.length === 0) return false;
|
||||
return lockedKeys.every(key => metadata[key] === true);
|
||||
}
|
||||
|
||||
formatFileSize(kb?: number): string {
|
||||
if (kb == null || isNaN(kb)) return '-';
|
||||
const mb = kb / 1024;
|
||||
return mb >= 1 ? `${mb.toFixed(1)} MB` : `${mb.toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
getReadStatusIcon(readStatus: ReadStatus | undefined): string {
|
||||
return this.readStatusHelper.getReadStatusIcon(readStatus);
|
||||
}
|
||||
|
||||
getReadStatusClass(readStatus: ReadStatus | undefined): string {
|
||||
return this.readStatusHelper.getReadStatusClass(readStatus);
|
||||
}
|
||||
|
||||
getReadStatusTooltip(readStatus: ReadStatus | undefined): string {
|
||||
return this.readStatusHelper.getReadStatusTooltip(readStatus);
|
||||
}
|
||||
|
||||
shouldShowStatusIcon(readStatus: ReadStatus | undefined): boolean {
|
||||
return this.readStatusHelper.shouldShowStatusIcon(readStatus);
|
||||
}
|
||||
|
||||
getCellValue(metadata: BookMetadata, book: Book, field: string): string | number {
|
||||
switch (field) {
|
||||
case 'readStatus':
|
||||
return this.readStatusHelper.getReadStatusTooltip(book?.readStatus);
|
||||
|
||||
case 'title':
|
||||
return metadata.title ?? '';
|
||||
|
||||
case 'authors':
|
||||
return this.getAuthorNames(metadata.authors!);
|
||||
|
||||
case 'publisher':
|
||||
return metadata.publisher ?? '';
|
||||
|
||||
case 'seriesName':
|
||||
return metadata.seriesName ?? '';
|
||||
|
||||
case 'seriesNumber':
|
||||
return metadata.seriesNumber ?? '';
|
||||
|
||||
case 'categories':
|
||||
return this.getGenres(metadata.categories!);
|
||||
|
||||
case 'publishedDate':
|
||||
return metadata.publishedDate ? this.datePipe.transform(metadata.publishedDate, 'dd-MMM-yyyy') ?? '' : '';
|
||||
|
||||
case 'lastReadTime':
|
||||
return book.lastReadTime ? this.datePipe.transform(book.lastReadTime, 'dd-MMM-yyyy') ?? '' : '';
|
||||
|
||||
case 'addedOn':
|
||||
return book.addedOn ? this.datePipe.transform(book.addedOn, 'dd-MMM-yyyy') ?? '' : '';
|
||||
|
||||
case 'fileSizeKb':
|
||||
return this.formatFileSize(book.fileSizeKb);
|
||||
|
||||
case 'language':
|
||||
return metadata.language ?? '';
|
||||
|
||||
case 'pageCount':
|
||||
return metadata.pageCount ?? '';
|
||||
|
||||
case 'amazonRating':
|
||||
case 'goodreadsRating':
|
||||
case 'hardcoverRating': {
|
||||
const rating = metadata[field];
|
||||
return typeof rating === 'number' ? rating.toFixed(1) : '';
|
||||
}
|
||||
|
||||
case 'amazonReviewCount':
|
||||
case 'goodreadsReviewCount':
|
||||
case 'hardcoverReviewCount':
|
||||
return metadata[field] ?? '';
|
||||
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
toggleMetadataLock(metadata: BookMetadata): void {
|
||||
const lockKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
|
||||
const allLocked = lockKeys.every(key => metadata[key] === true);
|
||||
const lockAction = allLocked ? 'UNLOCK' : 'LOCK';
|
||||
|
||||
this.bookService.toggleAllLock(new Set([metadata.bookId]), lockAction).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: `Metadata ${lockAction === 'LOCK' ? 'Locked' : 'Unlocked'}`,
|
||||
detail: `Book metadata has been ${lockAction === 'LOCK' ? 'locked' : 'unlocked'} successfully.`,
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: `Failed to ${lockAction === 'LOCK' ? 'Lock' : 'Unlock'}`,
|
||||
detail: `An error occurred while ${lockAction === 'LOCK' ? 'locking' : 'unlocking'} the metadata.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
window.removeEventListener('resize', this.setScrollHeight.bind(this));
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Subject} from 'rxjs';
|
||||
import {debounceTime} from 'rxjs/operators';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {LocalStorageService} from '../../../../shared/service/local-storage-service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class CoverScalePreferenceService {
|
||||
|
||||
private readonly BASE_WIDTH = 135;
|
||||
private readonly BASE_HEIGHT = 220;
|
||||
private readonly DEBOUNCE_MS = 1000;
|
||||
private readonly STORAGE_KEY = 'coverScalePreference';
|
||||
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly localStorageService = inject(LocalStorageService);
|
||||
|
||||
private readonly scaleChangeSubject = new Subject<number>();
|
||||
readonly scaleChange$ = this.scaleChangeSubject.asObservable();
|
||||
|
||||
scaleFactor = 1.0;
|
||||
|
||||
constructor() {
|
||||
this.loadScaleFromStorage();
|
||||
|
||||
this.scaleChange$
|
||||
.pipe(debounceTime(this.DEBOUNCE_MS))
|
||||
.subscribe(scale => this.saveScalePreference(scale));
|
||||
}
|
||||
|
||||
initScaleValue(scale: number | undefined): void {
|
||||
this.scaleFactor = scale ?? 1.0;
|
||||
}
|
||||
|
||||
setScale(scale: number): void {
|
||||
this.scaleFactor = scale;
|
||||
this.scaleChangeSubject.next(scale);
|
||||
}
|
||||
|
||||
get currentCardSize(): { width: number; height: number } {
|
||||
return {
|
||||
width: Math.round(this.BASE_WIDTH * this.scaleFactor),
|
||||
height: Math.round(this.BASE_HEIGHT * this.scaleFactor),
|
||||
};
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return `${this.currentCardSize.width}px`;
|
||||
}
|
||||
|
||||
private saveScalePreference(scale: number): void {
|
||||
try {
|
||||
this.localStorageService.set(this.STORAGE_KEY, scale);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Cover Size Saved',
|
||||
detail: `Cover size set to ${scale.toFixed(2)}x.`,
|
||||
life: 1500
|
||||
});
|
||||
} catch (e) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Save Failed',
|
||||
detail: 'Could not save cover size preference locally.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private loadScaleFromStorage(): void {
|
||||
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
|
||||
if (saved !== null && !isNaN(saved)) {
|
||||
this.scaleFactor = saved;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {Observable} from 'rxjs';
|
||||
|
||||
export interface BookFilter {
|
||||
filter(bookState: BookState): Observable<BookState>;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {Observable, of} from 'rxjs';
|
||||
import {map, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
|
||||
|
||||
export class HeaderFilter implements BookFilter {
|
||||
|
||||
constructor(private searchTerm$: Observable<any>) {
|
||||
}
|
||||
|
||||
filter(bookState: BookState): Observable<BookState> {
|
||||
const normalize = (str: string): string =>
|
||||
str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
|
||||
|
||||
return this.searchTerm$.pipe(
|
||||
distinctUntilChanged(),
|
||||
switchMap(term => {
|
||||
const normalizedTerm = normalize(term || '').trim();
|
||||
if (normalizedTerm.length < 2) {
|
||||
return of(bookState);
|
||||
}
|
||||
return of(normalizedTerm).pipe(
|
||||
debounceTime(500),
|
||||
map(nTerm => {
|
||||
const filteredBooks = bookState.books?.filter(book => {
|
||||
const title = book.metadata?.title || '';
|
||||
const series = book.metadata?.seriesName || '';
|
||||
const authors = book.metadata?.authors || [];
|
||||
const categories = book.metadata?.categories || [];
|
||||
const isbn = book.metadata?.isbn10 || '';
|
||||
const isbn13 = book.metadata?.isbn13 || '';
|
||||
|
||||
const matchesTitle = normalize(title).includes(nTerm);
|
||||
const matchesSeries = normalize(series).includes(nTerm);
|
||||
const matchesAuthor = authors.some(author => normalize(author).includes(nTerm));
|
||||
const matchesCategory = categories.some(category => normalize(category).includes(nTerm));
|
||||
const matchesIsbn = normalize(isbn).includes(nTerm) || normalize(isbn13).includes(nTerm);
|
||||
|
||||
return matchesTitle || matchesSeries || matchesAuthor || matchesCategory || matchesIsbn;
|
||||
}) || null;
|
||||
|
||||
return {...bookState, books: filteredBooks};
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {BehaviorSubject, Observable, Subject} from 'rxjs';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {debounceTime, filter, map, take, takeUntil} from 'rxjs/operators';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class SeriesCollapseFilter implements BookFilter, OnDestroy {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
|
||||
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
|
||||
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
private hasUserToggled = false;
|
||||
|
||||
constructor() {
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(user => {
|
||||
const prefs = user.user?.userSettings?.entityViewPreferences;
|
||||
const initialCollapsed = prefs?.global?.seriesCollapsed ?? false;
|
||||
this.seriesCollapseSubject.next(initialCollapsed);
|
||||
});
|
||||
|
||||
this.seriesCollapse$
|
||||
.pipe(debounceTime(500))
|
||||
.subscribe(isCollapsed => {
|
||||
if (this.hasUserToggled) {
|
||||
this.persistCollapsePreference(isCollapsed);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get isSeriesCollapsed(): boolean {
|
||||
return this.seriesCollapseSubject.value;
|
||||
}
|
||||
|
||||
setCollapsed(value: boolean): void {
|
||||
this.hasUserToggled = true;
|
||||
this.seriesCollapseSubject.next(value);
|
||||
}
|
||||
|
||||
filter(bookState: BookState, forceExpandSeries?: boolean): Observable<BookState> {
|
||||
return this.seriesCollapse$.pipe(
|
||||
map(isCollapsed => {
|
||||
const shouldCollapse = forceExpandSeries ? false : isCollapsed;
|
||||
if (!shouldCollapse || !bookState.books) return bookState;
|
||||
|
||||
const books = [...bookState.books];
|
||||
|
||||
const seriesMap = new Map<string, Book[]>();
|
||||
const collapsedBooks: Book[] = [];
|
||||
|
||||
for (const book of books) {
|
||||
const seriesName = book.metadata?.seriesName?.trim();
|
||||
if (seriesName) {
|
||||
if (!seriesMap.has(seriesName)) {
|
||||
seriesMap.set(seriesName, []);
|
||||
}
|
||||
seriesMap.get(seriesName)!.push(book);
|
||||
} else {
|
||||
collapsedBooks.push(book);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [seriesName, group] of seriesMap.entries()) {
|
||||
const sortedGroup = group.slice().sort((a, b) => {
|
||||
const aNum = a.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||
const bNum = b.metadata?.seriesNumber ?? Number.MAX_VALUE;
|
||||
return aNum - bNum;
|
||||
});
|
||||
const firstBook = sortedGroup[0];
|
||||
collapsedBooks.push({
|
||||
...firstBook,
|
||||
seriesCount: group.length
|
||||
});
|
||||
}
|
||||
|
||||
return {...bookState, books: collapsedBooks};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private persistCollapsePreference(isCollapsed: boolean): void {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const prefs = user?.userSettings?.entityViewPreferences;
|
||||
if (!user || !prefs) return;
|
||||
|
||||
prefs.global = prefs.global ?? {};
|
||||
prefs.global.seriesCollapsed = isCollapsed;
|
||||
|
||||
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved',
|
||||
detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}.`,
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import {Observable, combineLatest, of} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.component';
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
|
||||
export function isRatingInRange(rating: number | undefined | null, rangeId: string): boolean {
|
||||
if (rating == null) return false;
|
||||
const range = ratingRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return rating >= range.min && rating < range.max;
|
||||
}
|
||||
|
||||
export function isRatingInRange10(rating: number | undefined | null, rangeId: string): boolean {
|
||||
if (rating == null) return false;
|
||||
return `${Math.round(rating)}` === rangeId;
|
||||
}
|
||||
|
||||
export function isFileSizeInRange(fileSizeKb: number | undefined, rangeId: string): boolean {
|
||||
if (fileSizeKb == null) return false;
|
||||
const range = fileSizeRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return fileSizeKb >= range.min && fileSizeKb < range.max;
|
||||
}
|
||||
|
||||
export function isPageCountInRange(pageCount: number | undefined, rangeId: string): boolean {
|
||||
if (pageCount == null) return false;
|
||||
const range = pageCountRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return pageCount >= range.min && pageCount < range.max;
|
||||
}
|
||||
|
||||
export function isMatchScoreInRange(score: number | undefined | null, rangeId: string): boolean {
|
||||
if (score == null) return false;
|
||||
const range = matchScoreRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return score >= range.min && score < range.max;
|
||||
}
|
||||
|
||||
export function doesBookMatchReadStatus(book: Book, selected: string[]): boolean {
|
||||
const status = book.readStatus ?? ReadStatus.UNSET;
|
||||
return selected.includes(status);
|
||||
}
|
||||
|
||||
export class SideBarFilter implements BookFilter {
|
||||
|
||||
constructor(private selectedFilter$: Observable<any>, private selectedFilterMode$: Observable<'and' | 'or'>) {
|
||||
}
|
||||
|
||||
filter(bookState: BookState): Observable<BookState> {
|
||||
return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe(
|
||||
map(([activeFilters, mode]) => {
|
||||
if (!activeFilters) return bookState;
|
||||
const filteredBooks = (bookState.books || []).filter(book => {
|
||||
const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => {
|
||||
if (!Array.isArray(filterValues) || filterValues.length === 0) {
|
||||
return mode === 'or';
|
||||
}
|
||||
switch (filterType) {
|
||||
case 'author':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.authors?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.authors?.includes(val));
|
||||
case 'category':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.categories?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.categories?.includes(val));
|
||||
case 'mood':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.moods?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.moods?.includes(val));
|
||||
case 'tag':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.tags?.includes(val))
|
||||
: filterValues.some(val => book.metadata?.tags?.includes(val));
|
||||
case 'publisher':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.publisher === val)
|
||||
: filterValues.some(val => book.metadata?.publisher === val);
|
||||
case 'series':
|
||||
return mode === 'and'
|
||||
? filterValues.every(val => book.metadata?.seriesName === val)
|
||||
: filterValues.some(val => book.metadata?.seriesName === val);
|
||||
case 'readStatus':
|
||||
return doesBookMatchReadStatus(book, filterValues);
|
||||
case 'amazonRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.amazonRating, range));
|
||||
case 'goodreadsRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.goodreadsRating, range));
|
||||
case 'hardcoverRating':
|
||||
return filterValues.some(range => isRatingInRange(book.metadata?.hardcoverRating, range));
|
||||
case 'personalRating':
|
||||
return filterValues.some(range => isRatingInRange10(book.metadata?.personalRating, range));
|
||||
case 'publishedDate':
|
||||
return filterValues.includes(new Date(book.metadata?.publishedDate || '').getFullYear());
|
||||
case 'fileSize':
|
||||
return filterValues.some(range => isFileSizeInRange(book.fileSizeKb, range));
|
||||
case 'shelfStatus':
|
||||
const shelved = book.shelves && book.shelves.length > 0 ? 'shelved' : 'unshelved';
|
||||
return filterValues.includes(shelved);
|
||||
case 'pageCount':
|
||||
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range));
|
||||
case 'language':
|
||||
return filterValues.includes(book.metadata?.language);
|
||||
case 'matchScore':
|
||||
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range));
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return mode === 'and' ? matches.every(m => m) : matches.some(m => m);
|
||||
});
|
||||
return {...bookState, books: filteredBooks};
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {LocalStorageService} from '../../../../../shared/service/local-storage-service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SidebarFilterTogglePrefService {
|
||||
|
||||
private readonly STORAGE_KEY = 'showSidebarFilter';
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly localStorageService = inject(LocalStorageService);
|
||||
|
||||
private readonly showFilterSubject = new BehaviorSubject<boolean>(true);
|
||||
readonly showFilter$ = this.showFilterSubject.asObservable();
|
||||
|
||||
constructor() {
|
||||
const isNarrow = window.innerWidth <= 768;
|
||||
this.showFilterSubject = new BehaviorSubject<boolean>(!isNarrow);
|
||||
this.showFilter$ = this.showFilterSubject.asObservable();
|
||||
this.loadFromStorage();
|
||||
}
|
||||
|
||||
get selectedShowFilter(): boolean {
|
||||
return this.showFilterSubject.value;
|
||||
}
|
||||
|
||||
set selectedShowFilter(value: boolean) {
|
||||
if (this.showFilterSubject.value !== value) {
|
||||
this.showFilterSubject.next(value);
|
||||
this.savePreference(value);
|
||||
}
|
||||
}
|
||||
|
||||
toggle(): void {
|
||||
this.selectedShowFilter = !this.selectedShowFilter;
|
||||
}
|
||||
|
||||
private savePreference(value: boolean): void {
|
||||
try {
|
||||
this.localStorageService.set(this.STORAGE_KEY, value);
|
||||
} catch (e) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Save Failed',
|
||||
detail: 'Could not save sidebar filter preference locally.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private loadFromStorage(): void {
|
||||
const isNarrow = window.innerWidth <= 768;
|
||||
if (isNarrow) {
|
||||
this.showFilterSubject.next(false);
|
||||
} else {
|
||||
const saved = this.localStorageService.get<boolean>(this.STORAGE_KEY);
|
||||
this.showFilterSubject.next(saved !== null ? saved : true);
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
<div class="p-4">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-24 gap-y-4">
|
||||
@for (field of lockableFields; track field) {
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="capitalize">{{ fieldLabels[field] || field }}</label>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
[label]="getLockLabel(field)"
|
||||
[icon]="getLockIcon(field)"
|
||||
[severity]="fieldLocks[field] === true ? 'danger' : fieldLocks[field] === false ? 'success' : 'secondary'"
|
||||
(click)="cycleLockState(field)"
|
||||
></p-button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="flex justify-end px-4 pt-4">
|
||||
<p-button icon="pi pi-refresh" label="Reset" outlined="true" severity="warn" (onClick)="resetFieldLocks()"></p-button>
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<div class="flex gap-4 justify-center">
|
||||
<p-button icon="pi pi-lock" label="Lock All" outlined="true" severity="danger" (onClick)="toggleLockAll('LOCK')"></p-button>
|
||||
<p-button icon="pi pi-lock-open" label="Unlock All" outlined="true" severity="success" (onClick)="toggleLockAll('UNLOCK')"></p-button>
|
||||
</div>
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<p-button [label]="isSaving ? 'Saving...' : 'Save'" [outlined]="true" icon="pi pi-check" severity="info" (onClick)="applyFieldLocks()" [disabled]="bookIds.size === 0 || isSaving"></p-button>
|
||||
</div>
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {Divider} from 'primeng/divider';
|
||||
|
||||
@Component({
|
||||
selector: 'app-lock-unlock-metadata-dialog',
|
||||
standalone: true,
|
||||
imports: [
|
||||
Button,
|
||||
FormsModule,
|
||||
Divider
|
||||
],
|
||||
templateUrl: './lock-unlock-metadata-dialog.component.html',
|
||||
styleUrl: './lock-unlock-metadata-dialog.component.scss'
|
||||
})
|
||||
export class LockUnlockMetadataDialogComponent implements OnInit {
|
||||
private bookService = inject(BookService);
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
private dialogRef = inject(DynamicDialogRef);
|
||||
private messageService = inject(MessageService);
|
||||
fieldLocks: Record<string, boolean | undefined> = {};
|
||||
|
||||
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
|
||||
|
||||
lockableFields: string[] = [
|
||||
'titleLocked', 'subtitleLocked', 'publisherLocked', 'publishedDateLocked', 'descriptionLocked',
|
||||
'isbn13Locked', 'isbn10Locked', 'asinLocked', 'pageCountLocked', 'thumbnailLocked', 'languageLocked', 'coverLocked',
|
||||
'seriesNameLocked', 'seriesNumberLocked', 'seriesTotalLocked', 'authorsLocked', 'categoriesLocked', 'moodsLocked', 'TagsLocked',
|
||||
'amazonRatingLocked', 'amazonReviewCountLocked', 'goodreadsRatingLocked', 'goodreadsReviewCountLocked',
|
||||
'hardcoverRatingLocked', 'hardcoverReviewCountLocked', 'goodreadsIdLocked', 'hardcoverIdLocked', 'googleIdLocked', 'comicvineIdLocked'
|
||||
];
|
||||
|
||||
fieldLabels: Record<string, string> = {
|
||||
titleLocked: 'Title',
|
||||
subtitleLocked: 'Subtitle',
|
||||
publisherLocked: 'Publisher',
|
||||
publishedDateLocked: 'Date',
|
||||
descriptionLocked: 'Description',
|
||||
isbn13Locked: 'ISBN-13',
|
||||
isbn10Locked: 'ISBN-10',
|
||||
asinLocked: 'ASIN',
|
||||
pageCountLocked: 'Page Count',
|
||||
thumbnailLocked: 'Thumbnail',
|
||||
languageLocked: 'Language',
|
||||
coverLocked: 'Cover',
|
||||
seriesNameLocked: 'Series',
|
||||
seriesNumberLocked: 'Series #',
|
||||
seriesTotalLocked: 'Series Total #',
|
||||
authorsLocked: 'Authors',
|
||||
categoriesLocked: 'Genres',
|
||||
moodsLocked: 'Moods',
|
||||
tagsLocked: 'Tags',
|
||||
amazonRatingLocked: 'Amazon ★',
|
||||
amazonReviewCountLocked: 'Amazon Reviews',
|
||||
goodreadsRatingLocked: 'Goodreads ★',
|
||||
goodreadsReviewCountLocked: 'Goodreads Reviews',
|
||||
hardcoverRatingLocked: 'Hardcover ★',
|
||||
hardcoverReviewCountLocked: 'Hardcover Reviews',
|
||||
goodreadsIdLocked: 'Goodreads ID',
|
||||
hardcoverIdLocked: 'Hardcover ID',
|
||||
googleIdLocked: 'Google ID',
|
||||
comicvineIdLocked: 'Comicvine ID',
|
||||
};
|
||||
|
||||
isSaving = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.lockableFields.forEach(field => this.fieldLocks[field] = undefined);
|
||||
}
|
||||
|
||||
toggleLockAll(action: 'LOCK' | 'UNLOCK'): void {
|
||||
const lockState = action === 'LOCK' ? true : false;
|
||||
this.lockableFields.forEach(field => {
|
||||
this.fieldLocks[field] = lockState;
|
||||
});
|
||||
}
|
||||
|
||||
getLockLabel(field: string): string {
|
||||
const state = this.fieldLocks[field];
|
||||
if (state === undefined) return 'Unselected';
|
||||
return state ? 'Locked' : 'Unlocked';
|
||||
}
|
||||
|
||||
getLockIcon(field: string): string {
|
||||
const state = this.fieldLocks[field];
|
||||
return state === undefined ? '' : state ? 'pi pi-lock' : 'pi pi-lock-open';
|
||||
}
|
||||
|
||||
resetFieldLocks(): void {
|
||||
this.lockableFields.forEach(field => {
|
||||
this.fieldLocks[field] = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
cycleLockState(field: string): void {
|
||||
const current = this.fieldLocks[field];
|
||||
if (current === undefined) {
|
||||
this.fieldLocks[field] = true;
|
||||
} else if (current) {
|
||||
this.fieldLocks[field] = false;
|
||||
} else {
|
||||
this.fieldLocks[field] = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
applyFieldLocks(): void {
|
||||
const fieldActions: Record<string, 'LOCK' | 'UNLOCK'> = {};
|
||||
for (const [field, locked] of Object.entries(this.fieldLocks)) {
|
||||
if (locked !== undefined) {
|
||||
fieldActions[field] = locked ? 'LOCK' : 'UNLOCK';
|
||||
}
|
||||
}
|
||||
|
||||
this.isSaving = true;
|
||||
this.bookService.toggleFieldLocks(this.bookIds, fieldActions).subscribe({
|
||||
next: () => {
|
||||
this.isSaving = false;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Field Locks Updated',
|
||||
detail: 'Selected metadata fields have been updated successfully.'
|
||||
});
|
||||
this.dialogRef.close('fields-updated');
|
||||
},
|
||||
error: () => {
|
||||
this.isSaving = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed to Update Field Locks',
|
||||
detail: 'An error occurred while updating field lock statuses.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
<div class="p-4 w-[54rem]">
|
||||
<p class="mb-4 text-gray-300">
|
||||
This will restore the embedded metadata and cover (if available) from a saved backup for the selected book.
|
||||
</p>
|
||||
|
||||
@if (book) {
|
||||
<div class="mb-4">
|
||||
<p class="font-semibold text-gray-300 pb-2">Book to Restore:</p>
|
||||
<div class="border p-3 rounded space-y-1 custom-table">
|
||||
<div><strong>ID:</strong> {{ book.id }}</div>
|
||||
<div><strong>Current Title:</strong> {{ book.metadata?.title }}</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (backupMetadata) {
|
||||
<div class="mb-4">
|
||||
<p class="font-semibold text-gray-300 pb-2">Backup Metadata Preview:</p>
|
||||
<div class="p-6 rounded custom-table text-sm text-gray-400 flex flex-col gap-6">
|
||||
|
||||
<div class="flex">
|
||||
<div class="flex-1 space-y-1">
|
||||
@if (backupMetadata.title) {
|
||||
<div><strong>Title:</strong> {{ backupMetadata.title }}</div>
|
||||
}
|
||||
@if (backupMetadata.subtitle) {
|
||||
<div><strong>Subtitle:</strong> {{ backupMetadata.subtitle }}</div>
|
||||
}
|
||||
@if (backupMetadata.authors!.length) {
|
||||
<div><strong>Authors:</strong> {{ backupMetadata.authors!.join(', ') }}</div>
|
||||
}
|
||||
@if (backupMetadata.publisher) {
|
||||
<div><strong>Publisher:</strong> {{ backupMetadata.publisher }}</div>
|
||||
}
|
||||
@if (backupMetadata.publishedDate) {
|
||||
<div><strong>Published Date:</strong> {{ backupMetadata.publishedDate }}</div>
|
||||
}
|
||||
@if (backupMetadata.seriesName) {
|
||||
<div><strong>Series Name:</strong> {{ backupMetadata.seriesName }}</div>
|
||||
}
|
||||
@if (backupMetadata.seriesNumber !== null) {
|
||||
<div><strong>Series Number:</strong> {{ backupMetadata.seriesNumber }}</div>
|
||||
}
|
||||
@if (backupMetadata.seriesTotal !== null) {
|
||||
<div><strong>Series Total:</strong> {{ backupMetadata.seriesTotal }}</div>
|
||||
}
|
||||
@if (backupMetadata.isbn13) {
|
||||
<div><strong>ISBN-13:</strong> {{ backupMetadata.isbn13 }}</div>
|
||||
}
|
||||
@if (backupMetadata.isbn10) {
|
||||
<div><strong>ISBN-10:</strong> {{ backupMetadata.isbn10 }}</div>
|
||||
}
|
||||
@if (backupMetadata.pageCount !== null) {
|
||||
<div><strong>Page Count:</strong> {{ backupMetadata.pageCount }}</div>
|
||||
}
|
||||
@if (backupMetadata.language) {
|
||||
<div><strong>Language:</strong> {{ backupMetadata.language }}</div>
|
||||
}
|
||||
@if (backupMetadata.asin) {
|
||||
<div><strong>ASIN:</strong> {{ backupMetadata.asin }}</div>
|
||||
}
|
||||
@if (backupMetadata.amazonRating !== null) {
|
||||
<div><strong>Amazon Rating:</strong> {{ backupMetadata.amazonRating }}</div>
|
||||
}
|
||||
@if (backupMetadata.amazonReviewCount !== null) {
|
||||
<div><strong>Amazon Review Count:</strong> {{ backupMetadata.amazonReviewCount }}</div>
|
||||
}
|
||||
@if (backupMetadata.comicvineId) {
|
||||
<div><strong>Comicvine ID:</strong> {{ backupMetadata.comicvineId }}</div>
|
||||
}
|
||||
@if (backupMetadata.goodreadsId) {
|
||||
<div><strong>Goodreads ID:</strong> {{ backupMetadata.goodreadsId }}</div>
|
||||
}
|
||||
@if (backupMetadata.goodreadsRating !== null) {
|
||||
<div><strong>Goodreads Rating:</strong> {{ backupMetadata.goodreadsRating }}</div>
|
||||
}
|
||||
@if (backupMetadata.goodreadsReviewCount !== null) {
|
||||
<div><strong>Goodreads Review Count:</strong> {{ backupMetadata.goodreadsReviewCount }}</div>
|
||||
}
|
||||
@if (backupMetadata.hardcoverId) {
|
||||
<div><strong>Hardcover ID:</strong> {{ backupMetadata.hardcoverId }}</div>
|
||||
}
|
||||
@if (backupMetadata.hardcoverRating !== null) {
|
||||
<div><strong>Hardcover Rating:</strong> {{ backupMetadata.hardcoverRating }}</div>
|
||||
}
|
||||
@if (backupMetadata.hardcoverReviewCount !== null) {
|
||||
<div><strong>Hardcover Review Count:</strong> {{ backupMetadata.hardcoverReviewCount }}</div>
|
||||
}
|
||||
@if (backupMetadata.googleId) {
|
||||
<div><strong>Google Books ID:</strong> {{ backupMetadata.googleId }}</div>
|
||||
}
|
||||
@if (backupMetadata.categories && backupMetadata.categories.length) {
|
||||
<div><strong>Categories:</strong> {{ backupMetadata.categories.join(', ') }}</div>
|
||||
}
|
||||
</div>
|
||||
<div class="w-48 flex-shrink-0">
|
||||
<div class="font-semibold text-gray-300 pb-2">Backup Cover Preview:</div>
|
||||
<div class="bg-gray-900 border p-2 rounded flex justify-center">
|
||||
<img
|
||||
[src]="urlHelperService.getBackupCoverUrl(book?.id!)"
|
||||
alt="Backup Cover"
|
||||
class="max-h-80 object-contain rounded shadow"
|
||||
onerror="this.src='assets/images/missing-cover.jpg'"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (backupMetadata.description) {
|
||||
<div class="text-sm text-gray-400">
|
||||
<div class="font-semibold text-gray-300 pb-1">Description:</div>
|
||||
{{ backupMetadata.description }}
|
||||
</div>
|
||||
}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!backupMetadata) {
|
||||
<div class="mb-4">
|
||||
<div class="p-4 border border-yellow-700 rounded bg-yellow-900 text-yellow-300 text-sm shadow-sm">
|
||||
<p class="font-medium mb-1 text-yellow-200">No backup available</p>
|
||||
<p>We couldn't find a saved backup for this book. Metadata and cover cannot be restored.</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="flex justify-end gap-3 mt-6">
|
||||
<p-button
|
||||
severity="info"
|
||||
outlined
|
||||
label="Cancel"
|
||||
(onClick)="dynamicDialogRef.close()"
|
||||
icon="pi pi-times">
|
||||
</p-button>
|
||||
|
||||
<p-button
|
||||
outlined
|
||||
severity="danger"
|
||||
label="Restore"
|
||||
(onClick)="onRestore()"
|
||||
icon="pi pi-refresh"
|
||||
[disabled]="!backupMetadata">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
.custom-table {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--card-border);
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Button} from 'primeng/button';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {Book, BookMetadata} from '../../../model/book.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-restore-dialog-component',
|
||||
standalone: true,
|
||||
imports: [Button],
|
||||
templateUrl: './metadata-restore-dialog-component.html',
|
||||
styleUrl: './metadata-restore-dialog-component.scss'
|
||||
})
|
||||
export class MetadataRestoreDialogComponent implements OnInit {
|
||||
|
||||
bookId!: number;
|
||||
book!: Book | undefined;
|
||||
backupMetadata: BookMetadata | null = null;
|
||||
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
protected dynamicDialogRef = inject(DynamicDialogRef);
|
||||
protected bookService = inject(BookService);
|
||||
private messageService = inject(MessageService);
|
||||
protected urlHelperService = inject(UrlHelperService);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookId = this.dynamicDialogConfig.data.bookId;
|
||||
this.book = this.bookService.getBookByIdFromState(this.bookId);
|
||||
|
||||
this.bookService.getBackupMetadata(this.bookId).subscribe({
|
||||
next: (data) => {
|
||||
this.backupMetadata = data;
|
||||
},
|
||||
error: err => {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'No Backup Found',
|
||||
detail: err?.error?.message || 'Backup metadata could not be retrieved.'
|
||||
});
|
||||
this.backupMetadata = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onRestore(): void {
|
||||
this.bookService.restoreMetadata(this.bookId).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Restore Successful',
|
||||
detail: `Metadata restored for book ID ${this.bookId}`
|
||||
});
|
||||
this.dynamicDialogRef.close({ action: 'restore', bookId: this.bookId });
|
||||
},
|
||||
error: err => {
|
||||
const errorMessage = err?.error?.message || err?.message || 'Unknown error';
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Restore Failed',
|
||||
detail: `Failed to restore metadata: ${errorMessage}`
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
|
||||
export class BookSorter {
|
||||
selectedSort: SortOption | undefined = undefined;
|
||||
|
||||
sortOptions: SortOption[] = [
|
||||
{ label: 'Title', field: 'title', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Author', field: 'author', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING },
|
||||
{ label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING },
|
||||
{ label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING },
|
||||
];
|
||||
|
||||
constructor(private applySortOption: (sort: SortOption) => void) {}
|
||||
|
||||
sortBooks(field: string): void {
|
||||
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
||||
if (!existingSort) return;
|
||||
|
||||
if (this.selectedSort?.field === field) {
|
||||
this.selectedSort = {
|
||||
...this.selectedSort,
|
||||
direction: this.selectedSort.direction === SortDirection.ASCENDING
|
||||
? SortDirection.DESCENDING
|
||||
: SortDirection.ASCENDING
|
||||
};
|
||||
} else {
|
||||
this.selectedSort = {
|
||||
label: existingSort.label,
|
||||
field: existingSort.field,
|
||||
direction: SortDirection.ASCENDING
|
||||
};
|
||||
}
|
||||
|
||||
this.updateSortOptions();
|
||||
this.applySortOption(this.selectedSort);
|
||||
}
|
||||
|
||||
updateSortOptions() {
|
||||
const directionIcon = this.selectedSort!.direction === SortDirection.ASCENDING ? 'pi pi-arrow-up' : 'pi pi-arrow-down';
|
||||
this.sortOptions = this.sortOptions.map((option) => ({
|
||||
...option,
|
||||
icon: option.field === this.selectedSort!.field ? directionIcon : '',
|
||||
}));
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class TableColumnPreferenceService {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
|
||||
private readonly preferencesSubject = new BehaviorSubject<TableColumnPreference[]>([]);
|
||||
readonly preferences$ = this.preferencesSubject.asObservable();
|
||||
|
||||
private readonly allAvailableColumns = [
|
||||
{field: 'readStatus', header: 'Read'},
|
||||
{field: 'title', header: 'Title'},
|
||||
{field: 'authors', header: 'Authors'},
|
||||
{field: 'publisher', header: 'Publisher'},
|
||||
{field: 'seriesName', header: 'Series'},
|
||||
{field: 'seriesNumber', header: 'Series #'},
|
||||
{field: 'categories', header: 'Genres'},
|
||||
{field: 'publishedDate', header: 'Published'},
|
||||
{field: 'lastReadTime', header: 'Last Read'},
|
||||
{field: 'addedOn', header: 'Added'},
|
||||
{field: 'fileSizeKb', header: 'File Size'},
|
||||
{field: 'language', header: 'Language'},
|
||||
{field: 'pageCount', header: 'Pages'},
|
||||
{field: 'amazonRating', header: 'Amazon'},
|
||||
{field: 'amazonReviewCount', header: 'AZ #'},
|
||||
{field: 'goodreadsRating', header: 'Goodreads'},
|
||||
{field: 'goodreadsReviewCount', header: 'GR #'},
|
||||
{field: 'hardcoverRating', header: 'Hardcover'},
|
||||
{field: 'hardcoverReviewCount', header: 'HC #'}
|
||||
];
|
||||
|
||||
private readonly fallbackPreferences: TableColumnPreference[] = this.allAvailableColumns.map((col, index) => ({
|
||||
field: col.field,
|
||||
visible: true,
|
||||
order: index
|
||||
}));
|
||||
|
||||
initPreferences(savedPrefs: TableColumnPreference[] | undefined): void {
|
||||
const effectivePrefs = savedPrefs?.length ? savedPrefs : this.fallbackPreferences;
|
||||
this.preferencesSubject.next(this.mergeWithAllColumns(effectivePrefs));
|
||||
}
|
||||
|
||||
get allColumns(): { field: string; header: string }[] {
|
||||
return this.allAvailableColumns;
|
||||
}
|
||||
|
||||
get visibleColumns(): { field: string; header: string }[] {
|
||||
return this.preferencesSubject.value
|
||||
.filter(pref => pref.visible)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map(pref => ({
|
||||
field: pref.field,
|
||||
header: this.getColumnHeader(pref.field)
|
||||
}));
|
||||
}
|
||||
|
||||
get preferences(): TableColumnPreference[] {
|
||||
return this.preferencesSubject.value;
|
||||
}
|
||||
|
||||
saveVisibleColumns(selectedColumns: { field: string }[]): void {
|
||||
const selectedFieldSet = new Set(selectedColumns.map(c => c.field));
|
||||
|
||||
const updatedPreferences: TableColumnPreference[] = this.allAvailableColumns.map((col, index) => {
|
||||
const selectionIndex = selectedColumns.findIndex(c => c.field === col.field);
|
||||
return {
|
||||
field: col.field,
|
||||
visible: selectedFieldSet.has(col.field),
|
||||
order: selectionIndex >= 0 ? selectionIndex : index
|
||||
};
|
||||
});
|
||||
|
||||
this.preferencesSubject.next(updatedPreferences);
|
||||
|
||||
const currentUser = this.userService.getCurrentUser();
|
||||
if (!currentUser) return;
|
||||
|
||||
this.userService.updateUserSetting(currentUser.id, 'tableColumnPreference', updatedPreferences);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Preferences Saved',
|
||||
detail: 'Your column layout has been saved.',
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
|
||||
private getColumnHeader(field: string): string {
|
||||
return this.allAvailableColumns.find(col => col.field === field)?.header ?? field;
|
||||
}
|
||||
|
||||
private mergeWithAllColumns(savedPrefs: TableColumnPreference[]): TableColumnPreference[] {
|
||||
const savedPrefMap = new Map(savedPrefs.map(p => [p.field, p]));
|
||||
|
||||
return this.allAvailableColumns.map((col, index) => {
|
||||
const saved = savedPrefMap.get(col.field);
|
||||
return {
|
||||
field: col.field,
|
||||
visible: saved?.visible ?? true,
|
||||
order: saved?.order ?? index
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<div class="book-cover-wrapper" (mouseenter)="isHovered = true" (mouseleave)="isHovered = false">
|
||||
<img
|
||||
[src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
|
||||
class="book-cover"
|
||||
alt="Cover of {{ book.metadata?.title }}"
|
||||
loading="lazy"/>
|
||||
|
||||
@if (!this.isActive) {
|
||||
<p-button
|
||||
icon="pi pi-info"
|
||||
class="info-btn"
|
||||
[rounded]="true"
|
||||
[pTooltip]="book.metadata?.title"
|
||||
tooltipPosition="top"
|
||||
[ngClass]="{ 'visible': isHovered }"
|
||||
(onClick)="openBookInfo(book)">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
.book-cover-wrapper {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
display: block;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.info-btn {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s ease-in-out;
|
||||
z-index: 2;
|
||||
|
||||
&.visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {filter, Subject} from 'rxjs';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host-service';
|
||||
import {takeUntil} from 'rxjs/operators';
|
||||
import {TooltipModule} from 'primeng/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card-lite-component',
|
||||
imports: [
|
||||
Button,
|
||||
NgClass,
|
||||
TooltipModule
|
||||
],
|
||||
templateUrl: './book-card-lite-component.html',
|
||||
styleUrl: './book-card-lite-component.scss'
|
||||
})
|
||||
export class BookCardLiteComponent implements OnInit, OnDestroy {
|
||||
@Input() book!: Book;
|
||||
@Input() isActive: boolean = false;
|
||||
|
||||
private router = inject(Router);
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private userService = inject(UserService);
|
||||
private bookMetadataHostService = inject(BookMetadataHostService);
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
isHovered: boolean = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(userState => !!userState),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe((user) => {
|
||||
this.metadataCenterViewMode = user?.user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
});
|
||||
}
|
||||
|
||||
openBookInfo(book: Book): void {
|
||||
if (this.metadataCenterViewMode === 'route') {
|
||||
this.router.navigate(['/book', book.id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
} else {
|
||||
this.bookMetadataHostService.requestBookSwitch(book.id);
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
<div class="book-notes-container">
|
||||
<div class="notes-content">
|
||||
@if (loading) {
|
||||
<div class="flex flex-col items-center justify-center p-8 gap-4">
|
||||
<p-progressSpinner/>
|
||||
<span class="text-gray-400">Loading notes...</span>
|
||||
</div>
|
||||
} @else if (notes.length === 0) {
|
||||
<div class="text-center p-8 text-gray-400 empty-state">
|
||||
<div class="empty-state-icon">
|
||||
<p-button
|
||||
outlined
|
||||
rounded
|
||||
icon="pi pi-plus"
|
||||
severity="primary"
|
||||
(click)="openCreateDialog()"
|
||||
pTooltip="Add New Note"
|
||||
tooltipPosition="top"
|
||||
class="action-btn floating-btn">
|
||||
</p-button>
|
||||
</div>
|
||||
<p class="text-gray-200 empty-state-title">No notes yet for this book</p>
|
||||
<p class="text-sm text-gray-400 mt-2 empty-state-subtitle">
|
||||
Click "Add Note" to create your first note and start capturing your thoughts
|
||||
</p>
|
||||
<div class="empty-state-decoration"></div>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="notes-scroll-container">
|
||||
<div class="notes-horizontal-list">
|
||||
@for (note of notes; track note.id + '-' + note.createdAt + '-' + $index) {
|
||||
<div class="note-card border border-zinc-700">
|
||||
<div class="note-header">
|
||||
<div class="flex justify-between items-start p-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<h4 class="note-title font-medium text-lg text-gray-200 m-0">{{ note.title }}</h4>
|
||||
<div class="note-meta">
|
||||
<i class="pi pi-clock text-xs mr-1"></i>
|
||||
<span class="text-sm text-gray-400">
|
||||
@if (note.createdAt !== note.updatedAt) {
|
||||
Updated {{ formatDate(note.updatedAt) }}
|
||||
} @else {
|
||||
Created {{ formatDate(note.createdAt) }}
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="note-actions">
|
||||
<p-button
|
||||
icon="pi pi-pencil"
|
||||
size="small"
|
||||
severity="secondary"
|
||||
text
|
||||
(onClick)="openEditDialog(note)"
|
||||
pTooltip="Edit note"
|
||||
tooltipPosition="top"
|
||||
class="action-btn-hover">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
severity="danger"
|
||||
text
|
||||
(onClick)="deleteNote(note)"
|
||||
pTooltip="Delete note"
|
||||
tooltipPosition="top"
|
||||
class="action-btn-hover">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="note-content-area px-3 pb-3">
|
||||
<div class="text-zinc-300 note-body">{{ note.content }}</div>
|
||||
<div class="note-fade-overlay"></div>
|
||||
</div>
|
||||
<div class="note-bottom-glow"></div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (notes.length > 0) {
|
||||
<div class="action-bar">
|
||||
<p-button
|
||||
outlined
|
||||
icon="pi pi-plus"
|
||||
severity="success"
|
||||
(click)="openCreateDialog()"
|
||||
pTooltip="Add New Note"
|
||||
tooltipPosition="left">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
|
||||
<p-dialog
|
||||
header="Add New Note"
|
||||
[(visible)]="showCreateDialog"
|
||||
[modal]="true"
|
||||
[style]="{width: '500px'}"
|
||||
[closable]="true"
|
||||
[dismissableMask]="true">
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="field">
|
||||
<label for="create-title" class="block text-sm font-medium mb-2">Title</label>
|
||||
<input
|
||||
id="create-title"
|
||||
pInputText
|
||||
[(ngModel)]="newNote.title"
|
||||
placeholder="Enter note title"
|
||||
class="w-full"
|
||||
maxlength="255"/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="create-content" class="block text-sm font-medium mb-2">Content</label>
|
||||
<textarea
|
||||
id="create-content"
|
||||
pTextarea
|
||||
[(ngModel)]="newNote.content"
|
||||
placeholder="Enter your note content..."
|
||||
[rows]="8"
|
||||
class="w-full"
|
||||
[autoResize]="true">
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ng-template #footer>
|
||||
<div class="flex gap-2 justify-end">
|
||||
<p-button
|
||||
label="Cancel"
|
||||
severity="secondary"
|
||||
outlined
|
||||
(onClick)="cancelCreate()">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined
|
||||
severity="success"
|
||||
label="Save Note"
|
||||
icon="pi pi-save"
|
||||
(onClick)="createNote()">
|
||||
</p-button>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-dialog>
|
||||
|
||||
<p-dialog
|
||||
header="Edit Note"
|
||||
[(visible)]="showEditDialog"
|
||||
[modal]="true"
|
||||
[style]="{width: '500px'}"
|
||||
[closable]="true"
|
||||
[dismissableMask]="true">
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="field">
|
||||
<label for="edit-title" class="block text-sm font-medium mb-2">Title</label>
|
||||
<input
|
||||
id="edit-title"
|
||||
pInputText
|
||||
[(ngModel)]="editNote.title"
|
||||
placeholder="Enter note title"
|
||||
class="w-full"
|
||||
maxlength="255"/>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="edit-content" class="block text-sm font-medium mb-2">Content</label>
|
||||
<textarea
|
||||
id="edit-content"
|
||||
pTextarea
|
||||
[(ngModel)]="editNote.content"
|
||||
placeholder="Enter your note content..."
|
||||
[rows]="8"
|
||||
class="w-full"
|
||||
[autoResize]="true">
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ng-template #footer>
|
||||
<div class="flex gap-2 justify-end">
|
||||
<p-button
|
||||
label="Cancel"
|
||||
severity="secondary"
|
||||
outlined
|
||||
(onClick)="cancelEdit()">
|
||||
</p-button>
|
||||
<p-button
|
||||
outlined
|
||||
severity="success"
|
||||
label="Update Note"
|
||||
icon="pi pi-save"
|
||||
(onClick)="updateNote()">
|
||||
</p-button>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-dialog>
|
||||
|
||||
<p-confirmDialog key="deleteNote"></p-confirmDialog>
|
||||
</div>
|
||||
@@ -0,0 +1,254 @@
|
||||
.book-notes-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-height: 250px;
|
||||
|
||||
.notes-content {
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.action-bar {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 0;
|
||||
transform: translateY(-50%);
|
||||
z-index: 1000;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
position: relative;
|
||||
padding: 3rem !important;
|
||||
|
||||
.empty-state-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.empty-state-subtitle {
|
||||
max-width: 400px;
|
||||
margin: 0 auto;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.empty-state-decoration {
|
||||
position: absolute;
|
||||
top: 20%;
|
||||
right: 15%;
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
border-radius: 50%;
|
||||
filter: blur(40px);
|
||||
animation: float 4s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
.notes-scroll-container {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
height: 100%;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: rgba(30, 30, 30, 0.5);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.notes-horizontal-list {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.note-card {
|
||||
width: 500px;
|
||||
height: 240px;
|
||||
flex-shrink: 0;
|
||||
padding: 0;
|
||||
border-radius: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: 340px;
|
||||
height: 220px;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
width: 290px;
|
||||
height: 200px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: color-mix(in srgb, var(--primary-color), transparent 50%);
|
||||
|
||||
.note-bottom-glow {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.action-btn-hover {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.note-header {
|
||||
flex-shrink: 0;
|
||||
background: linear-gradient(135deg, rgba(40, 40, 40, 0.8), rgba(30, 30, 30, 0.8));
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
position: relative;
|
||||
|
||||
.note-title {
|
||||
max-width: 350px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
background: linear-gradient(135deg, #f8fafc, #e2e8f0);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-width: 200px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
max-width: 180px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.note-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
opacity: 0.8;
|
||||
|
||||
i {
|
||||
color: #3b82f6;
|
||||
}
|
||||
}
|
||||
|
||||
.note-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
.action-btn-hover {
|
||||
opacity: 0.7;
|
||||
transition: all 0.3s ease;
|
||||
transform: scale(0.9);
|
||||
|
||||
::ng-deep .p-button {
|
||||
border-radius: 8px;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.note-content-area {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
padding: 1rem !important;
|
||||
|
||||
.note-fade-overlay {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 30px;
|
||||
background: linear-gradient(transparent, rgba(20, 20, 20, 0.9));
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.note-bottom-glow {
|
||||
position: absolute;
|
||||
bottom: -5px;
|
||||
left: 20%;
|
||||
right: 20%;
|
||||
height: 10px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
color-mix(in srgb, var(--primary-color), transparent 60%),
|
||||
transparent
|
||||
);
|
||||
border-radius: 50%;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
filter: blur(5px);
|
||||
}
|
||||
}
|
||||
|
||||
.note-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
max-height: 180px;
|
||||
overflow-y: auto;
|
||||
word-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
padding-right: 8px;
|
||||
box-sizing: border-box;
|
||||
line-height: 1.6;
|
||||
color: #e2e8f0;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-height: 140px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
max-height: 120px;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes float {
|
||||
0%, 100% {
|
||||
transform: translateY(0px);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.05);
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Dialog} from 'primeng/dialog';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Textarea} from 'primeng/textarea';
|
||||
import {ConfirmDialog} from 'primeng/confirmdialog';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {BookNote, BookNoteService, CreateBookNoteRequest} from '../../../../shared/service/book-note.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-notes-component',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
Button,
|
||||
Dialog,
|
||||
InputText,
|
||||
Textarea,
|
||||
ConfirmDialog,
|
||||
ProgressSpinner,
|
||||
Tooltip
|
||||
],
|
||||
templateUrl: './book-notes-component.html',
|
||||
styleUrl: './book-notes-component.scss'
|
||||
})
|
||||
export class BookNotesComponent implements OnInit, OnChanges {
|
||||
@Input() bookId!: number;
|
||||
|
||||
private bookNoteService = inject(BookNoteService);
|
||||
private confirmationService = inject(ConfirmationService);
|
||||
private messageService = inject(MessageService);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
|
||||
notes: BookNote[] = [];
|
||||
loading = false;
|
||||
showCreateDialog = false;
|
||||
showEditDialog = false;
|
||||
selectedNote: BookNote | null = null;
|
||||
|
||||
newNote: CreateBookNoteRequest = {
|
||||
bookId: 0,
|
||||
title: '',
|
||||
content: ''
|
||||
};
|
||||
|
||||
editNote: CreateBookNoteRequest = {
|
||||
bookId: 0,
|
||||
title: '',
|
||||
content: ''
|
||||
};
|
||||
|
||||
ngOnInit(): void {
|
||||
if (this.bookId) {
|
||||
this.loadNotes();
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['bookId'] && changes['bookId'].currentValue) {
|
||||
this.loadNotes();
|
||||
}
|
||||
}
|
||||
|
||||
loadNotes(): void {
|
||||
if (!this.bookId) return;
|
||||
|
||||
this.loading = true;
|
||||
this.bookNoteService.getNotesForBook(this.bookId)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (notes) => {
|
||||
this.notes = notes.sort((a, b) =>
|
||||
new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
|
||||
);
|
||||
this.loading = false;
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to load notes:', error);
|
||||
this.loading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to load notes for this book.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
openCreateDialog(): void {
|
||||
this.newNote = {
|
||||
bookId: this.bookId,
|
||||
title: '',
|
||||
content: ''
|
||||
};
|
||||
this.showCreateDialog = true;
|
||||
}
|
||||
|
||||
openEditDialog(note: BookNote): void {
|
||||
this.selectedNote = note;
|
||||
this.editNote = {
|
||||
id: note.id,
|
||||
bookId: note.bookId,
|
||||
title: note.title,
|
||||
content: note.content
|
||||
};
|
||||
this.showEditDialog = true;
|
||||
}
|
||||
|
||||
createNote(): void {
|
||||
if (!this.newNote.title.trim() || !this.newNote.content.trim()) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'Validation Error',
|
||||
detail: 'Both title and content are required.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.bookNoteService.createOrUpdateNote(this.newNote)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (note) => {
|
||||
this.notes.unshift(note);
|
||||
this.showCreateDialog = false;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: 'Note created successfully.'
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to create note:', error);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to create note.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
updateNote(): void {
|
||||
if (!this.editNote.title?.trim() || !this.editNote.content?.trim()) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'Validation Error',
|
||||
detail: 'Both title and content are required.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.bookNoteService.createOrUpdateNote(this.editNote)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (updatedNote) => {
|
||||
const index = this.notes.findIndex(n => n.id === this.selectedNote?.id);
|
||||
if (index !== -1) {
|
||||
this.notes[index] = updatedNote;
|
||||
this.notes.sort((a, b) =>
|
||||
new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
|
||||
);
|
||||
}
|
||||
this.showEditDialog = false;
|
||||
this.selectedNote = null;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: 'Note updated successfully.'
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to update note:', error);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to update note.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteNote(note: BookNote): void {
|
||||
this.confirmationService.confirm({
|
||||
key: 'deleteNote',
|
||||
message: `Are you sure you want to delete the note "${note.title}"?`,
|
||||
header: 'Confirm Deletion',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptButtonStyleClass: 'p-button-danger, p-button-outlined p-button-danger',
|
||||
rejectButtonStyleClass: 'p-button-danger, p-button-outlined p-button-info',
|
||||
accept: () => {
|
||||
this.performDelete(note.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private performDelete(noteId: number): void {
|
||||
this.bookNoteService.deleteNote(noteId).subscribe({
|
||||
next: () => {
|
||||
this.notes = this.notes.filter(n => n.id !== noteId);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: 'Note deleted successfully.'
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to delete note:', error);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to delete note.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancelCreate(): void {
|
||||
this.showCreateDialog = false;
|
||||
this.newNote = {
|
||||
bookId: this.bookId,
|
||||
title: '',
|
||||
content: ''
|
||||
};
|
||||
}
|
||||
|
||||
cancelEdit(): void {
|
||||
this.showEditDialog = false;
|
||||
this.selectedNote = null;
|
||||
this.editNote = {
|
||||
bookId: this.bookId,
|
||||
title: '',
|
||||
content: ''
|
||||
};
|
||||
}
|
||||
|
||||
formatDate(dateString: string): string {
|
||||
return new Date(dateString).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../../../core/config/api-config';
|
||||
|
||||
export interface BookReview {
|
||||
id?: number;
|
||||
metadataProvider?: string;
|
||||
reviewerName?: string;
|
||||
title?: string;
|
||||
rating?: number;
|
||||
date?: string;
|
||||
body?: string;
|
||||
country?: string;
|
||||
spoiler?: boolean;
|
||||
followersCount?: number;
|
||||
textReviewsCount?: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookReviewService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/reviews`;
|
||||
private http = inject(HttpClient);
|
||||
|
||||
getByBookId(bookId: number): Observable<BookReview[]> {
|
||||
return this.http.get<BookReview[]>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
|
||||
refreshReviews(bookId: number): Observable<BookReview[]> {
|
||||
return this.http.post<BookReview[]>(`${this.url}/book/${bookId}/refresh`, {});
|
||||
}
|
||||
|
||||
delete(reviewId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${reviewId}`);
|
||||
}
|
||||
|
||||
deleteAllByBookId(bookId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
<div class="book-reviews-container">
|
||||
<div class="reviews-content">
|
||||
@if (loading) {
|
||||
<div class="flex flex-col items-center justify-center p-8 gap-4">
|
||||
<p-progressSpinner/>
|
||||
<span class="text-gray-400">Getting latest reviews...</span>
|
||||
</div>
|
||||
} @else if (reviews?.length === 0) {
|
||||
<div class="text-center p-8 text-gray-400 empty-state">
|
||||
<div class="empty-state-icon">
|
||||
@if (hasPermission && !reviewsLocked && reviewDownloadEnabled) {
|
||||
<p-button
|
||||
outlined
|
||||
rounded
|
||||
icon="pi pi-download"
|
||||
severity="primary"
|
||||
(click)="fetchNewReviews()"
|
||||
pTooltip="Fetch Reviews"
|
||||
tooltipPosition="top"
|
||||
class="action-btn floating-btn">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
<p class="text-gray-200 empty-state-title">No reviews available for this book</p>
|
||||
@if (!reviewDownloadEnabled) {
|
||||
<p class="text-sm text-amber-400 mt-2 empty-state-subtitle">
|
||||
Book review downloads are currently disabled. Enable this in Metadata Settings to fetch reviews.
|
||||
</p>
|
||||
} @else if (hasPermission && !reviewsLocked) {
|
||||
<p class="text-sm text-gray-400 mt-2 empty-state-subtitle">
|
||||
Click "Fetch Reviews" to download reviews from configured providers
|
||||
</p>
|
||||
}
|
||||
<div class="empty-state-decoration"></div>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="reviews-scroll-container">
|
||||
<div class="reviews-horizontal-list">
|
||||
@for (review of reviews; track review.id || $index) {
|
||||
<div [class]="'review-card border border-zinc-700' + (!review.title ? ' no-title' : '') + (review.spoiler && !isSpoilerRevealed(review.id!) ? ' has-spoiler' : '')">
|
||||
@if (review.spoiler && !isSpoilerRevealed(review.id!)) {
|
||||
<p-button
|
||||
label="Show Spoiler"
|
||||
icon="pi pi-eye"
|
||||
severity="warn"
|
||||
size="small"
|
||||
class="spoiler-overlay-button"
|
||||
(onClick)="revealSpoiler(review.id!)"/>
|
||||
}
|
||||
|
||||
<div class="review-header">
|
||||
<div class="flex justify-between items-start p-3">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-medium text-sm reviewer-name">{{ review.reviewerName || 'Anonymous' }}</span>
|
||||
@if (review.metadataProvider) {
|
||||
<p-tag
|
||||
[rounded]="true"
|
||||
[value]="review.metadataProvider"
|
||||
[severity]="getProviderSeverity(review.metadataProvider)"/>
|
||||
}
|
||||
@if (review.country) {
|
||||
<p-tag [rounded]="true" [value]="review.country" severity="info"/>
|
||||
}
|
||||
@if (review.spoiler) {
|
||||
<p-tag [rounded]="true" value="Spoiler" severity="warn" icon="pi pi-exclamation-triangle"/>
|
||||
}
|
||||
</div>
|
||||
<div class="review-meta">
|
||||
<i class="pi pi-clock text-xs mr-1"></i>
|
||||
@if (review.date) {
|
||||
<span class="text-sm text-gray-400">{{ formatDate(review.date) }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
@if (review.rating) {
|
||||
<div class="flex items-center gap-1">
|
||||
<p-rating
|
||||
[ngModel]="review.rating"
|
||||
[readonly]="true"
|
||||
[stars]="5"/>
|
||||
<span class="text-sm font-medium">{{ review.rating }}/5</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (hasPermission) {
|
||||
@if (reviewsLocked) {
|
||||
<div class="flex items-center justify-center w-8 h-8">
|
||||
<i class="pi pi-lock text-amber-500 text-sm"
|
||||
pTooltip="Reviews are locked"
|
||||
tooltipPosition="top"></i>
|
||||
</div>
|
||||
} @else {
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
severity="danger"
|
||||
text
|
||||
(onClick)="deleteReview(review)"
|
||||
pTooltip="Delete Review"
|
||||
tooltipPosition="top"
|
||||
class="action-btn-hover"/>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (review.title && (!review.spoiler || isSpoilerRevealed(review.id!))) {
|
||||
<div class="review-title-section">
|
||||
<h4 class="font-medium text-xl text-gray-200 leading-tight m-0 review-title"
|
||||
[pTooltip]="review.title"
|
||||
tooltipPosition="top">{{ review.title }}
|
||||
</h4>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="review-content-area">
|
||||
@if (review.spoiler && !isSpoilerRevealed(review.id!)) {
|
||||
<div class="spoiler-blur-content">
|
||||
@if (review.title) {
|
||||
<h4 class="font-medium text-gray-200 leading-tight m-0 review-title blur-sm mb-2">{{ review.title }}</h4>
|
||||
}
|
||||
@if (review.body) {
|
||||
<div class="text-zinc-300 review-body blur-sm">{{ review.body }}</div>
|
||||
} @else {
|
||||
<div class="text-zinc-400 italic text-sm blur-sm">No review content available</div>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
@if (review.body) {
|
||||
<div class="text-zinc-300 review-body">{{ review.body }}</div>
|
||||
} @else {
|
||||
<div class="text-zinc-400 italic text-sm">No review content available</div>
|
||||
}
|
||||
}
|
||||
<div class="review-fade-overlay"></div>
|
||||
</div>
|
||||
<div class="review-bottom-glow"></div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="action-bar">
|
||||
<div class="action-buttons">
|
||||
|
||||
@if (hasPermission) {
|
||||
<p-button
|
||||
outlined
|
||||
[icon]="reviewsLocked ? 'pi pi-lock' : 'pi pi-lock-open'"
|
||||
size="small"
|
||||
[severity]="reviewsLocked ? 'danger' : 'success'"
|
||||
[disabled]="!reviewDownloadEnabled || loading"
|
||||
(click)="toggleReviewsLock()"
|
||||
[pTooltip]="loading ? 'Please wait while reviews are being fetched' : (!reviewDownloadEnabled ? 'Enable review downloads in settings to use this feature' : (reviewsLocked ? 'Unlock Reviews' : 'Lock Reviews'))"
|
||||
tooltipPosition="left"
|
||||
class="action-btn"/>
|
||||
|
||||
<p-button
|
||||
outlined
|
||||
icon="pi pi-refresh"
|
||||
size="small"
|
||||
severity="primary"
|
||||
[loading]="loading"
|
||||
[disabled]="reviewsLocked || !reviewDownloadEnabled || loading"
|
||||
(click)="fetchNewReviews()"
|
||||
[pTooltip]="loading ? 'Please wait while reviews are being fetched' : (!reviewDownloadEnabled ? 'Enable review downloads in settings to use this feature' : (reviewsLocked ? 'Reviews are locked' : 'Fetch New Reviews'))"
|
||||
tooltipPosition="left"
|
||||
class="action-btn"/>
|
||||
}
|
||||
|
||||
@if (hasPermission && reviews && reviews.length > 0) {
|
||||
<p-button
|
||||
outlined
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
severity="danger"
|
||||
[disabled]="reviewsLocked || loading"
|
||||
(click)="deleteAllReviews()"
|
||||
[pTooltip]="loading ? 'Please wait while reviews are being fetched' : (reviewsLocked ? 'Reviews are locked' : 'Delete All Reviews')"
|
||||
tooltipPosition="left"
|
||||
class="action-btn"/>
|
||||
}
|
||||
|
||||
@if (reviews && reviews.length > 0) {
|
||||
<p-button
|
||||
outlined
|
||||
[icon]="allSpoilersRevealed ? 'pi pi-eye-slash' : 'pi pi-eye'"
|
||||
size="small"
|
||||
[severity]="allSpoilersRevealed ? 'warn' : 'info'"
|
||||
[disabled]="loading"
|
||||
(click)="toggleSpoilerVisibility()"
|
||||
[pTooltip]="loading ? 'Please wait while reviews are being fetched' : (allSpoilersRevealed ? 'Hide All Spoilers' : 'Reveal All Spoilers')"
|
||||
tooltipPosition="left"
|
||||
class="action-btn"/>
|
||||
|
||||
<p-button
|
||||
outlined
|
||||
icon="pi pi-sort-amount-down"
|
||||
size="small"
|
||||
severity="contrast"
|
||||
[disabled]="loading"
|
||||
(click)="toggleSortOrder()"
|
||||
[pTooltip]="loading ? 'Please wait while reviews are being fetched' : (sortAscending ? 'Sort by Newest First' : 'Sort by Oldest First')"
|
||||
tooltipPosition="left"
|
||||
class="action-btn"/>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
.book-reviews-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-height: 250px;
|
||||
|
||||
.reviews-content {
|
||||
flex: 1;
|
||||
padding-right: 60px;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.action-bar {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 0;
|
||||
transform: translateY(-50%);
|
||||
width: 50px;
|
||||
z-index: 1000;
|
||||
pointer-events: none;
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 16px 8px;
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
backdrop-filter: blur(8px);
|
||||
pointer-events: auto;
|
||||
position: relative;
|
||||
top: -50%;
|
||||
|
||||
.action-btn {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
|
||||
::ng-deep {
|
||||
.p-button {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
|
||||
.p-button-icon {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
position: relative;
|
||||
padding: 3rem !important;
|
||||
|
||||
.empty-state-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.empty-state-subtitle {
|
||||
max-width: 400px;
|
||||
margin: 0 auto;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.empty-state-decoration {
|
||||
position: absolute;
|
||||
top: 20%;
|
||||
right: 15%;
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
border-radius: 50%;
|
||||
filter: blur(40px);
|
||||
animation: float 4s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
.reviews-scroll-container {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
padding-bottom: 8px;
|
||||
height: 100%;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: var(--surface-ground);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--surface-border);
|
||||
border-radius: 4px;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.reviews-horizontal-list {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.review-card {
|
||||
width: 500px;
|
||||
height: 250px;
|
||||
flex-shrink: 0;
|
||||
padding: 0;
|
||||
border-radius: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
|
||||
@media (max-width: 768px) {
|
||||
width: 340px;
|
||||
height: 220px;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
width: 290px;
|
||||
height: 200px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: color-mix(in srgb, var(--primary-color), transparent 50%);
|
||||
|
||||
.action-btn-hover {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
&.no-title {
|
||||
.review-content-area {
|
||||
height: calc(100% - 80px);
|
||||
}
|
||||
}
|
||||
|
||||
&.has-spoiler {
|
||||
.review-content-area {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
z-index: 50;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.review-header {
|
||||
flex-shrink: 0;
|
||||
background: linear-gradient(135deg, rgba(40, 40, 40, 0.8), rgba(30, 30, 30, 0.8));
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
|
||||
position: relative;
|
||||
|
||||
.reviewer-name {
|
||||
max-width: 120px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
background: linear-gradient(135deg, #f8fafc, #e2e8f0);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.review-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
opacity: 0.8;
|
||||
|
||||
i {
|
||||
color: #3b82f6;
|
||||
}
|
||||
}
|
||||
|
||||
.action-btn-hover {
|
||||
opacity: 0.7;
|
||||
transition: all 0.3s ease;
|
||||
transform: scale(0.9);
|
||||
|
||||
::ng-deep .p-button {
|
||||
border-radius: 8px;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.review-title-section {
|
||||
flex-shrink: 0;
|
||||
border-bottom: 1px solid var(--surface-border);
|
||||
padding: 8px 16px 4px 16px;
|
||||
}
|
||||
|
||||
.review-content-area {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
padding: 8px 16px 16px 16px;
|
||||
|
||||
.review-fade-overlay {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 30px;
|
||||
background: linear-gradient(transparent, rgba(20, 20, 20, 0.9));
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.spoiler-overlay-button {
|
||||
position: absolute;
|
||||
top: 62%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
z-index: 100;
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.review-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
max-height: 210px;
|
||||
overflow-y: auto;
|
||||
word-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
box-sizing: border-box;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: var(--surface-ground);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--surface-border);
|
||||
border-radius: 2px;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.review-title {
|
||||
max-width: 450px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
cursor: help;
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
import {BookReview, BookReviewService} from './book-review-service';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Rating} from 'primeng/rating';
|
||||
import {Tag} from 'primeng/tag';
|
||||
import {Button} from 'primeng/button';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-reviews',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ProgressSpinner, Rating, Tag, Button, FormsModule, Tooltip],
|
||||
templateUrl: './book-reviews.component.html',
|
||||
styleUrl: './book-reviews.component.scss'
|
||||
})
|
||||
export class BookReviewsComponent implements OnInit, OnChanges {
|
||||
@Input() bookId!: number;
|
||||
@Input() reviews: BookReview[] | undefined = [];
|
||||
@Input() active: boolean = false;
|
||||
|
||||
private reviewService = inject(BookReviewService);
|
||||
private bookService = inject(BookService);
|
||||
private confirmationService = inject(ConfirmationService);
|
||||
private messageService = inject(MessageService);
|
||||
private userService = inject(UserService);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
|
||||
loading = false;
|
||||
hasPermission = false;
|
||||
revealedSpoilers = new Set<number>();
|
||||
sortAscending = false;
|
||||
reviewsLocked = false;
|
||||
allSpoilersRevealed = false;
|
||||
reviewDownloadEnabled = true;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.checkUserPermissions();
|
||||
this.subscribeToBookState();
|
||||
this.subscribeToAppSettings();
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['bookId'] && changes['bookId'].currentValue) {
|
||||
this.loadReviews();
|
||||
}
|
||||
}
|
||||
|
||||
private subscribeToBookState(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(state => {
|
||||
if (state.books && this.bookId) {
|
||||
const book = state.books.find(b => b.id === this.bookId);
|
||||
this.reviewsLocked = book?.metadata?.reviewsLocked ?? false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private loadReviews(): void {
|
||||
if (this.loading || !this.bookId) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.loading = true;
|
||||
this.reviewService.getByBookId(this.bookId)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (reviews) => {
|
||||
this.reviews = this.sortReviewsByDate(reviews || []);
|
||||
this.loading = false;
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to load reviews for bookId', this.bookId, ':', error);
|
||||
this.reviews = [];
|
||||
this.loading = false;
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed to Load Reviews',
|
||||
detail: 'Could not load reviews for this book.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fetchNewReviews(): void {
|
||||
if (!this.bookId || this.loading || this.reviewsLocked) return;
|
||||
|
||||
this.loading = true;
|
||||
this.revealedSpoilers.clear();
|
||||
|
||||
this.reviewService.refreshReviews(this.bookId)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (reviews) => {
|
||||
this.reviews = this.sortReviewsByDate(reviews || []);
|
||||
this.loading = false;
|
||||
this.updateSpoilerState();
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Reviews Updated',
|
||||
detail: 'Latest reviews have been fetched successfully.',
|
||||
life: 3000
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to fetch new reviews:', error);
|
||||
this.loading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Fetch Failed',
|
||||
detail: 'Could not fetch new reviews for this book.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteAllReviews(): void {
|
||||
if (!this.reviews || this.reviews.length === 0 || this.reviewsLocked) return;
|
||||
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete all ${this.reviews.length} reviews for this book? This action cannot be undone.`,
|
||||
header: 'Confirm Delete All',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
if (!this.bookId) return;
|
||||
|
||||
this.reviewService.deleteAllByBookId(this.bookId).subscribe({
|
||||
next: () => {
|
||||
this.reviews = [];
|
||||
this.revealedSpoilers.clear();
|
||||
this.allSpoilersRevealed = false;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'All Reviews Deleted',
|
||||
detail: 'All reviews have been successfully deleted.',
|
||||
life: 3000
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to delete all reviews:', error);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Delete Failed',
|
||||
detail: 'Could not delete all reviews.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
toggleSpoilerVisibility(): void {
|
||||
if (this.allSpoilersRevealed) {
|
||||
this.hideAllSpoilers();
|
||||
} else {
|
||||
this.revealAllSpoilers();
|
||||
}
|
||||
}
|
||||
|
||||
hideAllSpoilers(): void {
|
||||
this.revealedSpoilers.clear();
|
||||
this.allSpoilersRevealed = false;
|
||||
}
|
||||
|
||||
revealAllSpoilers(): void {
|
||||
if (this.reviews) {
|
||||
this.reviews.forEach(review => {
|
||||
if (review.spoiler && review.id) {
|
||||
this.revealedSpoilers.add(review.id);
|
||||
}
|
||||
});
|
||||
this.allSpoilersRevealed = true;
|
||||
}
|
||||
}
|
||||
|
||||
toggleReviewsLock(): void {
|
||||
if (!this.bookId) return;
|
||||
|
||||
const newLockState = !this.reviewsLocked;
|
||||
const fieldActions: Record<string, 'LOCK' | 'UNLOCK'> = {
|
||||
'reviewsLocked': newLockState ? 'LOCK' : 'UNLOCK'
|
||||
};
|
||||
|
||||
this.bookService.toggleFieldLocks([this.bookId], fieldActions)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
const action = newLockState ? 'locked' : 'unlocked';
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: `Reviews ${action.charAt(0).toUpperCase() + action.slice(1)}`,
|
||||
detail: newLockState
|
||||
? 'Reviews are now protected from modifications and refreshes.'
|
||||
: 'Reviews can now be modified and refreshed.',
|
||||
life: 3000
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to toggle lock status:', error);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Lock Toggle Failed',
|
||||
detail: 'Could not change the lock status for reviews.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
toggleSortOrder(): void {
|
||||
this.sortAscending = !this.sortAscending;
|
||||
if (this.reviews) {
|
||||
this.reviews = this.sortReviewsByDate([...this.reviews]);
|
||||
}
|
||||
}
|
||||
|
||||
private sortReviewsByDate(reviews: BookReview[]): BookReview[] {
|
||||
return reviews.sort((a, b) => {
|
||||
if (!a.date && !b.date) return 0;
|
||||
if (!a.date) return this.sortAscending ? -1 : 1;
|
||||
if (!b.date) return this.sortAscending ? 1 : -1;
|
||||
|
||||
const dateA = new Date(a.date).getTime();
|
||||
const dateB = new Date(b.date).getTime();
|
||||
|
||||
return this.sortAscending ? dateA - dateB : dateB - dateA;
|
||||
});
|
||||
}
|
||||
|
||||
private checkUserPermissions(): void {
|
||||
this.userService.userState$
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(userState => {
|
||||
this.hasPermission = userState?.user?.permissions?.admin ||
|
||||
userState?.user?.permissions?.canEditMetadata || false;
|
||||
});
|
||||
}
|
||||
|
||||
deleteReview(review: BookReview): void {
|
||||
if (!review.id || this.reviewsLocked) return;
|
||||
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete this review by ${review.reviewerName || 'Anonymous'}?`,
|
||||
header: 'Confirm Deletion',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
this.reviewService.delete(review.id!).subscribe({
|
||||
next: () => {
|
||||
this.reviews = this.reviews?.filter(r => r.id !== review.id);
|
||||
this.updateSpoilerState();
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Review Deleted',
|
||||
detail: 'The review has been successfully deleted.',
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to delete review:', error);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Delete Failed',
|
||||
detail: 'Could not delete the review.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
revealSpoiler(reviewId: number): void {
|
||||
if (reviewId) {
|
||||
this.revealedSpoilers.add(reviewId);
|
||||
this.updateSpoilerState();
|
||||
}
|
||||
}
|
||||
|
||||
private updateSpoilerState(): void {
|
||||
const spoilerReviews = this.reviews?.filter(r => r.spoiler) || [];
|
||||
const revealedSpoilerReviews = spoilerReviews.filter(r => r.id && this.revealedSpoilers.has(r.id));
|
||||
this.allSpoilersRevealed = spoilerReviews.length > 0 && spoilerReviews.length === revealedSpoilerReviews.length;
|
||||
}
|
||||
|
||||
formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
}
|
||||
|
||||
isSpoilerRevealed(reviewId: number): boolean {
|
||||
return this.revealedSpoilers.has(reviewId);
|
||||
}
|
||||
|
||||
private subscribeToAppSettings(): void {
|
||||
this.appSettingsService.appSettings$
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(settings => {
|
||||
this.reviewDownloadEnabled = settings?.metadataPublicReviewsSettings?.downloadEnabled ?? true;
|
||||
});
|
||||
}
|
||||
|
||||
getProviderSeverity(provider: string): 'success' | 'warn' {
|
||||
switch (provider?.toLowerCase()) {
|
||||
case 'amazon':
|
||||
return 'warn';
|
||||
default:
|
||||
return 'success';
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
<div class="ml-2 md:ml-5 relative w-full max-w-[500px]">
|
||||
<!-- Desktop view -->
|
||||
<p-iconfield class="w-full sm:flex">
|
||||
<p-inputicon styleClass="pi pi-search"/>
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="searchQuery"
|
||||
(input)="onSearchInputChange()"
|
||||
placeholder="Title, Author, Series, Genre, or ISBN..."
|
||||
class="w-full pr-10"
|
||||
/>
|
||||
@if (searchQuery) {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
(click)="clearSearch()"
|
||||
[text]="true"
|
||||
[rounded]="true"
|
||||
class="absolute right-2 top-1/2 -translate-y-1/2 hidden lg:inline-flex"
|
||||
aria-label="Clear Search">
|
||||
</p-button>
|
||||
}
|
||||
</p-iconfield>
|
||||
|
||||
<!-- Search results below small screen search input -->
|
||||
@if (books.length > 0 || searchQuery) {
|
||||
<div
|
||||
class="search-dropdown layout-menu w-[300px] sm:w-[600px]"
|
||||
[class.show]="(books.length > 0)"
|
||||
>
|
||||
@if (books.length > 0) {
|
||||
@for (book of books; track book) {
|
||||
<div class="search-dropdown-item flex flex-col" (click)="onBookClick(book)">
|
||||
<div class="flex flex-row w-full p-2">
|
||||
<img
|
||||
[attr.src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
|
||||
alt="Book Cover"
|
||||
class="search-book-cover"
|
||||
/>
|
||||
<div class="search-book-details">
|
||||
<div class="flex items-center">
|
||||
<p class="search-book-name text font-medium truncate">
|
||||
{{ book.metadata?.title | slice: 0:70 }}
|
||||
</p>
|
||||
</div>
|
||||
@if (book.metadata?.authors?.length ?? 0 > 0) {
|
||||
<p class="italic text-gray-300">by: {{ getAuthorNames(book.metadata?.authors) }}</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<p-divider></p-divider>
|
||||
</div>
|
||||
}
|
||||
} @else {
|
||||
<div class="search-dropdown-item px-4 py-2">
|
||||
<span>No results found</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
.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;
|
||||
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;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.3s;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--surface-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.search-book-cover {
|
||||
width: 35px;
|
||||
height: 47px;
|
||||
object-fit: cover;
|
||||
max-width: 100px;
|
||||
max-height: 150px;
|
||||
border-radius: 4px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {BehaviorSubject, of, Subject, Subscription} from 'rxjs';
|
||||
import {catchError, switchMap} from 'rxjs/operators';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {InputTextModule} from 'primeng/inputtext';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {SlicePipe} from '@angular/common';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {IconField} from 'primeng/iconfield';
|
||||
import {InputIcon} from 'primeng/inputicon';
|
||||
import {HeaderFilter} from '../book-browser/filters/HeaderFilter';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-searcher',
|
||||
templateUrl: './book-searcher.component.html',
|
||||
imports: [
|
||||
FormsModule,
|
||||
InputTextModule,
|
||||
Button,
|
||||
SlicePipe,
|
||||
Divider,
|
||||
IconField,
|
||||
InputIcon
|
||||
],
|
||||
styleUrls: ['./book-searcher.component.scss'],
|
||||
standalone: true
|
||||
})
|
||||
export class BookSearcherComponent implements OnInit, OnDestroy {
|
||||
searchQuery: string = '';
|
||||
books: Book[] = [];
|
||||
#searchSubject = new BehaviorSubject<string>('');
|
||||
#subscription!: Subscription;
|
||||
|
||||
private bookService = inject(BookService);
|
||||
private router = inject(Router);
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
private headerFilter = new HeaderFilter(this.#searchSubject.asObservable());
|
||||
|
||||
ngOnInit(): void {
|
||||
this.initializeSearch();
|
||||
}
|
||||
|
||||
initializeSearch(): void {
|
||||
this.#subscription = this.bookService.bookState$.pipe(
|
||||
switchMap(bookState => this.headerFilter.filter(bookState)),
|
||||
catchError((error) => {
|
||||
console.error('Error while searching books:', error);
|
||||
return of({books: [], loaded: true, error: null});
|
||||
})
|
||||
).subscribe({
|
||||
next: (filteredState) => {
|
||||
const term = this.searchQuery.trim();
|
||||
this.books = term.length >= 2
|
||||
? (filteredState.books || []).slice(0, 50)
|
||||
: [];
|
||||
},
|
||||
error: (error) => console.error('Subscription error:', error)
|
||||
});
|
||||
}
|
||||
|
||||
getAuthorNames(authors: string[] | undefined): string {
|
||||
return authors?.join(', ') || 'Unknown Author';
|
||||
}
|
||||
|
||||
onSearchInputChange(): void {
|
||||
this.#searchSubject.next(this.searchQuery.trim());
|
||||
}
|
||||
|
||||
onBookClick(book: Book): void {
|
||||
this.clearSearch();
|
||||
this.router.navigate(['/book', book.id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
}
|
||||
|
||||
clearSearch(): void {
|
||||
this.searchQuery = '';
|
||||
this.books = [];
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
if (this.#subscription) {
|
||||
this.#subscription.unsubscribe();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<div class="flex flex-col gap-10 p-4 items-center justify-center min-w-[300px] max-w-[700px] sm:min-w-[400px] mx-auto">
|
||||
|
||||
<p-select
|
||||
[options]="emailProviders"
|
||||
optionLabel="label"
|
||||
placeholder="Select Email Provider"
|
||||
[(ngModel)]="selectedProvider"
|
||||
appendTo="body"
|
||||
class="w-full">
|
||||
</p-select>
|
||||
|
||||
<p-select
|
||||
[options]="emailRecipients"
|
||||
optionLabel="label"
|
||||
placeholder="Select Book Recipient"
|
||||
[(ngModel)]="selectedRecipient"
|
||||
[disabled]="!selectedProvider"
|
||||
appendTo="body"
|
||||
class="w-full">
|
||||
</p-select>
|
||||
|
||||
<p-button
|
||||
icon="pi pi-envelope"
|
||||
label="Send Book"
|
||||
[disabled]="!selectedProvider || !selectedRecipient"
|
||||
(onClick)="sendBook()">
|
||||
</p-button>
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,114 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Select} from 'primeng/select';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {EmailProviderService} from '../../../settings/email/email-provider/email-provider.service';
|
||||
import {EmailRecipientService} from '../../../settings/email/email-recipient/email-recipient.service';
|
||||
import {EmailProvider} from '../../../settings/email/email-provider/email-provider.model';
|
||||
import {EmailRecipient} from '../../../settings/email/email-recipient/email-recipient.model';
|
||||
import {EmailService} from '../../../settings/email/email.service';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-sender',
|
||||
imports: [
|
||||
Button,
|
||||
Select,
|
||||
FormsModule
|
||||
],
|
||||
templateUrl: './book-sender.component.html',
|
||||
styleUrls: ['./book-sender.component.scss']
|
||||
})
|
||||
export class BookSenderComponent implements OnInit {
|
||||
|
||||
private emailProviderService = inject(EmailProviderService);
|
||||
private emailRecipientService = inject(EmailRecipientService);
|
||||
private emailService = inject(EmailService);
|
||||
private messageService = inject(MessageService);
|
||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
|
||||
bookId: number = this.dynamicDialogConfig.data.bookId;
|
||||
|
||||
emailProviders: { label: string, value: EmailProvider }[] = [];
|
||||
emailRecipients: { label: string, value: EmailRecipient }[] = [];
|
||||
selectedProvider?: any;
|
||||
selectedRecipient?: any;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.emailProviderService.getEmailProviders().subscribe({
|
||||
next: (emailProviders: EmailProvider[]) => {
|
||||
this.emailProviders = emailProviders.map(provider => ({
|
||||
label: `${provider.name} | ${provider.fromAddress || provider.host}`,
|
||||
value: provider
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
this.emailRecipientService.getRecipients().subscribe({
|
||||
next: (emailRecipients: EmailRecipient[]) => {
|
||||
this.emailRecipients = emailRecipients.map(recipient => ({
|
||||
label: `${recipient.name} | ${recipient.email}`,
|
||||
value: recipient
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
sendBook() {
|
||||
if (this.selectedProvider && this.selectedRecipient && this.bookId) {
|
||||
const bookId = this.bookId;
|
||||
const recipientId = this.selectedRecipient.value.id;
|
||||
const providerId = this.selectedProvider.value.id;
|
||||
|
||||
const emailRequest = {
|
||||
bookId,
|
||||
providerId,
|
||||
recipientId: recipientId,
|
||||
};
|
||||
|
||||
this.emailService.emailBook(emailRequest).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Email Scheduled',
|
||||
detail: 'The book has been successfully scheduled for sending.'
|
||||
});
|
||||
this.dynamicDialogRef.close(true);
|
||||
},
|
||||
error: (error) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Sending Failed',
|
||||
detail: 'There was an issue while scheduling the book for sending. Please try again later.'
|
||||
});
|
||||
console.error('Error sending book:', error);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
if (!this.selectedProvider) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Email Provider Missing',
|
||||
detail: 'Please select an email provider to proceed.'
|
||||
});
|
||||
}
|
||||
if (!this.selectedRecipient) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Recipient Missing',
|
||||
detail: 'Please select a recipient to send the book.'
|
||||
});
|
||||
}
|
||||
if (!this.bookId) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Book Not Selected',
|
||||
detail: 'Please select a book to send.'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
@if (filteredBooks$ | async; as books) {
|
||||
<div class="rounded-xl overflow-hidden">
|
||||
<p-tabs [value]="tab" lazy="true" scrollable>
|
||||
<p-tablist>
|
||||
<p-tab value="view">
|
||||
<i [class]="'pi pi-crown'"></i>
|
||||
Series Details
|
||||
</p-tab>
|
||||
</p-tablist>
|
||||
<p-tabpanels class="tabpanels-responsive overflow-auto">
|
||||
<p-tabpanel value="view">
|
||||
|
||||
@if (books[0]; as firstBook) {
|
||||
<div class="flex flex-col justify-between flex-grow">
|
||||
<div class="space-y-4 ">
|
||||
|
||||
<!-- <div class="flex items-start justify-between"> -->
|
||||
<div class="flex flex-col text-center gap-4 md:text-left w-full">
|
||||
|
||||
<div class="flex flex-col items-center md:items-start gap-1">
|
||||
<div class="flex items-center gap-2 justify-center md:justify-start flex-wrap text-center md:text-left">
|
||||
<h2 class="text-2xl md:text-3xl font-extrabold leading-tight">
|
||||
{{ seriesTitle$ | async }}
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<p class="text-lg">
|
||||
@for (author of firstBook.metadata?.authors; track $index; let isLast = $last) {
|
||||
<a class="hover:underline dark:text-blue-400 cursor-pointer" (click)="goToAuthorBooks(author)">
|
||||
{{ author }}
|
||||
</a>
|
||||
@if (!isLast) {
|
||||
<span>, </span>
|
||||
}
|
||||
}
|
||||
</p>
|
||||
<!-- </div> -->
|
||||
</div>
|
||||
|
||||
@if (firstBook.metadata?.categories?.length) {
|
||||
<div class="overflow-x-auto scrollbar-hide max-w-7xl pt-2 md:pt-0">
|
||||
<div class="flex gap-2 w-max max-w-[1150px]">
|
||||
@for (category of firstBook.metadata?.categories; track category) {
|
||||
<a (click)="goToCategory(category)" class="shrink-0 no-underline cursor-pointer">
|
||||
<p-tag [value]="category"></p-tag>
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<div class="px-1 md:px-0">
|
||||
<div
|
||||
class="grid md:grid-cols-5 p-3 gap-y-2.5 text-sm pt-2 md:pt-4 pb-2 text-gray-300 md:min-w-[60rem] md:max-w-[100rem]">
|
||||
<p>
|
||||
<span class="font-bold">Publisher: </span>
|
||||
@if (firstBook.metadata?.publisher; as publisher) {
|
||||
<span class="underline hover:opacity-80 cursor-pointer" (click)="goToPublisher(publisher)">
|
||||
{{publisher}}
|
||||
</span>
|
||||
} @else {
|
||||
<span>-</span>
|
||||
}
|
||||
</p>
|
||||
<p><strong>Years:</strong> {{ (yearsRange$ | async) || '-' }}</p>
|
||||
<p><strong>Number of books:</strong> {{ books.length || 0}}</p>
|
||||
<p><strong>Language:</strong> {{ firstBook.metadata?.language || "-"}}</p>
|
||||
<p><strong>Read Status: </strong>
|
||||
@let s = seriesReadStatus$ | async;
|
||||
<span class="inline-block px-2 py-0.5 rounded-full text-xs font-bold text-white"
|
||||
[ngClass]="getStatusSeverityClass(s || 'UNREAD')">
|
||||
{{ getStatusLabel(s) }}
|
||||
@if (s === 'PARTIALLY_READ') {
|
||||
({{ seriesReadProgress$ | async }})
|
||||
}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- DESCRIPTION -->
|
||||
<div class="px-4 pb-2 pt-4 mb-4 md:mb-6 md:mx-2 border border-[var(--border-color)] rounded-xl">
|
||||
<div [ngClass]="{ 'line-clamp-5': !isExpanded, 'line-clamp-none': isExpanded }"
|
||||
class="transition-all duration-300 overflow-hidden description-container">
|
||||
<div class="readonly-editor px-2"
|
||||
[innerHTML]="(firstDescription$ | async) || 'No description available.'"></div>
|
||||
</div>
|
||||
@let desc = firstDescription$ | async;
|
||||
@if ((desc?.length ?? 0) > 500) {
|
||||
<p-button [label]="isExpanded ? 'Show less' : 'Show more'"
|
||||
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'" iconPos="right" size="small" text
|
||||
(click)="toggleExpand()">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="grid series-items-grid overflow-y-auto" #Container
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
<div class="grid-item" *ngFor="let book of books; let i = index"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||
<app-book-card [index]="i" [book]="book" [isCheckboxEnabled]="false" [isSelected]="false"
|
||||
[isSeriesCollapsed]="false">
|
||||
</app-book-card>
|
||||
</div>
|
||||
<div *ngIf="books.length === 0" class="empty-state">No books found for this series.</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
</p-tabpanel>
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
</div>
|
||||
|
||||
} @else {
|
||||
<div class="flex flex-col justify-center items-center h-full gap-4">
|
||||
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
|
||||
</p-progressSpinner>
|
||||
<p style="color: var(--primary-color);">
|
||||
Loading series details...
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
.tabpanels-responsive {
|
||||
height: calc(100dvh - 9.7rem);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.tabpanels-responsive {
|
||||
height: calc(100dvh - 8.5rem);
|
||||
}
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(1px, 1fr));
|
||||
gap: 1.3rem;
|
||||
align-items: start;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
import { Component, inject, ViewChild } from "@angular/core";
|
||||
import { FormsModule } from "@angular/forms";
|
||||
import { Button } from "primeng/button";
|
||||
import { ActivatedRoute } from "@angular/router";
|
||||
import { AsyncPipe, NgClass, NgFor, NgIf, NgStyle } from "@angular/common";
|
||||
import { map, filter, switchMap } from "rxjs/operators";
|
||||
import { Observable, combineLatest } from "rxjs";
|
||||
import { Book, ReadStatus } from "../../model/book.model";
|
||||
import { BookService } from "../../service/book.service";
|
||||
import { BookCardComponent } from "../book-browser/book-card/book-card.component";
|
||||
import { CoverScalePreferenceService } from "../book-browser/cover-scale-preference.service";
|
||||
import { Tab, TabList, TabPanel, TabPanels, Tabs } from "primeng/tabs";
|
||||
import { Tag } from "primeng/tag";
|
||||
import { VirtualScrollerModule } from "@iharbeck/ngx-virtual-scroller";
|
||||
import { ProgressSpinner } from "primeng/progressspinner";
|
||||
import { DialogService, DynamicDialogRef } from "primeng/dynamicdialog";
|
||||
import { Router } from "@angular/router";
|
||||
|
||||
@Component({
|
||||
selector: "app-series-page",
|
||||
standalone: true,
|
||||
templateUrl: "./series-page.component.html",
|
||||
styleUrls: ["./series-page.component.scss"],
|
||||
imports: [
|
||||
AsyncPipe,
|
||||
Button,
|
||||
FormsModule,
|
||||
NgIf,
|
||||
NgFor,
|
||||
NgStyle,
|
||||
NgClass,
|
||||
BookCardComponent,
|
||||
ProgressSpinner,
|
||||
Tabs,
|
||||
TabList,
|
||||
Tab,
|
||||
TabPanels,
|
||||
TabPanel,
|
||||
Tag,
|
||||
|
||||
VirtualScrollerModule,
|
||||
],
|
||||
})
|
||||
export class SeriesPageComponent {
|
||||
|
||||
private route = inject(ActivatedRoute);
|
||||
private bookService = inject(BookService);
|
||||
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
|
||||
private metadataCenterViewMode: "route" | "dialog" = "route";
|
||||
private dialogRef?: DynamicDialogRef;
|
||||
private router = inject(Router);
|
||||
|
||||
tab: string = "view";
|
||||
isExpanded = false;
|
||||
|
||||
|
||||
seriesParam$: Observable<string> = this.route.paramMap.pipe(
|
||||
map((params) => params.get("seriesName") || ""),
|
||||
map((name) => decodeURIComponent(name))
|
||||
);
|
||||
|
||||
booksInSeries$: Observable<Book[]> = this.bookService.bookState$.pipe(
|
||||
filter((state) => state.loaded && !!state.books),
|
||||
map((state) => state.books || [])
|
||||
);
|
||||
|
||||
filteredBooks$: Observable<Book[]> = combineLatest([
|
||||
this.seriesParam$.pipe(map((n) => n.trim().toLowerCase())),
|
||||
this.booksInSeries$,
|
||||
]).pipe(
|
||||
map(([seriesName, books]) => {
|
||||
const inSeries = books.filter(
|
||||
(b) => b.metadata?.seriesName?.toLowerCase() === seriesName
|
||||
);
|
||||
return inSeries.sort((a, b) => {
|
||||
const aNum = a.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
|
||||
const bNum = b.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
|
||||
return aNum - bNum;
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
seriesTitle$: Observable<string> = combineLatest([
|
||||
this.seriesParam$,
|
||||
this.filteredBooks$,
|
||||
]).pipe(map(([param, books]) => books[0]?.metadata?.seriesName || param));
|
||||
|
||||
yearsRange$: Observable<string | null> = this.filteredBooks$.pipe(
|
||||
map((books) => {
|
||||
const years = books
|
||||
.map((b) => b.metadata?.publishedDate)
|
||||
.filter((d): d is string => !!d)
|
||||
.map((d) => {
|
||||
const match = d.match(/\d{4}/);
|
||||
return match ? parseInt(match[0], 10) : null;
|
||||
})
|
||||
.filter((y): y is number => y !== null);
|
||||
|
||||
if (years.length === 0) return null;
|
||||
const min = Math.min(...years);
|
||||
const max = Math.max(...years);
|
||||
return min === max ? String(min) : `${min}-${max}`;
|
||||
})
|
||||
);
|
||||
|
||||
firstBookWithDesc$: Observable<Book> = this.filteredBooks$.pipe(
|
||||
map((books) => books[0]),
|
||||
filter((b): b is Book => !!b),
|
||||
switchMap((b) => this.bookService.getBookByIdFromAPI(b.id, true))
|
||||
);
|
||||
|
||||
firstDescription$: Observable<string> = this.firstBookWithDesc$.pipe(
|
||||
map((b) => b.metadata?.description || "")
|
||||
);
|
||||
|
||||
seriesReadStatus$: Observable<ReadStatus> = this.filteredBooks$.pipe(
|
||||
map((books) => {
|
||||
if (!books || books.length === 0) return ReadStatus.UNREAD;
|
||||
const statuses = books.map((b) => (b.readStatus as ReadStatus) ?? ReadStatus.UNREAD);
|
||||
|
||||
const hasWontRead = statuses.includes(ReadStatus.WONT_READ);
|
||||
if (hasWontRead) return ReadStatus.WONT_READ;
|
||||
|
||||
const hasAbandoned = statuses.includes(ReadStatus.ABANDONED);
|
||||
if (hasAbandoned) return ReadStatus.ABANDONED;
|
||||
|
||||
const allRead = statuses.every((s) => s === ReadStatus.READ);
|
||||
if (allRead) return ReadStatus.READ;
|
||||
|
||||
// If any book is currently being read, surface series status as READING
|
||||
const isAnyReading = statuses.some(
|
||||
(s) => s === ReadStatus.READING || s === ReadStatus.RE_READING || s === ReadStatus.PAUSED
|
||||
);
|
||||
if (isAnyReading) return ReadStatus.READING;
|
||||
|
||||
// If some are read and some are unread, surface as PARTIALLY_READ
|
||||
const someRead = statuses.some((s) => s === ReadStatus.READ);
|
||||
if (someRead) return ReadStatus.PARTIALLY_READ;
|
||||
|
||||
const allUnread = statuses.every((s) => s === ReadStatus.UNREAD);
|
||||
if (allUnread) return ReadStatus.UNREAD;
|
||||
|
||||
return ReadStatus.PARTIALLY_READ;
|
||||
})
|
||||
);
|
||||
|
||||
// Progress like "12/20" (read/total)
|
||||
seriesReadProgress$: Observable<string> = this.filteredBooks$.pipe(
|
||||
map((books) => {
|
||||
const total = books?.length ?? 0;
|
||||
const readCount = (books || []).filter((b) => b.readStatus === ReadStatus.READ).length;
|
||||
return `${readCount}/${total}`;
|
||||
})
|
||||
);
|
||||
|
||||
get currentCardSize() {
|
||||
return this.coverScalePreferenceService.currentCardSize;
|
||||
}
|
||||
|
||||
get gridColumnMinWidth(): string {
|
||||
return this.coverScalePreferenceService.gridColumnMinWidth;
|
||||
}
|
||||
|
||||
goToAuthorBooks(author: string): void {
|
||||
this.handleMetadataClick("author", author);
|
||||
}
|
||||
|
||||
goToCategory(category: string): void {
|
||||
this.handleMetadataClick("category", category);
|
||||
}
|
||||
|
||||
goToPublisher(publisher: string): void {
|
||||
this.handleMetadataClick("publisher", publisher);
|
||||
}
|
||||
|
||||
private navigateToFilteredBooks(
|
||||
filterKey: string,
|
||||
filterValue: string
|
||||
): void {
|
||||
this.router.navigate(["/all-books"], {
|
||||
queryParams: {
|
||||
view: "grid",
|
||||
sort: "title",
|
||||
direction: "asc",
|
||||
sidebar: true,
|
||||
filter: `${filterKey}:${filterValue}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private handleMetadataClick(filterKey: string, filterValue: string): void {
|
||||
if (this.metadataCenterViewMode === "dialog") {
|
||||
this.dialogRef?.close();
|
||||
setTimeout(
|
||||
() => this.navigateToFilteredBooks(filterKey, filterValue),
|
||||
200
|
||||
);
|
||||
} else {
|
||||
this.navigateToFilteredBooks(filterKey, filterValue);
|
||||
}
|
||||
}
|
||||
|
||||
toggleExpand(): void {
|
||||
this.isExpanded = !this.isExpanded;
|
||||
}
|
||||
|
||||
getStatusLabel(value: string | ReadStatus | null | undefined): string {
|
||||
const v = (value ?? '').toString().toUpperCase();
|
||||
switch (v) {
|
||||
case ReadStatus.UNREAD:
|
||||
return 'UNREAD';
|
||||
case ReadStatus.READING:
|
||||
return 'READING';
|
||||
case ReadStatus.RE_READING:
|
||||
return 'RE-READING';
|
||||
case ReadStatus.READ:
|
||||
return 'READ';
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
return 'PARTIALLY READ';
|
||||
case ReadStatus.PAUSED:
|
||||
return 'PAUSED';
|
||||
case ReadStatus.ABANDONED:
|
||||
return 'ABANDONED';
|
||||
case ReadStatus.WONT_READ:
|
||||
return "WON'T READ";
|
||||
default:
|
||||
return 'UNSET';
|
||||
}
|
||||
}
|
||||
|
||||
getStatusSeverityClass(status: string): string {
|
||||
const normalized = status?.toUpperCase();
|
||||
switch (normalized) {
|
||||
case "UNREAD":
|
||||
return "bg-gray-500";
|
||||
case "READING":
|
||||
return "bg-blue-600";
|
||||
case "READ":
|
||||
return "bg-green-600";
|
||||
case "PARTIALLY_READ":
|
||||
return "bg-yellow-600";
|
||||
case "PAUSED":
|
||||
return "bg-slate-600";
|
||||
case "RE-READING":
|
||||
case "RE_READING":
|
||||
return "bg-purple-600";
|
||||
case "ABANDONED":
|
||||
return "bg-red-600";
|
||||
case "WONT_READ":
|
||||
return "bg-pink-700";
|
||||
default:
|
||||
return "bg-gray-600";
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
<div class="p-4 min-w-[26rem] min-h-[30rem] flex flex-col">
|
||||
|
||||
<div class="flex flex-col flex-grow">
|
||||
|
||||
@for (shelf of (shelfState$ | async)?.shelves; track shelf) {
|
||||
<div>
|
||||
<div class="flex flex-row items-center gap-4 py-2">
|
||||
<p-checkbox [inputId]="shelf.name" name="group" [value]="shelf" [(ngModel)]="selectedShelves"></p-checkbox>
|
||||
<label [for]="shelf.id">{{ shelf.name }}</label>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div class="flex justify-between items-center pt-4 mt-auto">
|
||||
<p-button outlined="true" label="Create Shelf" (onClick)="createShelfDialog()"></p-button>
|
||||
<div class="flex gap-4">
|
||||
<p-button severity="secondary" label="Cancel" (onClick)="closeDialog()"></p-button>
|
||||
<p-button label="Save" (onClick)="updateBooksShelves()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-dialog [style]="{ width: '26rem', height: '30rem' }" [(visible)]="displayShelfDialog" header="Create Shelf" [modal]="true" [draggable]="false" [closable]="true" (onHide)="closeShelfDialog()">
|
||||
<div class="py-2">
|
||||
<label for="shelfName">Shelf Name</label>
|
||||
<input id="shelfName" type="text" pInputText [(ngModel)]="shelfName" class="w-full"/>
|
||||
</div>
|
||||
<div class="py-4">
|
||||
<label>Shelf Icon</label>
|
||||
@if (!selectedIcon) {
|
||||
<div>
|
||||
<p-button label="Select Icon" icon="pi pi-search" (onClick)="openIconPicker()"></p-button>
|
||||
</div>
|
||||
}
|
||||
@if (selectedIcon) {
|
||||
<div class="flex items-center gap-4">
|
||||
<i [class]="selectedIcon"></i>
|
||||
<p-button icon="pi pi-times" text="true" outlined="true" severity="warn" (onClick)="clearSelectedIcon()"></p-button>
|
||||
</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>
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {MessageService, PrimeTemplate} 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 {ShelfState} from '../../model/state/shelf-state.model';
|
||||
import {Button} from 'primeng/button';
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Dialog} from 'primeng/dialog';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {IconPickerService} from '../../../../shared/service/icon-picker.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-shelf-assigner',
|
||||
standalone: true,
|
||||
templateUrl: './shelf-assigner.component.html',
|
||||
imports: [
|
||||
Button,
|
||||
Checkbox,
|
||||
AsyncPipe,
|
||||
FormsModule,
|
||||
Dialog,
|
||||
InputText,
|
||||
PrimeTemplate
|
||||
],
|
||||
styleUrls: ['./shelf-assigner.component.scss']
|
||||
})
|
||||
export class ShelfAssignerComponent implements OnInit {
|
||||
|
||||
private shelfService = inject(ShelfService);
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private messageService = inject(MessageService);
|
||||
private bookService = inject(BookService);
|
||||
private iconPickerService = inject(IconPickerService);
|
||||
|
||||
shelfState$: Observable<ShelfState> = this.shelfService.shelfState$;
|
||||
book: Book = this.dynamicDialogConfig.data.book;
|
||||
selectedShelves: Shelf[] = [];
|
||||
displayShelfDialog: boolean = false;
|
||||
shelfName: string = '';
|
||||
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
|
||||
isMultiBooks: boolean = this.dynamicDialogConfig.data.isMultiBooks;
|
||||
selectedIcon: string | null = null;
|
||||
|
||||
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({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: `Shelf created: ${this.shelfName}`});
|
||||
this.displayShelfDialog = false;
|
||||
},
|
||||
error: (e) => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to create shelf'});
|
||||
console.error('Error creating shelf:', e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
updateBooksShelves(): void {
|
||||
const idsToAssign = new Set<number | undefined>(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({
|
||||
next: () => {
|
||||
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() {
|
||||
this.iconPickerService.open().subscribe(icon => {
|
||||
if (icon) {
|
||||
this.selectedIcon = icon;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
clearSelectedIcon() {
|
||||
this.selectedIcon = null;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<div class="flex flex-col py-4 px-4 gap-6 h-96 w-96">
|
||||
<div class="flex flex-col gap-10">
|
||||
<div class="flex items-center gap-4">
|
||||
<p>Shelf Name: </p>
|
||||
<input type="text" pInputText [(ngModel)]="shelfName" placeholder="Enter shelf name..."/>
|
||||
</div>
|
||||
<div class="flex items-center gap-5">
|
||||
<p>Shelf Icon:</p>
|
||||
@if (!selectedIcon) {
|
||||
<div>
|
||||
<p-button label="Select Icon" icon="pi pi-search" (onClick)="openIconPicker()"></p-button>
|
||||
</div>
|
||||
}
|
||||
@if (selectedIcon) {
|
||||
<div>
|
||||
<i [class]="selectedIcon" class="text-xl mr-3"></i>
|
||||
<p-button icon="pi pi-times" (onClick)="clearSelectedIcon()" [rounded]="true" [text]="true" [outlined]="true" severity="danger"></p-button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end">
|
||||
<p-button label="Save" icon="pi pi-check" (onClick)="save()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {ShelfService} from '../../service/shelf.service';
|
||||
import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {Shelf} from '../../model/shelf.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {IconPickerService} from '../../../../shared/service/icon-picker.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-shelf-edit-dialog',
|
||||
imports: [
|
||||
Button,
|
||||
InputText,
|
||||
ReactiveFormsModule,
|
||||
FormsModule
|
||||
],
|
||||
templateUrl: './shelf-edit-dialog.component.html',
|
||||
standalone: true,
|
||||
styleUrl: './shelf-edit-dialog.component.scss'
|
||||
})
|
||||
export class ShelfEditDialogComponent implements OnInit{
|
||||
|
||||
private shelfService = inject(ShelfService);
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private messageService = inject(MessageService);
|
||||
private iconPickerService = inject(IconPickerService);
|
||||
|
||||
shelfName: string = '';
|
||||
selectedIcon: string | null = null;
|
||||
shelf!: Shelf | undefined;
|
||||
|
||||
ngOnInit(): void {
|
||||
const shelfId = this.dynamicDialogConfig?.data.shelfId;
|
||||
this.shelf = this.shelfService.getShelfById(shelfId);
|
||||
if(this.shelf) {
|
||||
this.shelfName = this.shelf.name;
|
||||
this.selectedIcon = 'pi pi-' + this.shelf.icon;
|
||||
}
|
||||
}
|
||||
|
||||
openIconPicker() {
|
||||
this.iconPickerService.open().subscribe(icon => {
|
||||
if (icon) {
|
||||
this.selectedIcon = icon;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
clearSelectedIcon() {
|
||||
this.selectedIcon = null;
|
||||
}
|
||||
|
||||
save() {
|
||||
const shelf: Shelf = {
|
||||
name: this.shelfName,
|
||||
icon: this.selectedIcon?.replace('pi pi-', '') || 'heart'
|
||||
};
|
||||
|
||||
this.shelfService.updateShelf(shelf, this.shelf?.id).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'success', summary: 'Shelf Updated', detail: 'The shelf was updated successfully.'});
|
||||
this.dynamicDialogRef.close();
|
||||
},
|
||||
error: (e) => {
|
||||
this.messageService.add({severity: 'error', summary: 'Update Failed', detail: 'An error occurred while updating the shelf. Please try again.'});
|
||||
console.error(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReadStatusHelper {
|
||||
|
||||
getReadStatusIcon(readStatus: ReadStatus | undefined): string {
|
||||
if (!readStatus) return '';
|
||||
switch (readStatus) {
|
||||
case ReadStatus.READ:
|
||||
return 'pi pi-check';
|
||||
case ReadStatus.READING:
|
||||
return 'pi pi-play';
|
||||
case ReadStatus.RE_READING:
|
||||
return 'pi pi-refresh';
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
return 'pi pi-clock';
|
||||
case ReadStatus.PAUSED:
|
||||
return 'pi pi-pause';
|
||||
case ReadStatus.ABANDONED:
|
||||
return 'pi pi-times';
|
||||
case ReadStatus.WONT_READ:
|
||||
return 'pi pi-ban';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
getReadStatusClass(readStatus: ReadStatus | undefined): string {
|
||||
if (!readStatus) return '';
|
||||
switch (readStatus) {
|
||||
case ReadStatus.READ:
|
||||
return 'status-read';
|
||||
case ReadStatus.READING:
|
||||
return 'status-reading';
|
||||
case ReadStatus.RE_READING:
|
||||
return 'status-re-reading';
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
return 'status-partially-read';
|
||||
case ReadStatus.PAUSED:
|
||||
return 'status-paused';
|
||||
case ReadStatus.ABANDONED:
|
||||
return 'status-abandoned';
|
||||
case ReadStatus.WONT_READ:
|
||||
return 'status-wont-read';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
getReadStatusTooltip(readStatus: ReadStatus | undefined): string {
|
||||
if (!readStatus) return '';
|
||||
switch (readStatus) {
|
||||
case ReadStatus.READ:
|
||||
return 'Read';
|
||||
case ReadStatus.READING:
|
||||
return 'Currently Reading';
|
||||
case ReadStatus.RE_READING:
|
||||
return 'Re-reading';
|
||||
case ReadStatus.PARTIALLY_READ:
|
||||
return 'Partially Read';
|
||||
case ReadStatus.PAUSED:
|
||||
return 'Paused';
|
||||
case ReadStatus.ABANDONED:
|
||||
return 'Abandoned';
|
||||
case ReadStatus.WONT_READ:
|
||||
return 'Won\'t Read';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
shouldShowStatusIcon(readStatus: ReadStatus | undefined): boolean {
|
||||
return !!(readStatus && readStatus !== ReadStatus.UNREAD && readStatus !== ReadStatus.UNSET);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import {Shelf} from './shelf.model';
|
||||
import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrollMode, NewPdfReaderSetting} from '../../settings/user-management/user.service';
|
||||
import {BookReview} from '../components/book-reviews/book-review-service';
|
||||
|
||||
export type BookType = "PDF" | "EPUB" | "CBX";
|
||||
|
||||
export enum AdditionalFileType {
|
||||
ALTERNATIVE_FORMAT = 'ALTERNATIVE_FORMAT',
|
||||
SUPPLEMENTARY = 'SUPPLEMENTARY'
|
||||
}
|
||||
|
||||
export interface FileInfo {
|
||||
fileName?: string;
|
||||
filePath?: string;
|
||||
fileSubPath?: string;
|
||||
fileSizeKb?: number;
|
||||
}
|
||||
|
||||
export interface AdditionalFile extends FileInfo {
|
||||
id: number;
|
||||
bookId: number;
|
||||
additionalFileType: AdditionalFileType;
|
||||
description?: string;
|
||||
addedOn?: string;
|
||||
}
|
||||
|
||||
export interface Book extends FileInfo {
|
||||
id: number;
|
||||
bookType: BookType;
|
||||
libraryId: number;
|
||||
libraryName: string;
|
||||
metadata?: BookMetadata;
|
||||
shelves?: Shelf[];
|
||||
lastReadTime?: string;
|
||||
addedOn?: string;
|
||||
epubProgress?: EpubProgress;
|
||||
pdfProgress?: PdfProgress;
|
||||
cbxProgress?: CbxProgress;
|
||||
koreaderProgress?: KoReaderProgress;
|
||||
seriesCount?: number | null;
|
||||
metadataMatchScore?: number | null;
|
||||
readStatus?: ReadStatus;
|
||||
dateFinished?: string;
|
||||
libraryPath?: { id: number };
|
||||
alternativeFormats?: AdditionalFile[];
|
||||
supplementaryFiles?: AdditionalFile[];
|
||||
}
|
||||
|
||||
export interface EpubProgress {
|
||||
cfi: string;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface PdfProgress {
|
||||
page: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface CbxProgress {
|
||||
page: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface KoReaderProgress {
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface BookMetadata {
|
||||
bookId: number;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
publisher?: string;
|
||||
publishedDate?: string;
|
||||
description?: string;
|
||||
seriesName?: string;
|
||||
seriesNumber?: number | null;
|
||||
seriesTotal?: number | null;
|
||||
isbn13?: string;
|
||||
isbn10?: string;
|
||||
asin?: string;
|
||||
goodreadsId?: string;
|
||||
comicvineId?: string;
|
||||
hardcoverId?: string;
|
||||
googleId?: string;
|
||||
pageCount?: number | null;
|
||||
language?: string;
|
||||
rating?: number | null;
|
||||
reviewCount?: number | null;
|
||||
amazonRating?: number | null;
|
||||
amazonReviewCount?: number | null;
|
||||
goodreadsRating?: number | null;
|
||||
goodreadsReviewCount?: number | null;
|
||||
hardcoverRating?: number | null;
|
||||
hardcoverReviewCount?: number | null;
|
||||
personalRating?: number | null;
|
||||
coverUpdatedOn?: string;
|
||||
authors?: string[];
|
||||
categories?: string[];
|
||||
moods?: string[];
|
||||
tags?: string[];
|
||||
provider?: string;
|
||||
providerBookId?: string;
|
||||
thumbnailUrl?: string | null;
|
||||
reviews?: BookReview[];
|
||||
|
||||
titleLocked?: boolean;
|
||||
subtitleLocked?: boolean;
|
||||
publisherLocked?: boolean;
|
||||
publishedDateLocked?: boolean;
|
||||
descriptionLocked?: boolean;
|
||||
seriesNameLocked?: boolean;
|
||||
seriesNumberLocked?: boolean;
|
||||
seriesTotalLocked?: boolean;
|
||||
isbn13Locked?: boolean;
|
||||
isbn10Locked?: boolean;
|
||||
asinLocked?: boolean;
|
||||
comicvineIdLocked?: boolean;
|
||||
goodreadsIdLocked?: boolean;
|
||||
hardcoverIdLocked?: boolean;
|
||||
googleIdLocked?: boolean;
|
||||
pageCountLocked?: boolean;
|
||||
languageLocked?: boolean;
|
||||
personalRatingLocked?: boolean;
|
||||
amazonRatingLocked?: boolean;
|
||||
amazonReviewCountLocked?: boolean;
|
||||
goodreadsRatingLocked?: boolean;
|
||||
goodreadsReviewCountLocked?: boolean;
|
||||
hardcoverRatingLocked?: boolean;
|
||||
hardcoverReviewCountLocked?: boolean;
|
||||
coverUpdatedOnLocked?: boolean;
|
||||
authorsLocked?: boolean;
|
||||
categoriesLocked?: boolean;
|
||||
moodsLocked?: boolean;
|
||||
tagsLocked?: boolean;
|
||||
coverLocked?: boolean;
|
||||
reviewsLocked?: boolean;
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface MetadataClearFlags {
|
||||
title?: boolean;
|
||||
subtitle?: boolean;
|
||||
publisher?: boolean;
|
||||
publishedDate?: boolean;
|
||||
description?: boolean;
|
||||
seriesName?: boolean;
|
||||
seriesNumber?: boolean;
|
||||
seriesTotal?: boolean;
|
||||
isbn13?: boolean;
|
||||
isbn10?: boolean;
|
||||
asin?: boolean;
|
||||
goodreadsId?: boolean;
|
||||
comicvineId?: boolean;
|
||||
hardcoverId?: boolean;
|
||||
googleId?: boolean;
|
||||
pageCount?: boolean;
|
||||
language?: boolean;
|
||||
amazonRating?: boolean;
|
||||
amazonReviewCount?: boolean;
|
||||
goodreadsRating?: boolean;
|
||||
goodreadsReviewCount?: boolean;
|
||||
hardcoverRating?: boolean;
|
||||
hardcoverReviewCount?: boolean;
|
||||
personalRating?: boolean;
|
||||
authors?: boolean;
|
||||
categories?: boolean;
|
||||
moods?: boolean;
|
||||
tags?: boolean;
|
||||
cover?: boolean;
|
||||
}
|
||||
|
||||
export interface MetadataUpdateWrapper {
|
||||
metadata: BookMetadata;
|
||||
clearFlags: MetadataClearFlags;
|
||||
}
|
||||
|
||||
export interface PdfViewerSetting {
|
||||
zoom: string | number;
|
||||
spread: 'off' | 'even' | 'odd';
|
||||
}
|
||||
|
||||
export interface EpubViewerSetting {
|
||||
theme: string;
|
||||
font: string;
|
||||
fontSize: number;
|
||||
flow: string;
|
||||
lineHeight: number;
|
||||
letterSpacing: number;
|
||||
spread: string;
|
||||
}
|
||||
|
||||
export interface CbxViewerSetting {
|
||||
pageSpread: CbxPageSpread;
|
||||
pageViewMode: CbxPageViewMode;
|
||||
fitMode: CbxFitMode;
|
||||
scrollMode?: CbxScrollMode;
|
||||
backgroundColor?: CbxBackgroundColor;
|
||||
}
|
||||
|
||||
export interface BookSetting {
|
||||
pdfSettings?: PdfViewerSetting;
|
||||
epubSettings?: EpubViewerSetting;
|
||||
cbxSettings?: CbxViewerSetting;
|
||||
newPdfSettings?: NewPdfReaderSetting;
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface BookRecommendation {
|
||||
book: Book;
|
||||
similarityScore: number;
|
||||
}
|
||||
|
||||
export interface BulkMetadataUpdateRequest {
|
||||
bookIds: number[];
|
||||
authors?: string[];
|
||||
clearAuthors?: boolean;
|
||||
publisher?: string;
|
||||
clearPublisher?: boolean;
|
||||
language?: string;
|
||||
clearLanguage?: boolean;
|
||||
seriesName?: string;
|
||||
clearSeriesName?: boolean;
|
||||
seriesTotal?: number | null;
|
||||
clearSeriesTotal?: boolean;
|
||||
publishedDate?: string | null;
|
||||
clearPublishedDate?: boolean;
|
||||
genres?: string[];
|
||||
clearGenres?: boolean;
|
||||
}
|
||||
|
||||
export interface BookDeletionResponse {
|
||||
deleted: number[];
|
||||
failedFileDeletions: number[];
|
||||
}
|
||||
|
||||
export enum ReadStatus {
|
||||
UNREAD = 'UNREAD',
|
||||
READING = 'READING',
|
||||
RE_READING = 'RE_READING',
|
||||
READ = 'READ',
|
||||
PARTIALLY_READ = 'PARTIALLY_READ',
|
||||
PAUSED = 'PAUSED',
|
||||
WONT_READ = 'WONT_READ',
|
||||
ABANDONED = 'ABANDONED',
|
||||
UNSET = 'UNSET'
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {SortOption} from './sort.model';
|
||||
|
||||
export type LibraryScanMode = 'FILE_AS_BOOK' | 'FOLDER_AS_BOOK';
|
||||
export type BookFileType = 'PDF' | 'EPUB' | 'CBX';
|
||||
|
||||
export interface Library {
|
||||
id?: number;
|
||||
name: string;
|
||||
icon: string;
|
||||
watch: boolean;
|
||||
fileNamingPattern?: string;
|
||||
sort?: SortOption;
|
||||
paths: LibraryPath[];
|
||||
scanMode?: LibraryScanMode;
|
||||
defaultBookFormat?: BookFileType;
|
||||
}
|
||||
|
||||
export interface LibraryPath {
|
||||
id?: number;
|
||||
path: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import {SortOption} from './sort.model';
|
||||
|
||||
export interface Shelf {
|
||||
id?: number;
|
||||
name: string;
|
||||
icon: string;
|
||||
sort?: SortOption;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export enum SortDirection {
|
||||
ASCENDING = 'ASCENDING',
|
||||
DESCENDING = 'DESCENDING'
|
||||
}
|
||||
|
||||
export interface SortOption {
|
||||
label: string;
|
||||
field: string;
|
||||
direction: SortDirection;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {Book} from '../book.model';
|
||||
|
||||
export interface BookState {
|
||||
books: Book[] | null;
|
||||
loaded: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {Library} from '../library.model';
|
||||
|
||||
export interface LibraryState {
|
||||
libraries: Library[] | null;
|
||||
loaded: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {Shelf} from '../shelf.model';
|
||||
|
||||
export interface ShelfState {
|
||||
shelves: Shelf[] | null;
|
||||
loaded: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {MenuItem} from 'primeng/api';
|
||||
import {BookService} from './book.service';
|
||||
import {readStatusLabels} from '../components/book-browser/book-filter/book-filter.component';
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookMenuService {
|
||||
|
||||
confirmationService = inject(ConfirmationService);
|
||||
messageService = inject(MessageService);
|
||||
bookService = inject(BookService);
|
||||
|
||||
|
||||
getMetadataMenuItems(
|
||||
autoFetchMetadata: () => void,
|
||||
fetchMetadata: () => void,
|
||||
bulkEditMetadata: () => void,
|
||||
multiBookEditMetadata: () => void): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
label: 'Auto Fetch Metadata',
|
||||
icon: 'pi pi-bolt',
|
||||
command: autoFetchMetadata
|
||||
},
|
||||
{
|
||||
label: 'Custom Fetch Metadata',
|
||||
icon: 'pi pi-sync',
|
||||
command: fetchMetadata
|
||||
},
|
||||
{
|
||||
label: 'Bulk Metadata Editor',
|
||||
icon: 'pi pi-table',
|
||||
command: bulkEditMetadata
|
||||
},
|
||||
{
|
||||
label: 'Multi-Book Metadata Editor',
|
||||
icon: 'pi pi-clone',
|
||||
command: multiBookEditMetadata
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
getTieredMenuItems(selectedBooks: Set<number>): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
label: 'Update Read Status',
|
||||
icon: 'pi pi-book',
|
||||
items: Object.entries(readStatusLabels).map(([status, label]) => ({
|
||||
label,
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to mark selected books as "${label}"?`,
|
||||
header: 'Confirm Read Status Update',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: 'Yes',
|
||||
rejectLabel: 'No',
|
||||
accept: () => {
|
||||
this.bookService.updateBookReadStatus(Array.from(selectedBooks), status as ReadStatus).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Read Status Updated',
|
||||
detail: `Marked as "${label}"`,
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Could not update read status.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}))
|
||||
},
|
||||
{
|
||||
label: 'Reset Booklore Progress',
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: 'Are you sure you want to reset Booklore reading progress for selected books?',
|
||||
header: 'Confirm Reset',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: 'Yes',
|
||||
rejectLabel: 'No',
|
||||
accept: () => {
|
||||
this.bookService.resetProgress(Array.from(selectedBooks), ResetProgressTypes.BOOKLORE).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'Booklore reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Could not reset progress.',
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Reset KOReader Progress',
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: 'Are you sure you want to reset KOReader reading progress for selected books?',
|
||||
header: 'Confirm Reset',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: 'Yes',
|
||||
rejectLabel: 'No',
|
||||
accept: () => {
|
||||
this.bookService.resetProgress(Array.from(selectedBooks), ResetProgressTypes.KOREADER).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'KOReader reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Could not reset progress.',
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {catchError, filter, map, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
|
||||
import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus, AdditionalFileType, AdditionalFile} from '../model/book.model';
|
||||
import {BookState} from '../model/state/book-state.model';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model';
|
||||
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private messageService = inject(MessageService);
|
||||
private authService = inject(AuthService);
|
||||
private fileDownloadService = inject(FileDownloadService);
|
||||
|
||||
private bookStateSubject = new BehaviorSubject<BookState>({
|
||||
books: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
private loading$: Observable<Book[]> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.authService.token$.pipe(
|
||||
distinctUntilChanged()
|
||||
).subscribe(token => {
|
||||
if (token === null) {
|
||||
this.bookStateSubject.next({
|
||||
books: null,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
} else {
|
||||
const current = this.bookStateSubject.value;
|
||||
if (current.loaded && !current.books) {
|
||||
this.bookStateSubject.next({
|
||||
books: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bookState$ = this.bookStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchBooks().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
getCurrentBookState(): BookState {
|
||||
return this.bookStateSubject.value;
|
||||
}
|
||||
|
||||
private fetchBooks(): Observable<Book[]> {
|
||||
return this.http.get<Book[]>(this.url).pipe(
|
||||
tap(books => {
|
||||
this.bookStateSubject.next({
|
||||
books: books || [],
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
const curr = this.bookStateSubject.value;
|
||||
this.bookStateSubject.next({
|
||||
books: curr.books,
|
||||
loaded: true,
|
||||
error: error.message,
|
||||
});
|
||||
throw error;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
refreshBooks(): void {
|
||||
this.http.get<Book[]>(this.url).pipe(
|
||||
tap(books => {
|
||||
this.bookStateSubject.next({
|
||||
books: books || [],
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.bookStateSubject.next({
|
||||
books: null,
|
||||
loaded: true,
|
||||
error: error.message,
|
||||
});
|
||||
return of(null);
|
||||
})
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
getBookByIdFromState(bookId: number): Book | undefined {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
return currentState.books?.find(book => +book.id === +bookId);
|
||||
}
|
||||
|
||||
getBooksByIdsFromState(bookIds: number[]): Book[] {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
if (!currentState.books || bookIds.length === 0) return [];
|
||||
|
||||
const idSet = new Set(bookIds.map(id => +id));
|
||||
return currentState.books.filter(book => idSet.has(+book.id));
|
||||
}
|
||||
|
||||
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
|
||||
const requestPayload = {
|
||||
bookIds: Array.from(bookIds),
|
||||
shelvesToAssign: Array.from(shelvesToAssign),
|
||||
shelvesToUnassign: Array.from(shelvesToUnassign),
|
||||
};
|
||||
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
|
||||
map(updatedBooks => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const currentBooks = currentState.books || [];
|
||||
updatedBooks.forEach(updatedBook => {
|
||||
const index = currentBooks.findIndex(b => b.id === updatedBook.id);
|
||||
if (index !== -1) {
|
||||
currentBooks[index] = updatedBook;
|
||||
}
|
||||
});
|
||||
this.bookStateSubject.next({...currentState, books: [...currentBooks]});
|
||||
return updatedBooks;
|
||||
}),
|
||||
catchError(error => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
this.bookStateSubject.next({...currentState, error: error.message});
|
||||
throw error;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
removeBooksByLibraryId(libraryId: number): void {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const currentBooks = currentState.books || [];
|
||||
const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId);
|
||||
this.bookStateSubject.next({...currentState, books: filteredBooks});
|
||||
}
|
||||
|
||||
removeBooksFromShelf(shelfId: number): void {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const currentBooks = currentState.books || [];
|
||||
const updatedBooks = currentBooks.map(book => ({
|
||||
...book,
|
||||
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
|
||||
}));
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||
}
|
||||
|
||||
getBookSetting(bookId: number): Observable<BookSetting> {
|
||||
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`);
|
||||
}
|
||||
|
||||
updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/${bookId}/viewer-setting`, bookSetting);
|
||||
}
|
||||
|
||||
updateLastReadTime(bookId: number) {
|
||||
const timestamp = new Date().toISOString();
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book =>
|
||||
book.id === bookId ? {...book, lastReadTime: timestamp} : book
|
||||
);
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||
}
|
||||
|
||||
readBook(bookId: number, reader?: "ngx" | "streaming"): void {
|
||||
const book = this.bookStateSubject.value.books?.find(b => b.id === bookId);
|
||||
if (!book) {
|
||||
console.error('Book not found');
|
||||
return;
|
||||
}
|
||||
|
||||
let url: string | null = null;
|
||||
switch (book.bookType) {
|
||||
case "PDF":
|
||||
url = !reader || reader === "ngx"
|
||||
? `/pdf-viewer/book/${book.id}`
|
||||
: `/cbx-viewer/book/${book.id}`;
|
||||
break;
|
||||
case "EPUB":
|
||||
url = `/epub-viewer/book/${book.id}`;
|
||||
break;
|
||||
case "CBX":
|
||||
url = `/cbx-viewer/book/${book.id}`;
|
||||
break;
|
||||
default:
|
||||
console.error('Unsupported book type:', book.bookType);
|
||||
return;
|
||||
}
|
||||
|
||||
window.open(url, '_blank');
|
||||
this.updateLastReadTime(book.id);
|
||||
}
|
||||
|
||||
getFileContent(bookId: number): Observable<Blob> {
|
||||
return this.http.get<Blob>(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'});
|
||||
}
|
||||
|
||||
getBookByIdFromAPI(bookId: number, withDescription: boolean) {
|
||||
return this.http.get<Book>(`${this.url}/${bookId}`, {
|
||||
params: {
|
||||
withDescription: withDescription.toString()
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteBooks(ids: Set<number>): Observable<BookDeletionResponse> {
|
||||
const idList = Array.from(ids);
|
||||
const params = new HttpParams().set('ids', idList.join(','));
|
||||
|
||||
return this.http.delete<BookDeletionResponse>(this.url, {params}).pipe(
|
||||
tap(response => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const remainingBooks = (currentState.books || []).filter(
|
||||
book => !ids.has(book.id)
|
||||
);
|
||||
|
||||
this.bookStateSubject.next({
|
||||
books: remainingBooks,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
if (response.failedFileDeletions?.length > 0) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'Some files could not be deleted',
|
||||
detail: `Books: ${response.failedFileDeletions.join(', ')}`,
|
||||
});
|
||||
} else {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Books Deleted',
|
||||
detail: `${idList.length} book(s) deleted successfully.`,
|
||||
});
|
||||
}
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Delete Failed',
|
||||
detail: error?.error?.message || error?.message || 'An error occurred while deleting books.',
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
|
||||
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
|
||||
return this.http.delete<void>(deleteUrl).pipe(
|
||||
tap(() => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book => {
|
||||
if (book.id === bookId) {
|
||||
return {
|
||||
...book,
|
||||
alternativeFormats: book.alternativeFormats?.filter(file => file.id !== fileId),
|
||||
supplementaryFiles: book.supplementaryFiles?.filter(file => file.id !== fileId)
|
||||
};
|
||||
}
|
||||
return book;
|
||||
});
|
||||
|
||||
this.bookStateSubject.next({
|
||||
...currentState,
|
||||
books: updatedBooks
|
||||
});
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'File Deleted',
|
||||
detail: 'Additional file deleted successfully.'
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Delete Failed',
|
||||
detail: error?.error?.message || error?.message || 'An error occurred while deleting the file.'
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
uploadAdditionalFile(bookId: number, file: File, fileType: AdditionalFileType, description?: string): Observable<AdditionalFile> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('additionalFileType', fileType);
|
||||
if (description) {
|
||||
formData.append('description', description);
|
||||
}
|
||||
|
||||
return this.http.post<AdditionalFile>(`${this.url}/${bookId}/files`, formData).pipe(
|
||||
tap((newFile) => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book => {
|
||||
if (book.id === bookId) {
|
||||
const updatedBook = {...book};
|
||||
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
|
||||
updatedBook.alternativeFormats = [...(book.alternativeFormats || []), newFile];
|
||||
} else {
|
||||
updatedBook.supplementaryFiles = [...(book.supplementaryFiles || []), newFile];
|
||||
}
|
||||
return updatedBook;
|
||||
}
|
||||
return book;
|
||||
});
|
||||
|
||||
this.bookStateSubject.next({
|
||||
...currentState,
|
||||
books: updatedBooks
|
||||
});
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'File Uploaded',
|
||||
detail: 'Additional file uploaded successfully.'
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Upload Failed',
|
||||
detail: error?.error?.message || error?.message || 'An error occurred while uploading the file.'
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
downloadFile(bookId: number): void {
|
||||
const downloadUrl = `${this.url}/${bookId}/download`;
|
||||
this.fileDownloadService.downloadFile(downloadUrl, `book_${bookId}`);
|
||||
}
|
||||
|
||||
downloadAdditionalFile(bookId: number, fileId: number): void {
|
||||
const downloadUrl = `${this.url}/${bookId}/files/${fileId}/download`;
|
||||
this.fileDownloadService.downloadFile(downloadUrl, `additional_file_${fileId}`);
|
||||
}
|
||||
|
||||
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
pdfProgress: {
|
||||
page: page,
|
||||
percentage: percentage
|
||||
}
|
||||
}
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
epubProgress: {
|
||||
cfi: cfi,
|
||||
percentage: percentage
|
||||
}
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
cbxProgress: {
|
||||
page: page,
|
||||
percentage: percentage
|
||||
}
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
dateFinished: dateFinished
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body).pipe(
|
||||
tap(() => {
|
||||
// Update the book in the state
|
||||
const currentState = this.bookStateSubject.value;
|
||||
if (currentState.books) {
|
||||
const updatedBooks = currentState.books.map(book => {
|
||||
if (book.id === bookId) {
|
||||
return {...book, dateFinished: dateFinished || undefined};
|
||||
}
|
||||
return book;
|
||||
});
|
||||
this.bookStateSubject.next({
|
||||
...currentState,
|
||||
books: updatedBooks
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
regenerateCovers(): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/regenerate-covers`, {});
|
||||
}
|
||||
|
||||
regenerateCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {});
|
||||
}
|
||||
|
||||
|
||||
/*------------------ All the metadata related calls go here ------------------*/
|
||||
|
||||
fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable<BookMetadata[]> {
|
||||
return this.http.post<BookMetadata[]>(`${this.url}/${bookId}/metadata/prospective`, request);
|
||||
}
|
||||
|
||||
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean): Observable<BookMetadata> {
|
||||
const params = new HttpParams().set('mergeCategories', mergeCategories.toString());
|
||||
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
|
||||
map(updatedMetadata => {
|
||||
this.handleBookMetadataUpdate(bookId!, updatedMetadata);
|
||||
return updatedMetadata;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateBooksMetadata(request: BulkMetadataUpdateRequest, mergeCategories: boolean): Observable<BookMetadata[]> {
|
||||
const params = new HttpParams().set('mergeCategories', mergeCategories.toString());
|
||||
return this.http.put<BookMetadata[]>(`${this.url}/bulk-edit-metadata`, request, {params}).pipe(
|
||||
map(updatedMetadataList => {
|
||||
request.bookIds.forEach((id, index) => {
|
||||
this.handleBookMetadataUpdate(id, updatedMetadataList[index]);
|
||||
});
|
||||
return updatedMetadataList;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
toggleAllLock(bookIds: Set<number>, lock: string): Observable<void> {
|
||||
const requestBody = {
|
||||
bookIds: Array.from(bookIds),
|
||||
lock: lock
|
||||
};
|
||||
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
|
||||
tap((updatedMetadataList) => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book => {
|
||||
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
|
||||
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
|
||||
});
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||
}),
|
||||
map(() => void 0),
|
||||
catchError((error) => {
|
||||
throw error;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getComicInfoMetadata(bookId: number): Observable<BookMetadata> {
|
||||
return this.http.get<BookMetadata>(`${this.url}/${bookId}/cbx/metadata/comicinfo`);
|
||||
}
|
||||
|
||||
autoRefreshMetadata(metadataRefreshRequest: MetadataRefreshRequest): Observable<any> {
|
||||
return this.http.put<void>(`${this.url}/metadata/refresh`, metadataRefreshRequest).pipe(
|
||||
map(() => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Metadata Update Scheduled',
|
||||
detail: 'The metadata update for the selected books has been successfully scheduled.'
|
||||
});
|
||||
return {success: true};
|
||||
}),
|
||||
catchError((e) => {
|
||||
if (e.status === 409) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Task Already Running',
|
||||
life: 5000,
|
||||
detail: 'A metadata refresh task is already in progress. Please wait for it to complete before starting another one.'
|
||||
});
|
||||
} else {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Metadata Update Failed',
|
||||
life: 5000,
|
||||
detail: 'An unexpected error occurred while scheduling the metadata update. Please try again later or contact support if the issue persists.'
|
||||
});
|
||||
}
|
||||
return of({success: false});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getUploadCoverUrl(bookId: number): string {
|
||||
return this.url + '/' + bookId + "/metadata/cover/upload"
|
||||
}
|
||||
|
||||
uploadCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
|
||||
return this.http
|
||||
.post<BookMetadata>(`${this.url}/${bookId}/metadata/cover/from-url`, {url})
|
||||
.pipe(
|
||||
tap(updatedMetadata =>
|
||||
this.handleBookMetadataUpdate(bookId, updatedMetadata)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
|
||||
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
|
||||
params: {limit: limit.toString()}
|
||||
});
|
||||
}
|
||||
|
||||
getBooksInSeries(bookId: number): Observable<Book[]> {
|
||||
return this.bookStateSubject.asObservable().pipe(
|
||||
filter(state => state.loaded),
|
||||
first(),
|
||||
map(state => {
|
||||
const allBooks = state.books || [];
|
||||
const currentBook = allBooks.find(b => b.id === bookId);
|
||||
|
||||
if (!currentBook || !currentBook.metadata?.seriesName) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const seriesName = currentBook.metadata.seriesName.toLowerCase();
|
||||
return allBooks.filter(b => b.metadata?.seriesName?.toLowerCase() === seriesName);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<Book[]> {
|
||||
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
|
||||
const params = new HttpParams().set('type', ResetProgressTypes[type]);
|
||||
return this.http.post<Book[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
|
||||
tap(updatedBooks => updatedBooks.forEach(book => this.handleBookUpdate(book)))
|
||||
);
|
||||
}
|
||||
|
||||
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<Book[]> {
|
||||
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
|
||||
return this.http.put<Book[]>(`${this.url}/read-status`, {ids, status}).pipe(
|
||||
tap(updatedBooks => {
|
||||
updatedBooks.forEach(updatedBook => this.handleBookUpdate(updatedBook));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
consolidateMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', targetValues: string[], valuesToMerge: string[]): Observable<any> {
|
||||
const payload = {metadataType, targetValues, valuesToMerge};
|
||||
return this.http.post(`${this.url}/metadata/manage/consolidate`, payload).pipe(
|
||||
tap(() => {
|
||||
this.refreshBooks();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', valuesToDelete: string[]): Observable<any> {
|
||||
const payload = {metadataType, valuesToDelete};
|
||||
return this.http.post(`${this.url}/metadata/manage/delete`, payload).pipe(
|
||||
tap(() => {
|
||||
this.refreshBooks();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/*------------------ All the websocket handlers go below ------------------*/
|
||||
|
||||
handleNewlyCreatedBook(book: Book): void {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = currentState.books ? [...currentState.books] : [];
|
||||
const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id);
|
||||
if (bookIndex > -1) {
|
||||
updatedBooks[bookIndex] = book;
|
||||
} else {
|
||||
updatedBooks.push(book);
|
||||
}
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||
}
|
||||
|
||||
handleRemovedBookIds(removedBookIds: number[]): void {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id));
|
||||
this.bookStateSubject.next({...currentState, books: filteredBooks});
|
||||
}
|
||||
|
||||
handleBookUpdate(updatedBook: Book) {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book =>
|
||||
book.id === updatedBook.id ? updatedBook : book
|
||||
);
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||
}
|
||||
|
||||
handleMultipleBookUpdates(updatedBooks: Book[]): void {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const currentBooks = currentState.books || [];
|
||||
|
||||
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
|
||||
|
||||
const mergedBooks = currentBooks.map(book =>
|
||||
updatedMap.has(book.id) ? updatedMap.get(book.id)! : book
|
||||
);
|
||||
|
||||
this.bookStateSubject.next({...currentState, books: mergedBooks});
|
||||
}
|
||||
|
||||
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata) {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book => {
|
||||
return book.id == bookId ? {...book, metadata: updatedMetadata} : book
|
||||
});
|
||||
this.bookStateSubject.next({...currentState, books: updatedBooks})
|
||||
}
|
||||
|
||||
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
|
||||
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
|
||||
|
||||
const requestBody = {
|
||||
bookIds: Array.from(bookIdSet),
|
||||
fieldActions
|
||||
};
|
||||
|
||||
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
|
||||
tap(() => {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
const updatedBooks = (currentState.books || []).map(book => {
|
||||
if (!bookIdSet.has(book.id)) return book;
|
||||
const updatedMetadata = {...book.metadata};
|
||||
for (const [field, action] of Object.entries(fieldActions)) {
|
||||
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
|
||||
if (lockField in updatedMetadata) {
|
||||
(updatedMetadata as any)[lockField] = action === 'LOCK';
|
||||
}
|
||||
}
|
||||
return {
|
||||
...book,
|
||||
metadata: updatedMetadata
|
||||
};
|
||||
});
|
||||
this.bookStateSubject.next({
|
||||
...currentState,
|
||||
books: updatedBooks as Book[]
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Field Lock Update Failed',
|
||||
detail: 'Failed to update metadata field locks. Please try again.',
|
||||
});
|
||||
throw error;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class CbxReaderService {
|
||||
|
||||
private readonly pagesUrl = `${API_CONFIG.BASE_URL}/api/v1/cbx`;
|
||||
private readonly imageUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book`;
|
||||
private authService = inject(AuthService);
|
||||
private http = inject(HttpClient);
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
private appendToken(url: string): string {
|
||||
const token = this.getToken();
|
||||
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
|
||||
}
|
||||
|
||||
getAvailablePages(bookId: number) {
|
||||
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
|
||||
}
|
||||
|
||||
getPageImageUrl(bookId: number, page: number): string {
|
||||
return this.appendToken(`${this.imageUrl}/${bookId}/cbx/pages/${page}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||
import {Router} from '@angular/router';
|
||||
import {LibraryService} from './library.service';
|
||||
import {ShelfService} from './shelf.service';
|
||||
import {BookService} from './book.service';
|
||||
import {Library} from '../model/library.model';
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {LibraryCreatorComponent} from '../../library-creator/library-creator.component';
|
||||
import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component';
|
||||
import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {MetadataFetchOptionsComponent} from '../../metadata/component/metadata-options-dialog/metadata-fetch-options-component/metadata-fetch-options.component';
|
||||
import {MagicShelfComponent} from '../../magic-shelf/component/magic-shelf-component';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class LibraryShelfMenuService {
|
||||
|
||||
private confirmationService = inject(ConfirmationService);
|
||||
private messageService = inject(MessageService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private shelfService = inject(ShelfService);
|
||||
private bookService = inject(BookService);
|
||||
private router = inject(Router);
|
||||
private dialogService = inject(DialogService);
|
||||
private magicShelfService = inject(MagicShelfService);
|
||||
|
||||
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
label: 'Options',
|
||||
items: [
|
||||
{
|
||||
label: 'Edit Library',
|
||||
icon: 'pi pi-pen-to-square',
|
||||
command: () => {
|
||||
this.dialogService.open(LibraryCreatorComponent, {
|
||||
header: 'Edit Library',
|
||||
modal: true,
|
||||
closable: true,
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
},
|
||||
data: {
|
||||
mode: 'edit',
|
||||
libraryId: entity?.id
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Delete Library',
|
||||
icon: 'pi pi-trash',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete library: ${entity?.name}?`,
|
||||
header: 'Confirmation',
|
||||
rejectButtonProps: {
|
||||
label: 'Cancel',
|
||||
severity: 'secondary',
|
||||
},
|
||||
acceptButtonProps: {
|
||||
label: 'Yes',
|
||||
severity: 'success',
|
||||
},
|
||||
accept: () => {
|
||||
this.libraryService.deleteLibrary(entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.router.navigate(['/']);
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Library was deleted'});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete library',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Re-scan Library',
|
||||
icon: 'pi pi-refresh',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to refresh library: ${entity?.name}?`,
|
||||
header: 'Confirmation',
|
||||
rejectButtonProps: {
|
||||
label: 'Cancel',
|
||||
severity: 'secondary',
|
||||
},
|
||||
acceptButtonProps: {
|
||||
label: 'Yes',
|
||||
severity: 'success',
|
||||
},
|
||||
accept: () => {
|
||||
this.libraryService.refreshLibrary(entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Library refresh scheduled'});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to refresh library',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Custom Fetch Metadata',
|
||||
icon: 'pi pi-sync',
|
||||
command: () => {
|
||||
this.dialogService.open(MetadataFetchOptionsComponent, {
|
||||
header: 'Metadata Refresh Options',
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
libraryId: entity?.id,
|
||||
metadataRefreshType: MetadataRefreshType.LIBRARY
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Auto Fetch Metadata',
|
||||
icon: 'pi pi-bolt',
|
||||
command: () => {
|
||||
this.bookService.autoRefreshMetadata({
|
||||
refreshType: MetadataRefreshType.LIBRARY,
|
||||
libraryId: entity?.id || undefined
|
||||
}).subscribe();
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
initializeShelfMenuItems(entity: any): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
label: 'Options',
|
||||
items: [
|
||||
{
|
||||
label: 'Edit Shelf',
|
||||
icon: 'pi pi-pen-to-square',
|
||||
command: () => {
|
||||
this.dialogService.open(ShelfEditDialogComponent, {
|
||||
header: 'Edit Shelf',
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
shelfId: entity?.id
|
||||
},
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '15%',
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Delete Shelf',
|
||||
icon: 'pi pi-trash',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete shelf: ${entity?.name}?`,
|
||||
header: 'Confirmation',
|
||||
accept: () => {
|
||||
this.shelfService.deleteShelf(entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.router.navigate(['/']);
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Shelf was deleted'});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete shelf',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
initializeMagicShelfMenuItems(entity: any): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
label: 'Options',
|
||||
items: [
|
||||
{
|
||||
label: 'Edit Magic Shelf',
|
||||
icon: 'pi pi-pen-to-square',
|
||||
command: () => {
|
||||
this.dialogService.open(MagicShelfComponent, {
|
||||
header: 'Edit Magic Shelf',
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
id: entity?.id
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Delete Magic Shelf',
|
||||
icon: 'pi pi-trash',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete magic shelf: ${entity?.name}?`,
|
||||
header: 'Confirmation',
|
||||
accept: () => {
|
||||
this.magicShelfService.deleteShelf(entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.router.navigate(['/']);
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Magic shelf was deleted'});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete shelf',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {catchError, distinctUntilChanged, finalize, map, shareReplay, tap} from 'rxjs/operators';
|
||||
|
||||
import {Library} from '../model/library.model';
|
||||
import {LibraryState} from '../model/state/library-state.model';
|
||||
import {BookService} from './book.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LibraryService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`;
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
private libraryStateSubject = new BehaviorSubject<LibraryState>({
|
||||
libraries: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
private loading$: Observable<Library[]> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.authService.token$.pipe(
|
||||
distinctUntilChanged()
|
||||
).subscribe(token => {
|
||||
if (token === null) {
|
||||
this.libraryStateSubject.next({
|
||||
libraries: null,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
} else {
|
||||
const current = this.libraryStateSubject.value;
|
||||
if (current.loaded && !current.libraries) {
|
||||
this.libraryStateSubject.next({
|
||||
libraries: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
libraryState$ = this.libraryStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchLibraries().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
private fetchLibraries(): Observable<Library[]> {
|
||||
return this.http.get<Library[]>(this.url).pipe(
|
||||
tap(libs => this.libraryStateSubject.next({libraries: libs, loaded: true, error: null})),
|
||||
catchError(err => {
|
||||
const current = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({libraries: current.libraries, loaded: true, error: err.message});
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
createLibrary(lib: Library): Observable<Library> {
|
||||
return this.http.post<Library>(this.url, lib).pipe(
|
||||
map(created => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const updated = curr.libraries ? [...curr.libraries, created] : [created];
|
||||
this.libraryStateSubject.next({...curr, libraries: updated});
|
||||
return created;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateLibrary(lib: Library, id?: number): Observable<Library> {
|
||||
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
|
||||
map(updated => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
|
||||
this.libraryStateSubject.next({...curr, libraries: list});
|
||||
return updated;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteLibrary(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
this.bookService.removeBooksByLibraryId(id);
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const filtered = curr.libraries?.filter(l => l.id !== id) || [];
|
||||
this.libraryStateSubject.next({...curr, libraries: filtered});
|
||||
}),
|
||||
catchError(err => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({...curr, error: err.message});
|
||||
return of();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
refreshLibrary(id: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
|
||||
catchError(err => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({...curr, error: err.message});
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateLibraryFileNamingPattern(id: number, pattern: string): Observable<Library> {
|
||||
return this.http
|
||||
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
|
||||
.pipe(
|
||||
map(updated => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
|
||||
this.libraryStateSubject.next({...curr, libraries: list});
|
||||
return updated;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
doesLibraryExistByName(name: string): boolean {
|
||||
return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name);
|
||||
}
|
||||
|
||||
findLibraryById(id: number): Library | undefined {
|
||||
return this.libraryStateSubject.value.libraries?.find(l => l.id === id);
|
||||
}
|
||||
|
||||
getLibrariesFromState(): Library[] {
|
||||
return this.libraryStateSubject.value.libraries || [];
|
||||
}
|
||||
|
||||
getLibraryPathById(pathId: number): string | undefined {
|
||||
return this.libraryStateSubject.value.libraries
|
||||
?.find(lib => lib.paths.some(p => p.id === pathId))
|
||||
?.paths.find(p => p.id === pathId)?.path;
|
||||
}
|
||||
|
||||
getBookCount(libraryId: number): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable, map} from 'rxjs';
|
||||
import {BookMetadata} from '../model/book.model';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MetadataBatchProgressNotification} from '../../../shared/model/metadata-batch-progress.model';
|
||||
|
||||
export enum FetchedMetadataProposalStatus {
|
||||
FETCHED = 'FETCHED',
|
||||
ACCEPTED = 'ACCEPTED',
|
||||
REJECTED = 'REJECTED',
|
||||
}
|
||||
|
||||
export interface FetchedProposal {
|
||||
proposalId: number;
|
||||
taskId: string;
|
||||
bookId: number;
|
||||
fetchedAt: string;
|
||||
reviewedAt: string | null;
|
||||
reviewerUserId: string | null;
|
||||
status: FetchedMetadataProposalStatus;
|
||||
metadataJson: BookMetadata;
|
||||
}
|
||||
|
||||
export interface MetadataFetchTask {
|
||||
id: string;
|
||||
status: string;
|
||||
completed: number;
|
||||
totalBooks: number;
|
||||
startedAt: string;
|
||||
completedAt: string | null;
|
||||
initiatedBy: string;
|
||||
errorMessage: string | null;
|
||||
|
||||
proposals: FetchedProposal[];
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class MetadataTaskService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/metadata/tasks`;
|
||||
private http = inject(HttpClient);
|
||||
|
||||
getTaskWithProposals(taskId: string): Observable<MetadataFetchTask> {
|
||||
return this.http.get<{ task: MetadataFetchTask }>(`${this.url}/${taskId}`)
|
||||
.pipe(
|
||||
map(response => response.task)
|
||||
);
|
||||
}
|
||||
|
||||
deleteTask(taskId: string): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${taskId}`);
|
||||
}
|
||||
|
||||
updateProposalStatus(taskId: string, proposalId: number, status: string): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${taskId}/proposals/${proposalId}/status`, null, {
|
||||
params: {status}
|
||||
});
|
||||
}
|
||||
|
||||
getActiveTasks(): Observable<MetadataBatchProgressNotification[]> {
|
||||
return this.http.get<MetadataBatchProgressNotification[]>(`${this.url}/active`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class NewPdfReaderService {
|
||||
|
||||
private readonly pagesUrl = `${API_CONFIG.BASE_URL}/api/v1/pdf`;
|
||||
private readonly imageUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book`;
|
||||
private authService = inject(AuthService);
|
||||
private http = inject(HttpClient);
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
private appendToken(url: string): string {
|
||||
const token = this.getToken();
|
||||
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
|
||||
}
|
||||
|
||||
getAvailablePages(bookId: number) {
|
||||
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
|
||||
}
|
||||
|
||||
getPageImageUrl(bookId: number, page: number): string {
|
||||
return this.appendToken(`${this.imageUrl}/${bookId}/pdf/pages/${page}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {tap, catchError, map, shareReplay, finalize} from 'rxjs/operators';
|
||||
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
import {ShelfState} from '../model/state/shelf-state.model';
|
||||
import {BookService} from './book.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class ShelfService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
|
||||
private shelfStateSubject = new BehaviorSubject<ShelfState>({
|
||||
shelves: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
private loading$: Observable<Shelf[]> | null = null;
|
||||
|
||||
shelfState$ = this.shelfStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchShelves().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
private fetchShelves(): Observable<Shelf[]> {
|
||||
return this.http.get<Shelf[]>(this.url).pipe(
|
||||
tap(shelves => this.shelfStateSubject.next({shelves, loaded: true, error: null})),
|
||||
catchError(err => {
|
||||
const curr = this.shelfStateSubject.value;
|
||||
this.shelfStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public reloadShelves(): void {
|
||||
this.fetchShelves().subscribe({
|
||||
next: () => {
|
||||
},
|
||||
error: () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
createShelf(shelf: Shelf): Observable<Shelf> {
|
||||
return this.http.post<Shelf>(this.url, shelf).pipe(
|
||||
map(newShelf => {
|
||||
const curr = this.shelfStateSubject.value;
|
||||
const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
|
||||
this.shelfStateSubject.next({...curr, shelves: updated});
|
||||
return newShelf;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
|
||||
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
|
||||
map(updated => {
|
||||
const curr = this.shelfStateSubject.value;
|
||||
const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated];
|
||||
this.shelfStateSubject.next({...curr, shelves: list});
|
||||
return updated;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteShelf(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
this.bookService.removeBooksFromShelf(id);
|
||||
const curr = this.shelfStateSubject.value;
|
||||
const filtered = curr.shelves?.filter(s => s.id !== id) || [];
|
||||
this.shelfStateSubject.next({...curr, shelves: filtered});
|
||||
}),
|
||||
catchError(err => {
|
||||
const curr = this.shelfStateSubject.value;
|
||||
this.shelfStateSubject.next({...curr, error: err.message});
|
||||
return of();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getShelfById(id: number): Shelf | undefined {
|
||||
return this.shelfStateSubject.value.shelves?.find(s => s.id === id);
|
||||
}
|
||||
|
||||
getBookCount(shelfId: number): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state =>
|
||||
(state.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
getUnshelvedBookCount(): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state =>
|
||||
(state.books || []).filter(b => !b.shelves || b.shelves.length === 0).length
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Book} from '../model/book.model';
|
||||
import {SortDirection, SortOption} from "../model/sort.model";
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SortService {
|
||||
|
||||
private readonly fieldExtractors: Record<string, (book: Book) => any> = {
|
||||
title: (book) => (book.seriesCount ? (book.metadata?.seriesName?.toLowerCase() || null) : null)
|
||||
?? (book.metadata?.title?.toLowerCase() || null),
|
||||
titleSeries: (book) => {
|
||||
const title = book.metadata?.title?.toLowerCase() || '';
|
||||
const series = book.metadata?.seriesName?.toLowerCase();
|
||||
const seriesNumber = book.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
|
||||
if (series) {
|
||||
return [series, seriesNumber];
|
||||
}
|
||||
return [title, Number.MAX_SAFE_INTEGER];
|
||||
},
|
||||
author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null,
|
||||
publishedDate: (book) => book.metadata?.publishedDate === null ? null : new Date(book.metadata?.publishedDate!).getTime(),
|
||||
publisher: (book) => book.metadata?.publisher || null,
|
||||
pageCount: (book) => book.metadata?.pageCount || null,
|
||||
rating: (book) => book.metadata?.rating || null,
|
||||
reviewCount: (book) => book.metadata?.reviewCount || null,
|
||||
amazonRating: (book) => book.metadata?.amazonRating || null,
|
||||
amazonReviewCount: (book) => book.metadata?.amazonReviewCount || null,
|
||||
goodreadsRating: (book) => book.metadata?.goodreadsRating || null,
|
||||
goodreadsReviewCount: (book) => book.metadata?.goodreadsReviewCount || null,
|
||||
hardcoverRating: (book) => book.metadata?.hardcoverRating || null,
|
||||
hardcoverReviewCount: (book) => book.metadata?.hardcoverReviewCount || null,
|
||||
locked: (book) =>
|
||||
Object.keys(book.metadata ?? {})
|
||||
.filter((key) => key.endsWith('Locked'))
|
||||
.every((key) => book.metadata?.[key] === true),
|
||||
lastReadTime: (book) => book.lastReadTime ? new Date(book.lastReadTime).getTime() : null,
|
||||
addedOn: (book) => book.addedOn ? new Date(book.addedOn).getTime() : null,
|
||||
fileSizeKb: (book) => book.fileSizeKb || null
|
||||
};
|
||||
|
||||
applySort(books: Book[], selectedSort: SortOption | null): Book[] {
|
||||
if (!selectedSort) return books;
|
||||
|
||||
const {field, direction} = selectedSort;
|
||||
const extractor = this.fieldExtractors[field];
|
||||
|
||||
if (!extractor) {
|
||||
console.warn(`[SortService] No extractor for field: ${field}`);
|
||||
return books;
|
||||
}
|
||||
|
||||
return books.slice().sort((a, b) => {
|
||||
const aValue = extractor(a);
|
||||
const bValue = extractor(b);
|
||||
|
||||
let result: number;
|
||||
|
||||
if (Array.isArray(aValue) && Array.isArray(bValue)) {
|
||||
const nameCompare = aValue[0]?.localeCompare?.(bValue[0]) ?? 0;
|
||||
result = nameCompare !== 0 ? nameCompare : (aValue[1] - bValue[1]);
|
||||
} else if (typeof aValue === 'string' && typeof bValue === 'string') {
|
||||
result = aValue.localeCompare(bValue);
|
||||
} else if (typeof aValue === 'number' && typeof bValue === 'number') {
|
||||
result = aValue - bValue;
|
||||
} else {
|
||||
// Handle nulls or mismatches
|
||||
if (aValue == null && bValue != null) return 1;
|
||||
if (aValue != null && bValue == null) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
return direction === SortDirection.ASCENDING ? result : -result;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user