fix(dashboard): improve performance with OnPush change detection (#440)

* fix(dashboard): improve performance with OnPush change detection

* fix(dashboard): refactor book card component for improved readability and performance

* fix(tests): mock matchMedia for improved test compatibility

* fix(tests): matchMedia mock for better CI compatibility and support

* fix(dashboard): add clearAll method to BookBrowserScrollService and update tests

* fix(dashboard): improve performance with content visibility and refactor styles

* fix(dashboard): improve scroll performance with estimated total height and refactor layout

* fix(tests): add mock for getCurrentUser in userService for improved test coverage

* fix(dashboard): implement infinite scroll for book loading and scroll restoration

* fix(tests): fix lint error

* fix(tests): mock ResizeObserver and IntersectionObserver

* fix(tests): mock ResizeObserver and IntersectionObserver (again)

* fix(dashboard): improve accessibility and performance by updating aria attributes and optimizing animations

* fix(dashboard): improve submenu accessibility and optimize virtual scroller performance

* fix(dashboard): clean up imports and improve component structure

* fix(dashboard): correct mobile check in author browser component

* fix(dashboard): add OnDestroy lifecycle hook to BookBrowserComponent
This commit is contained in:
brios
2026-04-22 17:27:11 -04:00
committed by Zach Yale
parent a779de8f57
commit 85e8d235b6
140 changed files with 1546 additions and 1233 deletions
@@ -1,126 +1,121 @@
<div class="book-card"
[class.selected]="isSelected"
[class.selected]="isSelected()"
role="button"
tabindex="0"
(click)="onCardClick($event)"
(keydown.enter)="onCardClick($event)">
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive || !hasDigitalFile(), 'audiobook-cover': _isAudiobook, 'square-library-cover': useSquareCovers }">
@if (coverImageUrl) {
<div class="cover-container" [ngClass]="{ 'center-info-btn': isSeriesViewActive() || !hasDigitalFile(), 'audiobook-cover': isAudiobook(), 'square-library-cover': useSquareCovers() }">
@if (coverImageUrl(); as url) {
<img
[src]="coverImageUrl"
[src]="url"
class="book-cover"
[class.square-cover]="_isAudiobook || useSquareCovers"
[alt]="('book.card.alt.cover' | transloco: { title: displayTitle })"
[class.square-cover]="isAudiobook() || useSquareCovers()"
[alt]="('book.card.alt.cover' | transloco: { title: displayTitle() })"
width="250"
[height]="(_isAudiobook || useSquareCovers) ? 250 : 350"
[height]="(isAudiobook() || useSquareCovers()) ? 250 : 350"
loading="lazy"
decoding="async"
fetchpriority="low"/>
} @else {
<app-cover-placeholder class="book-cover" [class.square-cover]="_isAudiobook || useSquareCovers" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" />
<app-cover-placeholder class="book-cover" [class.square-cover]="isAudiobook() || useSquareCovers()" [title]="book().metadata?.title ?? ''" [author]="(book().metadata?.authors ?? []).join(', ')" />
}
<div class="top-left-overlay-stack">
@if ((overlayPreferenceService?.showBookTypePill() ?? true) && getDisplayFormat(); as displayFormat) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + displayFormat.toLowerCase()">
{{ displayFormat }}
@if (showBookTypePill() && displayFormat(); as fmt) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + fmt.toLowerCase()">
{{ fmt }}
</div>
}
@if (!book.seriesCount && book.metadata?.seriesNumber !== null && book.metadata?.seriesNumber !== undefined) {
@if (!book().seriesCount && book().metadata?.seriesNumber !== null && book().metadata?.seriesNumber !== undefined) {
<div class="series-number-overlay">
#{{ book.metadata?.seriesNumber }}
#{{ book().metadata?.seriesNumber }}
</div>
}
@if (book.seriesCount && book.seriesCount >= 1) {
@if (book().seriesCount && book().seriesCount! >= 1) {
<div class="series-items-count-overlay">
<i class="pi pi-book series-items-count-icon"></i>{{ book.seriesCount }}
<i class="pi pi-book series-items-count-icon"></i>{{ book().seriesCount }}
</div>
}
</div>
@if (_isSeriesViewActive) {
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openSeriesInfo()" [ariaLabel]="'book.card.alt.viewSeriesInfo' | transloco"></p-button>
@if (isSeriesViewActive()) {
<button type="button" class="p-button p-component p-button-rounded info-btn" (click)="openSeriesInfo()" [attr.aria-label]="'book.card.alt.viewSeriesInfo' | transloco">
<i class="pi pi-info"></i>
</button>
} @else {
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)" [ariaLabel]="'book.card.alt.viewDetails' | transloco">
</p-button>
<button type="button" class="p-button p-component p-button-rounded info-btn" (click)="openBookInfo(book())" [attr.aria-label]="'book.card.alt.viewDetails' | transloco">
<i class="pi pi-info"></i>
</button>
}
@if (!_isSeriesViewActive && hasDigitalFile()) {
<a [routerLink]="urlHelper.getBookPrimaryReadingUrl(book)" (click)="readBook(book)"><p-button [rounded]="true" [icon]="readButtonIcon" class="read-btn" (click)="readBook(book)"
[pTooltip]="_isContinueReading ? ('book.card.alt.continueReading' | transloco) : ''"
tooltipPosition="bottom"
[ariaLabel]="_isContinueReading ? ('book.card.alt.continueReading' | transloco) : (_isAudiobook ? ('book.card.alt.playAudiobook' | transloco) : ('book.card.alt.readBook' | transloco))"></p-button></a>
@if (!isSeriesViewActive() && hasDigitalFile()) {
<a [routerLink]="readingUrl()" (click)="readBook(book())"
class="p-button p-component p-button-rounded read-btn"
[pTooltip]="isContinueReading() ? ('book.card.alt.continueReading' | transloco) : ''"
tooltipPosition="bottom"
[attr.aria-label]="isContinueReading() ? ('book.card.alt.continueReading' | transloco) : (isAudiobook() ? ('book.card.alt.playAudiobook' | transloco) : ('book.card.alt.readBook' | transloco))">
<i [class]="readButtonIcon()"></i>
</a>
}
@if (isCheckboxEnabled) {
@if (isCheckboxEnabled()) {
<p-checkbox
[binary]="true"
class="select-checkbox"
(click)="captureMouseEvent($event)"
[ngModel]="isSelected"
[ngModel]="isSelected()"
(onChange)="toggleSelection($event)">
</p-checkbox>
}
@if (hasProgress) {
<div class="cover-progress-bar-container" [pTooltip]="progressTooltip" tooltipPosition="top">
@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 (hasProgress()) {
<div class="cover-progress-bar-container" [pTooltip]="progressTooltip()" tooltipPosition="top">
@if (progressPercentage() !== null) {
<div class="cover-progress-bar" [ngClass]="{ 'progress-complete': progressPercentage() === 100, 'progress-incomplete': progressPercentage()! < 100 }">
<div class="progress-fill" [style.width.%]="progressPercentage()!"></div>
</div>
}
@if (_koProgressPercentage !== null) {
<p-progressBar
[value]="_koProgressPercentage"
[showValue]="false"
class="cover-progress-bar"
[ngClass]="_koProgressPercentage === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'">
</p-progressBar>
@if (koProgressPercentage() !== null) {
<div class="cover-progress-bar" [ngClass]="koProgressPercentage() === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'">
<div class="progress-fill" [style.width.%]="koProgressPercentage()!"></div>
</div>
}
@if (_koboProgressPercentage !== null) {
<p-progressBar
[value]="_koboProgressPercentage"
[showValue]="false"
class="cover-progress-bar"
[ngClass]="_koboProgressPercentage === 100 ? 'progress-complete-kobo' : 'progress-incomplete-kobo'">
</p-progressBar>
@if (koboProgressPercentage() !== null) {
<div class="cover-progress-bar" [ngClass]="koboProgressPercentage() === 100 ? 'progress-complete-kobo' : 'progress-incomplete-kobo'">
<div class="progress-fill" [style.width.%]="koboProgressPercentage()!"></div>
</div>
}
</div>
}
</div>
@if (!bottomBarHidden) {
@if (!bottomBarHidden()) {
<div class="book-title-container">
<div class="read-status-indicator"
[ngClass]="_readStatusClass"
[pTooltip]="readStatusTooltip"
[ngClass]="readStatusClass()"
[pTooltip]="readStatusTooltip()"
tooltipPosition="bottom"
(click)="toggleReadStatusMenu($event, readStatusMenu)"
(keydown.enter)="toggleReadStatusMenu($event, readStatusMenu)"
role="button"
tabindex="0"
[attr.aria-label]="'book.card.alt.readStatusMenu' | transloco">
<i [class]="_readStatusIcon" style="font-size: 0.9rem"></i>
<i [class]="readStatusIcon()" style="font-size: 0.9rem"></i>
</div>
<p-tieredmenu #readStatusMenu [model]="readStatusMenuItems" [popup]="true" appendTo="body"></p-tieredmenu>
<p-tieredmenu #readStatusMenu [model]="readStatusMenuItems()" [popup]="true" appendTo="body"></p-tieredmenu>
<h4 class="book-title"
tooltipPosition="bottom"
[pTooltip]="titleTooltip">
{{ displayTitle }}
[pTooltip]="titleTooltip()">
{{ displayTitle() }}
</h4>
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu>
<p-button
class="custom-button-padding"
size="small"
[text]="true"
<p-tieredmenu #menu [model]="items()" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu>
<button type="button"
class="p-button p-component p-button-text p-button-sm custom-button-padding"
(click)="onMenuToggle($event, menu)"
icon="pi pi-ellipsis-v"
[ariaLabel]="'book.card.alt.bookMenu' | transloco">
</p-button>
[attr.aria-label]="'book.card.alt.bookMenu' | transloco">
<i class="pi pi-ellipsis-v"></i>
</button>
</div>
}
</div>
@@ -100,7 +100,6 @@
visibility: hidden;
transition: opacity 0.15s ease, visibility 0.15s ease;
z-index: 2;
will-change: opacity, visibility;
::ng-deep .p-button {
box-shadow:
@@ -155,7 +154,6 @@
visibility: hidden;
transition: opacity 0.15s ease, visibility 0.15s ease;
z-index: 2;
will-change: opacity, visibility;
@media (width <= 767px) {
top: 4px;
@@ -191,6 +189,20 @@
height: 2.5px;
z-index: 1;
opacity: 0.9;
background: rgb(0 0 0 / 30%);
overflow: hidden;
.progress-fill {
height: 100%;
transition: width 0.3s ease;
}
&.progress-incomplete .progress-fill { background: var(--primary-color); }
&.progress-complete .progress-fill { background: #22c55e; }
&.progress-incomplete-ko .progress-fill { background: #f97316; }
&.progress-complete-ko .progress-fill { background: #f59e0b; }
&.progress-incomplete-kobo .progress-fill { background: #a855f7; }
&.progress-complete-kobo .progress-fill { background: #8b5cf6; }
}
.series-number-overlay {
@@ -396,39 +408,3 @@
.status-unset {
color: var(--text-color-secondary);
}
::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 .progress-incomplete-kobo .p-progressbar-value {
background-color: #bf0000;
}
::ng-deep .progress-complete-kobo .p-progressbar-value {
background-color: #f65c9c;
}
::ng-deep .cover-progress-bar {
--p-progressbar-border-radius: 0 !important;
}
::ng-deep .custom-button-padding .p-button {
padding-block: 0.25rem !important;
}
::ng-deep .book-details-dialog .p-dialog-header {
padding: 1rem 1.25rem !important;
}
@@ -1,10 +1,9 @@
import {NO_ERRORS_SCHEMA, SimpleChange, SimpleChanges} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {ComponentRef, NO_ERRORS_SCHEMA, signal, WritableSignal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ActivatedRoute, Router} from '@angular/router';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TranslocoService} from '@jsverse/transloco';
import {ConfirmationService, MessageService} from 'primeng/api';
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
import {EmailService} from '../../../../settings/email-v2/email.service';
@@ -18,6 +17,7 @@ import {BookFileService} from '../../../service/book-file.service';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {BookNavigationService} from '../../../service/book-navigation.service';
import {BookService} from '../../../service/book.service';
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
function makeBook(overrides: Partial<Book> = {}): Book {
return {
@@ -92,6 +92,8 @@ function makeUser(metadataCenterViewMode: 'route' | 'dialog'): User {
describe('BookCardComponent', () => {
let component: BookCardComponent;
let fixture: ComponentFixture<BookCardComponent>;
let ref: ComponentRef<BookCardComponent>;
let bookService: {
readBook: ReturnType<typeof vi.fn>;
};
@@ -108,7 +110,8 @@ describe('BookCardComponent', () => {
refreshMetadataTask: ReturnType<typeof vi.fn>;
};
let userService: {
currentUser: ReturnType<typeof vi.fn>;
currentUser: WritableSignal<User | null>;
getCurrentUser: ReturnType<typeof vi.fn>;
};
let emailService: {
emailBookQuick: ReturnType<typeof vi.fn>;
@@ -122,6 +125,7 @@ describe('BookCardComponent', () => {
let urlHelper: {
getThumbnailUrl: ReturnType<typeof vi.fn>;
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
getBookPrimaryReadingUrl: ReturnType<typeof vi.fn>;
};
let confirmationService: {
confirm: ReturnType<typeof vi.fn>;
@@ -140,15 +144,9 @@ describe('BookCardComponent', () => {
let appSettingsService: {
appSettings: ReturnType<typeof vi.fn>;
};
let translocoService: {
translate: ReturnType<typeof vi.fn>;
};
let queryClient: {
fetchQuery: ReturnType<typeof vi.fn>;
};
let cdr: {
markForCheck: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
bookService = {
@@ -166,8 +164,10 @@ describe('BookCardComponent', () => {
taskHelperService = {
refreshMetadataTask: vi.fn(),
};
const currentUser = signal<User | null>(null);
userService = {
currentUser: vi.fn(() => null),
currentUser,
getCurrentUser: vi.fn(() => currentUser()),
};
emailService = {
emailBookQuick: vi.fn(),
@@ -181,6 +181,7 @@ describe('BookCardComponent', () => {
urlHelper = {
getThumbnailUrl: vi.fn((bookId: number, coverUpdatedOn?: string) => `thumb:${bookId}:${coverUpdatedOn ?? 'none'}`),
getAudiobookThumbnailUrl: vi.fn((bookId: number, audiobookCoverUpdatedOn?: string) => `audio-thumb:${bookId}:${audiobookCoverUpdatedOn ?? 'none'}`),
getBookPrimaryReadingUrl: vi.fn((book: Book) => `/read/${book.id}`),
};
confirmationService = {
confirm: vi.fn(),
@@ -199,20 +200,15 @@ describe('BookCardComponent', () => {
appSettingsService = {
appSettings: vi.fn(() => ({diskType: 'LOCAL'})),
};
translocoService = {
translate: vi.fn((key: string, params?: Record<string, unknown>) => (params ? `${key}:${JSON.stringify(params)}` : key)),
};
queryClient = {
fetchQuery: vi.fn(),
};
cdr = {
markForCheck: vi.fn(),
};
TestBed.configureTestingModule({
imports: [BookCardComponent],
imports: [BookCardComponent, getTranslocoModule()],
schemas: [NO_ERRORS_SCHEMA],
providers: [
{provide: ActivatedRoute, useValue: {}},
{provide: BookService, useValue: bookService},
{provide: BookFileService, useValue: bookFileService},
{provide: BookMetadataManageService, useValue: bookMetadataManageService},
@@ -226,16 +222,34 @@ describe('BookCardComponent', () => {
{provide: BookDialogHelperService, useValue: bookDialogHelperService},
{provide: BookNavigationService, useValue: bookNavigationService},
{provide: AppSettingsService, useValue: appSettingsService},
{provide: TranslocoService, useValue: translocoService},
{provide: QueryClient, useValue: queryClient},
{provide: QueryClient, useValue: queryClient},
{provide: BookCardComponent, useValue: BookCardComponent},
{provide: 'ChangeDetectorRef', useValue: cdr},
],
});
component = TestBed.createComponent(BookCardComponent).componentInstance;
(component as unknown as {cdr: typeof cdr}).cdr = cdr;
// Secondary mock for matchMedia to ensure it's available in CI environment
Object.defineProperty(window, 'matchMedia', {
writable: true,
configurable: true,
value: vi.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
fixture = TestBed.createComponent(BookCardComponent);
ref = fixture.componentRef;
component = fixture.componentInstance;
// Set required inputs before first change detection
ref.setInput('book', makeBook());
ref.setInput('index', 0);
fixture.detectChanges();
});
afterEach(() => {
@@ -243,8 +257,8 @@ describe('BookCardComponent', () => {
TestBed.resetTestingModule();
});
it('derives progress, audiobook, and series display state from inputs and changes', () => {
component.book = makeBook({
it('derives progress, audiobook, and series display state from inputs', () => {
ref.setInput('book', makeBook({
id: 8,
metadata: {
bookId: 8,
@@ -265,27 +279,24 @@ describe('BookCardComponent', () => {
koreaderProgress: {percentage: 11},
koboProgress: {percentage: 7},
readStatus: ReadStatus.READING,
});
component.seriesViewEnabled = true;
component.isSeriesCollapsed = true;
component.forceEbookMode = false;
}));
ref.setInput('seriesViewEnabled', true);
ref.setInput('isSeriesCollapsed', true);
ref.setInput('forceEbookMode', false);
fixture.detectChanges();
component.ngOnInit();
expect(component.hasProgress()).toBe(true);
expect(component.displayTitle()).toBe('Series Saga');
expect(component.titleTooltip()).toContain('Series Saga');
expect(component.coverImageUrl()).toBe('audio-thumb:8:2024-04-02');
expect(component.progressTooltip()).toBe('42% (Grimmory) | 11% (KOReader) | 7% (Kobo)');
expect(component.readButtonIcon()).toBe('pi pi-forward');
expect(component.hasProgress).toBe(true);
expect(component.displayTitle).toBe('Series Saga');
expect(component.titleTooltip).toContain('Series Saga');
expect(component.coverImageUrl).toBe('audio-thumb:8:2024-04-02');
expect(component.progressTooltip).toBe('42% (Grimmory) | 11% (KOReader) | 7% (Kobo)');
expect(component.readButtonIcon).toBe('pi pi-forward');
ref.setInput('isSeriesCollapsed', false);
fixture.detectChanges();
component.isSeriesCollapsed = false;
component.ngOnChanges({
isSeriesCollapsed: new SimpleChange(true, false, false),
} as SimpleChanges);
expect(component.displayTitle).toBe('Volume One');
expect(component.titleTooltip).toContain('Volume One');
expect(component.displayTitle()).toBe('Volume One');
expect(component.titleTooltip()).toContain('Volume One');
});
it('uses forced ebook mode for audiobook reads and falls back to the normal read flow otherwise', () => {
@@ -310,23 +321,26 @@ describe('BookCardComponent', () => {
],
});
component.forceEbookMode = true;
ref.setInput('forceEbookMode', true);
fixture.detectChanges();
component.readBook(audiobookWithAlternativeFormat);
expect(bookService.readBook).toHaveBeenCalledWith(12, undefined, 'PDF');
component.forceEbookMode = false;
ref.setInput('forceEbookMode', false);
fixture.detectChanges();
component.readBook(makeBook({id: 13}));
expect(bookService.readBook).toHaveBeenCalledWith(13);
});
it('derives display format from missing primary files, extensions, paths, and forced audiobook ebook types', () => {
component.book = makeBook({id: 20, primaryFile: undefined});
component.forceEbookMode = false;
expect(component.getDisplayFormat()).toBe('PHY');
ref.setInput('book', makeBook({id: 20, primaryFile: undefined}));
ref.setInput('forceEbookMode', false);
fixture.detectChanges();
expect(component.displayFormat()).toBe('PHY');
component.book = makeBook({
ref.setInput('book', makeBook({
id: 21,
primaryFile: {
id: 211,
@@ -335,10 +349,11 @@ describe('BookCardComponent', () => {
extension: 'pdf',
filePath: 'books/volume-one.pdf',
},
});
expect(component.getDisplayFormat()).toBe('PDF');
}));
fixture.detectChanges();
expect(component.displayFormat()).toBe('PDF');
component.book = makeBook({
ref.setInput('book', makeBook({
id: 22,
primaryFile: {
id: 221,
@@ -346,10 +361,11 @@ describe('BookCardComponent', () => {
bookType: 'EPUB',
filePath: 'books/volume-one.mobi',
},
});
expect(component.getDisplayFormat()).toBe('MOBI');
}));
fixture.detectChanges();
expect(component.displayFormat()).toBe('MOBI');
component.book = makeBook({
ref.setInput('book', makeBook({
id: 23,
primaryFile: {
id: 231,
@@ -358,40 +374,45 @@ describe('BookCardComponent', () => {
filePath: 'books/volume-one.m4b',
},
epubProgress: {cfi: 'epub', percentage: 73},
});
component.forceEbookMode = true;
expect(component.getDisplayFormat()).toBe('EPUB');
}));
ref.setInput('forceEbookMode', true);
fixture.detectChanges();
expect(component.displayFormat()).toBe('EPUB');
});
it('guards card selection and preserves shift metadata for ctrl-initiated changes only', () => {
component.book = makeBook({id: 30});
component.index = 4;
component.isCheckboxEnabled = false;
component.isSelected = false;
component.onBookSelect = vi.fn();
it('guards card selection and emits checkbox events for ctrl-initiated changes only', () => {
ref.setInput('book', makeBook({id: 30}));
ref.setInput('index', 4);
ref.setInput('isCheckboxEnabled', false);
ref.setInput('isSelected', false);
const selectFn = vi.fn();
ref.setInput('onBookSelect', selectFn);
fixture.detectChanges();
const emitSpy = vi.spyOn(component.checkboxClick, 'emit');
const emitted: unknown[] = [];
component.checkboxClick.subscribe(e => emitted.push(e));
component.toggleCardSelection(true);
expect(emitSpy).not.toHaveBeenCalled();
expect(component.onBookSelect).not.toHaveBeenCalled();
expect(emitted).toHaveLength(0);
expect(selectFn).not.toHaveBeenCalled();
component.isCheckboxEnabled = true;
ref.setInput('isCheckboxEnabled', true);
fixture.detectChanges();
component.captureMouseEvent(new MouseEvent('mousedown', {shiftKey: true}));
component.onCardClick(new MouseEvent('click', {ctrlKey: false}));
expect(emitSpy).not.toHaveBeenCalled();
expect(emitted).toHaveLength(0);
component.onCardClick(new MouseEvent('click', {ctrlKey: true}));
expect(component.isSelected).toBe(true);
expect(emitSpy).toHaveBeenCalledWith({
expect(emitted).toHaveLength(1);
expect(emitted[0]).toEqual({
index: 4,
book: component.book,
book: component.book(),
selected: true,
shiftKey: true,
});
expect(component.onBookSelect).toHaveBeenCalledWith(component.book, true);
expect(selectFn).toHaveBeenCalledWith(component.book(), true);
});
it('routes series info and book details through the correct destination', () => {
@@ -406,16 +427,17 @@ describe('BookCardComponent', () => {
},
});
userService.currentUser.mockReturnValue(makeUser('route'));
component.book = book;
component.isSeriesCollapsed = true;
component.ngOnInit();
userService.currentUser.set(makeUser('route'));
ref.setInput('book', book);
ref.setInput('isSeriesCollapsed', true);
fixture.detectChanges();
component.openSeriesInfo();
expect(router.navigate).toHaveBeenCalledWith(['/series', 'The Series']);
bookNavigationService.availableBookIds.mockReturnValue([2, 44, 77]);
component.isSeriesCollapsed = false;
ref.setInput('isSeriesCollapsed', false);
fixture.detectChanges();
component.openSeriesInfo();
expect(bookNavigationService.setNavigationContext).toHaveBeenCalledWith([2, 44, 77], 44);
@@ -423,9 +445,7 @@ describe('BookCardComponent', () => {
queryParams: {tab: 'view'},
});
userService.currentUser.mockReturnValue(makeUser('dialog'));
const dialogComponent = component as unknown as {metadataCenterViewMode: 'route' | 'dialog'};
dialogComponent.metadataCenterViewMode = 'dialog';
userService.currentUser.set(makeUser('dialog'));
router.navigate.mockClear();
bookNavigationService.setNavigationContext.mockClear();
@@ -1,24 +1,20 @@
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
import {TooltipModule} from "primeng/tooltip";
import {ChangeDetectionStrategy, Component, computed, inject, input, output, signal} from '@angular/core';
import {Tooltip} from 'primeng/tooltip';
import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model';
import {Button} from 'primeng/button';
import {MenuModule} from 'primeng/menu';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
import {BookService} from '../../../service/book.service';
import {BookFileService} from '../../../service/book-file.service';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {CheckboxChangeEvent, CheckboxModule} from 'primeng/checkbox';
import {CheckboxChangeEvent, Checkbox} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {NgClass} from '@angular/common';
import {User, UserService} from '../../../../settings/user-management/user.service';
import {UserService} from '../../../../settings/user-management/user.service';
import {EmailService} from '../../../../settings/email-v2/email.service';
import {TieredMenu} from 'primeng/tieredmenu';
import {Router} from '@angular/router';
import {RouterLink} from '@angular/router';
import {ProgressBar} from 'primeng/progressbar';
import {Router, RouterLink} from '@angular/router';
import {readStatusLabels} from '../book-filter/book-filter.config';
import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
@@ -34,32 +30,37 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
selector: 'app-book-card',
templateUrl: './book-card.component.html',
styleUrls: ['./book-card.component.scss'],
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgClass, TieredMenu, ProgressBar, TooltipModule, RouterLink, TranslocoPipe, CoverPlaceholderComponent],
imports: [Checkbox, FormsModule, NgClass, TieredMenu, Tooltip, RouterLink, TranslocoPipe, CoverPlaceholderComponent],
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
export class BookCardComponent {
@Output() checkboxClick = new EventEmitter<{ index: number; book: Book; selected: boolean; shiftKey: boolean }>();
@Output() menuToggled = new EventEmitter<boolean>();
// --- Inputs ---
readonly book = input.required<Book>();
readonly index = input.required<number>();
readonly isCheckboxEnabled = input(false);
readonly onBookSelect = input<((book: Book, selected: boolean) => void) | undefined>();
readonly isSelected = input(false);
readonly bottomBarHidden = input(false);
readonly seriesViewEnabled = input(false);
readonly isSeriesCollapsed = input(false);
readonly overlayPreferenceService = input<BookCardOverlayPreferenceService | undefined>();
private readonly overlayService = inject(BookCardOverlayPreferenceService);
readonly showBookTypePill = computed(() => (this.overlayPreferenceService() ?? this.overlayService).showBookTypePill());
readonly forceEbookMode = input(false);
readonly useSquareCovers = input(false);
@Input() index!: number;
@Input() book!: Book;
@Input() isCheckboxEnabled: boolean = false;
@Input() onBookSelect?: (book: Book, selected: boolean) => void;
@Input() isSelected: boolean = false;
@Input() bottomBarHidden: boolean = false;
@Input() seriesViewEnabled: boolean = false;
@Input() isSeriesCollapsed: boolean = false;
@Input() overlayPreferenceService?: BookCardOverlayPreferenceService;
@Input() forceEbookMode: boolean = false;
@Input() useSquareCovers: boolean = false;
readonly checkboxClick = output<{ index: number; book: Book; selected: boolean; shiftKey: boolean }>();
readonly menuToggled = output<boolean>();
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
items: MenuItem[] | undefined;
readStatusMenuItems: MenuItem[] = [];
isSubMenuLoading = false;
private additionalFilesLoaded = false;
readonly items = signal<MenuItem[] | undefined>(undefined);
readonly readStatusMenuItems = signal<MenuItem[]>([]);
readonly isSubMenuLoading = signal(false);
private readonly additionalFilesLoaded = signal(false);
/** Tracks the book id for which the menu was last built, to auto-rebuild on virtual-scroller reuse. */
private menuBookId: number | undefined;
private menuInitialized = false;
private bookService = inject(BookService);
private bookFileService = inject(BookFileService);
@@ -69,165 +70,113 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
private emailService = inject(EmailService);
private messageService = inject(MessageService);
private router = inject(Router);
protected urlHelper = inject(UrlHelperService);
private urlHelper = inject(UrlHelperService);
private confirmationService = inject(ConfirmationService);
private bookDialogHelperService = inject(BookDialogHelperService);
private bookNavigationService = inject(BookNavigationService);
private cdr = inject(ChangeDetectorRef);
private appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
private queryClient = inject(QueryClient);
protected _progressPercentage: number | null = null;
protected _koProgressPercentage: number | null = null;
protected _koboProgressPercentage: number | null = null;
protected _displayTitle: string | undefined = undefined;
protected _isSeriesViewActive: boolean = false;
protected _coverImageUrl: string | null = null;
protected _readStatusIcon: string = '';
protected _readStatusClass: string = '';
protected _readStatusTooltip: string = '';
protected _shouldShowStatusIcon: boolean = false;
protected _seriesCountTooltip: string = '';
protected _titleTooltip: string = '';
protected _hasProgress: boolean = false;
protected _isAudiobook: boolean = false;
protected _progressTooltip: string = '';
protected _isContinueReading: boolean = false;
protected _readButtonIcon: string = 'pi pi-book';
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
protected readStatusHelper = inject(ReadStatusHelper);
private user: User | null = null;
private diskType: string = 'LOCAL';
private menuInitialized = false;
ngOnInit(): void {
this.computeAllMemoizedValues();
const currentUser = this.userService.currentUser();
if (currentUser) {
this.user = currentUser;
this.metadataCenterViewMode = currentUser.userSettings?.metadataCenterViewMode ?? 'route';
}
private readonly currentUser = computed(() => this.userService.currentUser());
private readonly metadataCenterViewMode = computed(() => this.currentUser()?.userSettings?.metadataCenterViewMode ?? 'route' as 'route' | 'dialog');
private readonly diskType = computed(() => this.appSettingsService.appSettings()?.diskType ?? 'LOCAL');
const settings = this.appSettingsService.appSettings();
if (settings) {
this.diskType = settings.diskType ?? 'LOCAL';
}
}
ngOnDestroy(): void {
this._coverImageUrl = null;
}
readonly progressPercentage = computed(() => {
const b = this.book();
return b.epubProgress?.percentage ?? b.pdfProgress?.percentage ?? b.cbxProgress?.percentage ?? null;
});
ngOnChanges(changes: SimpleChanges): void {
if (changes['book'] || changes['forceEbookMode'] || changes['useSquareCovers']) {
this.computeAllMemoizedValues();
if (changes['book'] && !changes['book'].firstChange && this.menuInitialized) {
this.additionalFilesLoaded = false;
this.initMenu();
}
}
readonly koProgressPercentage = computed(() => this.book().koreaderProgress?.percentage ?? null);
readonly koboProgressPercentage = computed(() => this.book().koboProgress?.percentage ?? null);
if (changes['seriesViewEnabled'] || changes['isSeriesCollapsed']) {
this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1;
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title;
this._titleTooltip = this.t.translate('book.card.alt.titleTooltip', { title: this._displayTitle });
}
}
readonly hasProgress = computed(() =>
this.progressPercentage() !== null || this.koProgressPercentage() !== null || this.koboProgressPercentage() !== null
);
private computeAllMemoizedValues(): void {
this._progressPercentage = this.book.epubProgress?.percentage
?? this.book.pdfProgress?.percentage
?? this.book.cbxProgress?.percentage
?? null;
readonly isSeriesViewActive = computed(() =>
this.seriesViewEnabled() && !!this.book().seriesCount && this.book().seriesCount! >= 1
);
this._koProgressPercentage = this.book.koreaderProgress?.percentage ?? null;
this._koboProgressPercentage = this.book.koboProgress?.percentage ?? null;
readonly displayTitle = computed(() =>
(this.isSeriesCollapsed() && this.book().metadata?.seriesName)
? this.book().metadata?.seriesName
: this.book().metadata?.title
);
this._hasProgress = this._progressPercentage !== null || this._koProgressPercentage !== null || this._koboProgressPercentage !== null;
readonly isAudiobook = computed(() =>
this.book().primaryFile?.bookType === 'AUDIOBOOK' && !this.forceEbookMode()
);
this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1;
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName)
? this.book.metadata?.seriesName
: this.book.metadata?.title;
this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK' && !this.forceEbookMode;
this._coverImageUrl = this._isAudiobook
? this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
readonly coverImageUrl = computed(() =>
this.isAudiobook()
? this.urlHelper.getAudiobookThumbnailUrl(this.book().id, this.book().metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getThumbnailUrl(this.book().id, this.book().metadata?.coverUpdatedOn)
);
this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus);
this._readStatusClass = this.readStatusHelper.getReadStatusClass(this.book.readStatus);
this._readStatusTooltip = this.readStatusHelper.getReadStatusTooltip(this.book.readStatus);
this._shouldShowStatusIcon = this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus);
readonly readStatusIcon = computed(() => this.readStatusHelper.getReadStatusIcon(this.book().readStatus));
readonly readStatusClass = computed(() => this.readStatusHelper.getReadStatusClass(this.book().readStatus));
readonly readStatusTooltip = computed(() => this.readStatusHelper.getReadStatusTooltip(this.book().readStatus));
this._seriesCountTooltip = this.t.translate('book.card.alt.seriesCollapsed', { count: this.book.seriesCount });
this._titleTooltip = this.t.translate('book.card.alt.titleTooltip', { title: this._displayTitle });
readonly seriesCountTooltip = computed(() =>
this.t.translate('book.card.alt.seriesCollapsed', {count: this.book().seriesCount})
);
const progressParts: string[] = [];
if (this._progressPercentage !== null) {
progressParts.push(`${this._progressPercentage}% (Grimmory)`);
}
if (this._koProgressPercentage !== null) {
progressParts.push(`${this._koProgressPercentage}% (KOReader)`);
}
if (this._koboProgressPercentage !== null) {
progressParts.push(`${this._koboProgressPercentage}% (Kobo)`);
}
this._progressTooltip = progressParts.join(' | ');
readonly titleTooltip = computed(() =>
this.t.translate('book.card.alt.titleTooltip', {title: this.displayTitle()})
);
const maxProgress = Math.max(
this._progressPercentage ?? 0,
this._koProgressPercentage ?? 0,
this._koboProgressPercentage ?? 0
readonly progressTooltip = computed(() => {
const parts: string[] = [];
const p = this.progressPercentage();
const ko = this.koProgressPercentage();
const kobo = this.koboProgressPercentage();
if (p !== null) parts.push(`${p}% (Grimmory)`);
if (ko !== null) parts.push(`${ko}% (KOReader)`);
if (kobo !== null) parts.push(`${kobo}% (Kobo)`);
return parts.join(' | ');
});
readonly isContinueReading = computed(() => {
const max = Math.max(
this.progressPercentage() ?? 0,
this.koProgressPercentage() ?? 0,
this.koboProgressPercentage() ?? 0
);
this._isContinueReading = maxProgress > 0 && maxProgress < 100;
return max > 0 && max < 100;
});
if (this._isAudiobook) {
this._readButtonIcon = this._isContinueReading ? 'pi pi-forward' : 'pi pi-play';
} else {
this._readButtonIcon = this._isContinueReading ? 'pi pi-forward' : 'pi pi-book';
readonly readButtonIcon = computed(() => {
if (this.isAudiobook()) {
return this.isContinueReading() ? 'pi pi-forward' : 'pi pi-play';
}
}
return this.isContinueReading() ? 'pi pi-forward' : 'pi pi-book';
});
get hasProgress(): boolean {
return this._hasProgress;
}
readonly displayFormat = computed<string | null>(() => {
const b = this.book();
if (!b.primaryFile) return 'PHY';
if (this.forceEbookMode() && b.primaryFile.bookType === 'AUDIOBOOK') {
const ebookType = this.getEbookType(b);
if (ebookType) return ebookType;
}
const ext = b.primaryFile.extension;
if (ext) return ext.toUpperCase();
return this.getFileExtension(b.primaryFile.filePath);
});
get seriesCountTooltip(): string {
return this._seriesCountTooltip;
}
readonly hasDigitalFile = computed(() => !!this.book().primaryFile);
get titleTooltip(): string {
return this._titleTooltip;
}
get readStatusTooltip(): string {
return this._readStatusTooltip;
}
get progressTooltip(): string {
return this._progressTooltip;
}
get readButtonIcon(): string {
return this._readButtonIcon;
}
get displayTitle(): string | undefined {
return this._displayTitle;
}
get coverImageUrl(): string | null {
return this._coverImageUrl;
}
readonly readingUrl = computed(() => this.urlHelper.getBookPrimaryReadingUrl(this.book()));
private buildReadStatusMenuItems(): void {
this.readStatusMenuItems = Object.entries(readStatusLabels).map(([status, label]) => ({
this.readStatusMenuItems.set(Object.entries(readStatusLabels).map(([status, label]) => ({
label,
command: () => {
this.bookService.updateBookReadStatus(this.book.id, status as ReadStatus).subscribe({
this.bookService.updateBookReadStatus(this.book().id, status as ReadStatus).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
@@ -246,20 +195,19 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
}
});
}
}));
})));
}
toggleReadStatusMenu(event: Event, menu: TieredMenu): void {
event.stopPropagation();
if (this.readStatusMenuItems.length === 0) {
if (this.readStatusMenuItems().length === 0) {
this.buildReadStatusMenuItems();
}
menu.toggle(event);
}
readBook(book: Book): void {
if (this.forceEbookMode && book.primaryFile?.bookType === 'AUDIOBOOK') {
if (this.forceEbookMode() && book.primaryFile?.bookType === 'AUDIOBOOK') {
const ebookType = this.getEbookType(book);
if (ebookType) {
this.bookService.readBook(book.id, undefined, ebookType);
@@ -288,52 +236,47 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
}
onMenuToggle(event: Event, menu: TieredMenu): void {
if (!this.menuInitialized) {
const currentBookId = this.book().id;
if (!this.menuInitialized || this.menuBookId !== currentBookId) {
this.menuInitialized = true;
this.menuBookId = currentBookId;
this.additionalFilesLoaded.set(false);
this.initMenu();
this.cdr.markForCheck();
}
menu.toggle(event);
if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) {
this.isSubMenuLoading = true;
this.cdr.markForCheck();
const requestedBookId = this.book.id;
if (!this.additionalFilesLoaded() && !this.isSubMenuLoading() && this.needsAdditionalFilesData()) {
this.isSubMenuLoading.set(true);
const requestedBookId = currentBookId;
void this.queryClient.fetchQuery(this.bookService.bookDetailQueryOptions(requestedBookId, true))
.then((book) => {
if (this.book.id !== requestedBookId) {
return;
}
this.book = book;
this.additionalFilesLoaded = true;
this.isSubMenuLoading = false;
this.initMenu();
this.cdr.markForCheck();
.then((fetchedBook) => {
if (this.book().id !== requestedBookId) return;
this.additionalFilesLoaded.set(true);
this.initMenu(fetchedBook);
})
.catch(() => {
if (this.book.id !== requestedBookId) {
return;
.finally(() => {
if (this.book().id === requestedBookId) {
this.isSubMenuLoading.set(false);
}
this.isSubMenuLoading = false;
this.cdr.markForCheck();
});
}
}
private needsAdditionalFilesData(): boolean {
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;
const canDownload = !!this.user?.permissions.canDownload;
const canDeleteBook = !!this.user?.permissions.canDeleteBook;
if (this.additionalFilesLoaded()) return false;
const b = this.book();
const hasNoAlternativeFormats = !b.alternativeFormats || b.alternativeFormats.length === 0;
const hasNoSupplementaryFiles = !b.supplementaryFiles || b.supplementaryFiles.length === 0;
const canDownload = !!this.currentUser()?.permissions.canDownload;
const canDeleteBook = !!this.currentUser()?.permissions.canDeleteBook;
return (canDownload || canDeleteBook) && hasNoAlternativeFormats && hasNoSupplementaryFiles;
}
private initMenu() {
this.items = [
private initMenu(bookOverride?: Book) {
const b = bookOverride ?? this.book();
this.items.set([
{
label: this.t.translate('book.card.menu.assignShelf'),
icon: 'pi pi-folder',
@@ -344,64 +287,60 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
icon: 'pi pi-info-circle',
command: () => {
setTimeout(() => {
this.openBookInfo(this.book);
this.openBookInfo(this.book());
}, 150);
},
},
...this.getPermissionBasedMenuItems(),
...this.getPermissionBasedMenuItems(b),
...this.moreMenuItems(),
];
]);
}
private getPermissionBasedMenuItems(): MenuItem[] {
private getPermissionBasedMenuItems(b: Book): MenuItem[] {
const items: MenuItem[] = [];
if (this.user?.permissions.canDownload) {
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
if (this.currentUser()?.permissions.canDownload) {
const hasAdditional = (b.alternativeFormats && b.alternativeFormats.length > 0) ||
(b.supplementaryFiles && b.supplementaryFiles.length > 0);
if (hasAdditionalFiles) {
const downloadItems = this.getDownloadMenuItems();
if (hasAdditional) {
items.push({
label: this.t.translate('book.card.menu.download'),
icon: 'pi pi-download',
items: downloadItems
items: this.getDownloadMenuItems(b)
});
} else if (this.additionalFilesLoaded) {
} else if (this.additionalFilesLoaded()) {
items.push({
label: this.t.translate('book.card.menu.download'),
icon: 'pi pi-download',
command: () => {
this.bookFileService.downloadFile(this.book);
}
command: () => this.bookFileService.downloadFile(this.book())
});
} else {
items.push({
label: this.t.translate('book.card.menu.download'),
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-download',
icon: this.isSubMenuLoading() ? 'pi pi-spin pi-spinner' : 'pi pi-download',
items: [{label: this.t.translate('book.card.menu.loading'), disabled: true}]
});
}
}
if (this.user?.permissions.canDeleteBook) {
const hasAdditionalFiles = (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) ||
(this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0);
if (this.currentUser()?.permissions.canDeleteBook) {
const hasAdditional = (b.alternativeFormats && b.alternativeFormats.length > 0) ||
(b.supplementaryFiles && b.supplementaryFiles.length > 0);
if (hasAdditionalFiles) {
const deleteItems = this.getDeleteMenuItems();
if (hasAdditional) {
items.push({
label: this.t.translate('book.card.menu.delete'),
icon: 'pi pi-trash',
items: deleteItems
items: this.getDeleteMenuItems(b)
});
} else if (this.additionalFilesLoaded) {
} else if (this.additionalFilesLoaded()) {
items.push({
label: this.t.translate('book.card.menu.delete'),
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book.metadata?.title}),
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book().metadata?.title}),
header: this.t.translate('book.card.confirm.deleteBookHeader'),
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
@@ -411,7 +350,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
acceptButtonStyleClass: 'p-button-danger',
rejectButtonStyleClass: 'p-button-outlined',
accept: () => {
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
this.bookService.deleteBooks(new Set([this.book().id])).subscribe();
}
});
}
@@ -419,69 +358,67 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
} else {
items.push({
label: this.t.translate('book.card.menu.delete'),
icon: this.isSubMenuLoading ? 'pi pi-spin pi-spinner' : 'pi pi-trash',
icon: this.isSubMenuLoading() ? 'pi pi-spin pi-spinner' : 'pi pi-trash',
items: [{label: this.t.translate('book.card.menu.loading'), disabled: true}]
});
}
}
if (this.user?.permissions.canEmailBook) {
items.push(
{
label: this.t.translate('book.card.menu.emailBook'),
if (this.currentUser()?.permissions.canEmailBook) {
items.push({
label: this.t.translate('book.card.menu.emailBook'),
icon: 'pi pi-envelope',
items: [{
label: this.t.translate('book.card.menu.quickSend'),
icon: 'pi pi-envelope',
items: [{
label: this.t.translate('book.card.menu.quickSend'),
icon: 'pi pi-envelope',
command: () => {
const doSend = () => {
this.emailService.emailBookQuick(this.book.id).subscribe({
next: () => {
this.messageService.add({
severity: 'info',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.quickSendSuccessDetail'),
});
},
error: (err) => {
const errorMessage = err?.error?.message || this.t.translate('book.card.toast.quickSendErrorDetail');
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: errorMessage,
});
},
});
};
command: () => {
const doSend = () => {
this.emailService.emailBookQuick(this.book().id).subscribe({
next: () => {
this.messageService.add({
severity: 'info',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.quickSendSuccessDetail'),
});
},
error: (err: {error?: {message?: string}}) => {
const errorMessage = err?.error?.message || this.t.translate('book.card.toast.quickSendErrorDetail');
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: errorMessage,
});
},
});
};
if (this.book.primaryFile?.fileSizeKb && this.book.primaryFile.fileSizeKb > 25 * 1024) {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.largeFileMessage'),
header: this.t.translate('book.card.confirm.largeFileHeader'),
icon: 'pi pi-exclamation-triangle',
acceptLabel: this.t.translate('book.card.confirm.sendAnyway'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: { severity: 'warn' },
rejectButtonProps: { severity: 'secondary' },
accept: doSend,
});
} else {
doSend();
}
const currentBook = this.book();
if (currentBook.primaryFile?.fileSizeKb && currentBook.primaryFile.fileSizeKb > 25 * 1024) {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.largeFileMessage'),
header: this.t.translate('book.card.confirm.largeFileHeader'),
icon: 'pi pi-exclamation-triangle',
acceptLabel: this.t.translate('book.card.confirm.sendAnyway'),
rejectLabel: this.t.translate('common.cancel'),
acceptButtonProps: {severity: 'warn'},
rejectButtonProps: {severity: 'secondary'},
accept: doSend,
});
} else {
doSend();
}
},
{
label: this.t.translate('book.card.menu.customSend'),
icon: 'pi pi-envelope',
command: () => {
this.bookDialogHelperService.openCustomSendDialog(this.book);
}
}
]
});
}
},
{
label: this.t.translate('book.card.menu.customSend'),
icon: 'pi pi-envelope',
command: () => this.bookDialogHelperService.openCustomSendDialog(this.book())
}
]
});
}
if (this.user?.permissions.canEditMetadata) {
if (this.currentUser()?.permissions.canEditMetadata) {
items.push({
label: this.t.translate('book.card.menu.metadata'),
icon: 'pi pi-database',
@@ -491,9 +428,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
icon: 'pi pi-sparkles',
command: () => {
setTimeout(() => {
this.router.navigate(['/book', this.book.id], {
queryParams: {tab: 'match'}
})
this.router.navigate(['/book', this.book().id], {queryParams: {tab: 'match'}});
}, 150);
},
},
@@ -503,28 +438,26 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
command: () => {
this.taskHelperService.refreshMetadataTask({
refreshType: MetadataRefreshType.BOOKS,
bookIds: [this.book.id],
bookIds: [this.book().id],
}).subscribe();
}
},
{
label: this.t.translate('book.card.menu.customFetch'),
icon: 'pi pi-sync',
command: () => {
this.bookDialogHelperService.openMetadataRefreshDialog(new Set([this.book!.id]))
},
command: () => this.bookDialogHelperService.openMetadataRefreshDialog(new Set([this.book().id])),
},
{
label: this.t.translate('book.card.menu.regenerateCover'),
icon: 'pi pi-image',
command: () => {
this.bookMetadataManageService.regenerateCover(this.book.id).subscribe({
this.bookMetadataManageService.regenerateCover(this.book().id).subscribe({
next: () => this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.coverRegenSuccessDetail')
}),
error: (err) => this.messageService.add({
error: (err: {error?: {message?: string}}) => this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: err?.error?.message || this.t.translate('book.card.toast.coverRegenFailedDetail')
@@ -536,13 +469,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
label: this.t.translate('book.card.menu.generateCustomCover'),
icon: 'pi pi-palette',
command: () => {
this.bookMetadataManageService.generateCustomCover(this.book.id).subscribe({
this.bookMetadataManageService.generateCustomCover(this.book().id).subscribe({
next: () => this.messageService.add({
severity: 'success',
summary: this.t.translate('common.success'),
detail: this.t.translate('book.card.toast.customCoverSuccessDetail')
}),
error: (err) => this.messageService.add({
error: (err: {error?: {message?: string}}) => this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: err?.error?.message || this.t.translate('book.card.toast.customCoverFailedDetail')
@@ -561,13 +494,11 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
const items: MenuItem[] = [];
const moreActions: MenuItem[] = [];
if (this.user?.permissions.canMoveOrganizeFiles && this.diskType === 'LOCAL') {
if (this.currentUser()?.permissions.canMoveOrganizeFiles && this.diskType() === 'LOCAL') {
moreActions.push({
label: this.t.translate('book.card.menu.organizeFile'),
icon: 'pi pi-arrows-h',
command: () => {
this.bookDialogHelperService.openFileMoverDialog(new Set([this.book.id]));
}
command: () => this.bookDialogHelperService.openFileMoverDialog(new Set([this.book().id]))
});
}
@@ -578,7 +509,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
items: Object.entries(readStatusLabels).map(([status, label]) => ({
label,
command: () => {
this.bookService.updateBookReadStatus(this.book.id, status as ReadStatus).subscribe({
this.bookService.updateBookReadStatus(this.book().id, status as ReadStatus).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
@@ -603,7 +534,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
label: this.t.translate('book.card.menu.resetGrimmoryProgress'),
icon: 'pi pi-undo',
command: () => {
this.bookService.resetProgress(this.book.id, ResetProgressTypes.GRIMMORY).subscribe({
this.bookService.resetProgress(this.book().id, ResetProgressTypes.GRIMMORY).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
@@ -627,7 +558,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
label: this.t.translate('book.card.menu.resetKOReaderProgress'),
icon: 'pi pi-undo',
command: () => {
this.bookService.resetProgress(this.book.id, ResetProgressTypes.KOREADER).subscribe({
this.bookService.resetProgress(this.book().id, ResetProgressTypes.KOREADER).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
@@ -659,15 +590,16 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
}
private openShelfDialog(): void {
this.bookDialogHelperService.openShelfAssignerDialog(this.book, null);
this.bookDialogHelperService.openShelfAssignerDialog(this.book(), null);
}
openSeriesInfo(): void {
const seriesName = this.book?.metadata?.seriesName;
if (this.isSeriesCollapsed && seriesName) {
const b = this.book();
const seriesName = b.metadata?.seriesName;
if (this.isSeriesCollapsed() && seriesName) {
this.router.navigate(['/series', seriesName]);
} else {
this.openBookInfo(this.book);
this.openBookInfo(b);
}
}
@@ -677,7 +609,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this.bookNavigationService.setNavigationContext(allBookIds, book.id);
}
if (this.metadataCenterViewMode === 'route') {
if (this.metadataCenterViewMode() === 'route') {
this.router.navigate(['/book', book.id], {
queryParams: {tab: 'view'}
});
@@ -686,52 +618,50 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
}
}
private getDownloadMenuItems(): MenuItem[] {
private getDownloadMenuItems(b: Book): MenuItem[] {
const items: MenuItem[] = [];
items.push({
label: `${this.book.fileName || 'Book File'}`,
label: `${b.fileName || 'Book File'}`,
icon: 'pi pi-file',
command: () => {
this.bookFileService.downloadFile(this.book);
}
command: () => this.bookFileService.downloadFile(this.book())
});
if (this.hasAdditionalFiles()) {
if (this.hasAdditionalFilesForBook(b)) {
items.push({separator: true});
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
this.book.alternativeFormats.forEach(format => {
if (b.alternativeFormats && b.alternativeFormats.length > 0) {
for (const format of b.alternativeFormats) {
const extension = this.getFileExtension(format.filePath);
items.push({
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
icon: this.getFileIcon(extension),
command: () => this.downloadAdditionalFile(this.book, format.id)
command: () => this.downloadAdditionalFile(this.book(), format.id)
});
});
}
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
if (b.alternativeFormats && b.alternativeFormats.length > 0 &&
b.supplementaryFiles && b.supplementaryFiles.length > 0) {
items.push({separator: true});
}
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
this.book.supplementaryFiles.forEach(file => {
if (b.supplementaryFiles && b.supplementaryFiles.length > 0) {
for (const file of b.supplementaryFiles) {
const extension = this.getFileExtension(file.filePath);
items.push({
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
icon: this.getFileIcon(extension),
command: () => this.downloadAdditionalFile(this.book, file.id)
command: () => this.downloadAdditionalFile(this.book(), file.id)
});
});
}
}
return items;
}
private getDeleteMenuItems(): MenuItem[] {
private getDeleteMenuItems(b: Book): MenuItem[] {
const items: MenuItem[] = [];
items.push({
@@ -739,7 +669,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
icon: 'pi pi-book',
command: () => {
this.confirmationService.confirm({
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book.metadata?.title}),
message: this.t.translate('book.card.confirm.deleteBookMessage', {title: this.book().metadata?.title}),
header: this.t.translate('book.card.confirm.deleteBookHeader'),
icon: 'pi pi-exclamation-triangle',
acceptIcon: 'pi pi-trash',
@@ -749,49 +679,49 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
acceptButtonStyleClass: 'p-button-danger',
rejectButtonStyleClass: 'p-button-outlined',
accept: () => {
this.bookService.deleteBooks(new Set([this.book.id])).subscribe();
this.bookService.deleteBooks(new Set([this.book().id])).subscribe();
}
});
}
});
if (this.hasAdditionalFiles()) {
if (this.hasAdditionalFilesForBook(b)) {
items.push({separator: true});
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0) {
this.book.alternativeFormats.forEach(format => {
if (b.alternativeFormats && b.alternativeFormats.length > 0) {
for (const format of b.alternativeFormats) {
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')
command: () => this.deleteAdditionalFile(this.book().id, format.id, format.fileName || 'file')
});
});
}
}
if (this.book.alternativeFormats && this.book.alternativeFormats.length > 0 &&
this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
if (b.alternativeFormats && b.alternativeFormats.length > 0 &&
b.supplementaryFiles && b.supplementaryFiles.length > 0) {
items.push({separator: true});
}
if (this.book.supplementaryFiles && this.book.supplementaryFiles.length > 0) {
this.book.supplementaryFiles.forEach(file => {
if (b.supplementaryFiles && b.supplementaryFiles.length > 0) {
for (const file of b.supplementaryFiles) {
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')
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 hasAdditionalFilesForBook(b: Book): boolean {
return !!(b.alternativeFormats && b.alternativeFormats.length > 0) ||
!!(b.supplementaryFiles && b.supplementaryFiles.length > 0);
}
private downloadAdditionalFile(book: Book, fileId: number): void {
@@ -815,7 +745,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
detail: this.t.translate('book.card.toast.deleteFileSuccessDetail', {fileName})
});
},
error: (error) => {
error: (error: {message?: string}) => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -827,34 +757,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
});
}
getFileExtension(filePath?: string): string | null {
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;
}
getDisplayFormat(): string | null {
if (!this.book?.primaryFile) {
return 'PHY';
}
if (this.forceEbookMode && this.book.primaryFile?.bookType === 'AUDIOBOOK') {
const ebookType = this.getEbookType(this.book);
if (ebookType) {
return ebookType;
}
}
const ext = this.book?.primaryFile?.extension;
if (ext) {
return ext.toUpperCase();
}
return this.getFileExtension(this.book?.primaryFile?.filePath);
}
hasDigitalFile(): boolean {
return !!this.book?.primaryFile;
}
private getFileIcon(fileType: string | null): string {
if (!fileType) return 'pi pi-file';
switch (fileType.toLowerCase()) {
@@ -896,26 +805,26 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
return;
}
this.toggleCardSelection(!this.isSelected)
this.toggleCardSelection(!this.isSelected());
}
toggleCardSelection(selected: boolean): void {
if (!this.isCheckboxEnabled) {
if (!this.isCheckboxEnabled()) {
return;
}
this.isSelected = selected;
const shiftKey = this.lastMouseEvent?.shiftKey ?? false;
this.checkboxClick.emit({
index: this.index,
book: this.book,
selected: selected,
shiftKey: shiftKey,
index: this.index(),
book: this.book(),
selected,
shiftKey,
});
if (this.onBookSelect) {
this.onBookSelect(this.book, selected);
const selectFn = this.onBookSelect();
if (selectFn) {
selectFn(this.book(), selected);
}
this.lastMouseEvent = null;