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:
+11
@@ -19,4 +19,15 @@ describe('BookBrowserScrollService', () => {
|
||||
service.clearPosition('books');
|
||||
expect(service.getPosition('books')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('clearAll removes all stored positions', () => {
|
||||
const fresh = new BookBrowserScrollService();
|
||||
fresh.savePosition('a', 10);
|
||||
fresh.savePosition('b', 20);
|
||||
|
||||
fresh.clearAll();
|
||||
|
||||
expect(fresh.getPosition('a')).toBeUndefined();
|
||||
expect(fresh.getPosition('b')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,10 @@ export class BookBrowserScrollService {
|
||||
this.scrollPositions.delete(key);
|
||||
}
|
||||
|
||||
clearAll(): void {
|
||||
this.scrollPositions.clear();
|
||||
}
|
||||
|
||||
createKey(path: string, params: Record<string, string>): string {
|
||||
const paramValues = Object.values(params).join('-');
|
||||
return paramValues ? `${path}:${paramValues}` : path;
|
||||
|
||||
+25
-28
@@ -318,35 +318,32 @@
|
||||
></app-book-table>
|
||||
}
|
||||
@if (currentViewMode === 'grid') {
|
||||
<virtual-scroller class="virtual-scroller" #scroll
|
||||
[items]="books"
|
||||
[bufferAmount]="16"
|
||||
[compareItems]="compareBookItems"
|
||||
(vsEnd)="onScrollEnd()">
|
||||
<div
|
||||
class="grid"
|
||||
#container
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
@for (book of scroll.viewPortItems; let i = $index; track book.id) {
|
||||
<div
|
||||
class="virtual-scroller-item"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||
<app-book-card
|
||||
[index]="bookIndexById().get(book.id) ?? i"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[seriesViewEnabled]="seriesViewEnabled"
|
||||
[onBookSelect]="onBookCardSelect"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="selectedBooks().has(book.id)"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
}
|
||||
<div class="virtual-scroller" #scrollContainer>
|
||||
<div class="scroll-height-anchor" [ngStyle]="{'min-height': estimatedTotalHeight() + 'px'}">
|
||||
<div class="book-grid"
|
||||
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
|
||||
@for (book of books; track book.id; let i = $index) {
|
||||
<div
|
||||
class="virtual-scroller-item"
|
||||
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||
<app-book-card
|
||||
[index]="i"
|
||||
[book]="book"
|
||||
[isCheckboxEnabled]="true"
|
||||
[seriesViewEnabled]="seriesViewEnabled"
|
||||
[onBookSelect]="onBookCardSelect"
|
||||
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
|
||||
(checkboxClick)="onCheckboxClicked($event)"
|
||||
[isSelected]="selectedBooks().has(book.id)"
|
||||
[useSquareCovers]="isAudiobookOnlyLibrary"
|
||||
[overlayPreferenceService]="bookCardOverlayPreferenceService">
|
||||
</app-book-card>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="scroll-sentinel" #scrollSentinel></div>
|
||||
</div>
|
||||
</virtual-scroller>
|
||||
</div>
|
||||
}
|
||||
@if (userService.currentUser(); as currentUser) {
|
||||
<div class="book-browser-footer" [class.footer-hidden]="selectedCount() === 0">
|
||||
|
||||
@@ -440,32 +440,31 @@
|
||||
padding: 1rem;
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
will-change: scroll-position;
|
||||
overflow-anchor: none;
|
||||
|
||||
@media (width <= 768px) {
|
||||
height: calc(100dvh - 9rem);
|
||||
}
|
||||
}
|
||||
|
||||
.grid {
|
||||
.book-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(1px, 1fr));
|
||||
column-gap: 21px;
|
||||
gap: 21px;
|
||||
align-items: start;
|
||||
width: 100%;
|
||||
contain: layout style;
|
||||
|
||||
// Mobile: fixed 2 or 3 columns based on phone width
|
||||
@media (width <= 767px) {
|
||||
column-gap: 8px;
|
||||
gap: 0.5rem 8px;
|
||||
padding: 0 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.scroll-sentinel {
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
.virtual-scroller-item {
|
||||
position: relative;
|
||||
margin-bottom: 21px; // Whole px to avoid parseInt truncation in ngx-virtual-scroller
|
||||
margin-bottom: 21px;
|
||||
contain: strict;
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto var(--virtual-scroller-item-height, 220px);
|
||||
|
||||
+48
-2
@@ -1,4 +1,4 @@
|
||||
import {computed, signal, WritableSignal} from '@angular/core';
|
||||
import {computed, ElementRef, signal, WritableSignal} from '@angular/core';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRoute, convertToParamMap, ParamMap, Router} from '@angular/router';
|
||||
import {BehaviorSubject, Subject} from 'rxjs';
|
||||
@@ -247,6 +247,7 @@ function createHarness(options?: {
|
||||
const _filters = signal<AppBookFilters>({});
|
||||
const _sort = signal<AppBookSort>({field: 'addedOn', dir: 'desc'});
|
||||
const _search = signal('');
|
||||
const _hasNextPage = signal(false);
|
||||
|
||||
const filteredSortedBooks = computed(() => {
|
||||
let result = books();
|
||||
@@ -266,7 +267,8 @@ function createHarness(options?: {
|
||||
return {
|
||||
books: filteredSortedBooks,
|
||||
totalElements: computed(() => filteredSortedBooks().length),
|
||||
hasNextPage: computed(() => false),
|
||||
hasNextPage: _hasNextPage.asReadonly(),
|
||||
setHasNextPage: (v: boolean) => _hasNextPage.set(v),
|
||||
isLoading: isBooksLoading.asReadonly(),
|
||||
isFetchingNextPage: computed(() => false),
|
||||
isError: computed(() => !!booksError()),
|
||||
@@ -354,9 +356,20 @@ function createHarness(options?: {
|
||||
describe('BookBrowserComponent', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
});
|
||||
vi.stubGlobal('IntersectionObserver', class {
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
TestBed.resetTestingModule();
|
||||
@@ -423,4 +436,37 @@ describe('BookBrowserComponent', () => {
|
||||
expect(component.showGridLoadingPlaceholder).toBe(false);
|
||||
expect(component.showTableLoadingPlaceholder).toBe(false);
|
||||
});
|
||||
|
||||
it('triggers next page fetch when scrolled near the bottom of rendered content', async () => {
|
||||
const {component} = createHarness();
|
||||
const appBooksApi = TestBed.inject(AppBooksApiService);
|
||||
|
||||
// Initial load
|
||||
vi.runOnlyPendingTimers();
|
||||
TestBed.flushEffects();
|
||||
|
||||
// Mock hasNextPage to be true
|
||||
// @ts-expect-error test helper
|
||||
appBooksApi.setHasNextPage(true);
|
||||
const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage');
|
||||
|
||||
// Mock scroll container
|
||||
const mockElement = {
|
||||
scrollTop: 2000,
|
||||
clientHeight: 1000,
|
||||
clientWidth: 1000,
|
||||
scrollHeight: 5000,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
} as unknown as HTMLElement;
|
||||
|
||||
component.currentViewMode = VIEW_MODES.GRID;
|
||||
component.scrollContainerRef = {nativeElement: mockElement} as ElementRef<HTMLElement>;
|
||||
|
||||
// Trigger initial check
|
||||
vi.runOnlyPendingTimers(); // For requestAnimationFrame
|
||||
TestBed.flushEffects();
|
||||
|
||||
expect(fetchNextPageSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import {AfterViewInit, ChangeDetectionStrategy, Component, HostListener, computed, effect, inject, OnDestroy, OnInit, signal, untracked, ViewChild} from '@angular/core';
|
||||
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||
import {AfterViewInit, ChangeDetectionStrategy, Component, DestroyRef, ElementRef, HostListener, OnDestroy, computed, effect, inject, OnInit, signal, untracked, ViewChild} from '@angular/core';
|
||||
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||
import {PageTitleService} from '../../../../shared/service/page-title.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
|
||||
import {debounceTime, distinctUntilChanged, filter, map, takeUntil} from 'rxjs/operators';
|
||||
import {debounceTime, distinctUntilChanged, filter, map, take} from 'rxjs/operators';
|
||||
import {combineLatest, finalize, Subject} from 'rxjs';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {Library} from '../../model/library.model';
|
||||
@@ -13,10 +13,9 @@ import {SortDirection, SortOption} from '../../model/sort.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, style, transition, trigger} from '@angular/animations';
|
||||
import {computeGridColumns} from '../../../../shared/util/viewport.util';
|
||||
import {Button} from 'primeng/button';
|
||||
import {NgClass, NgStyle} from '@angular/common';
|
||||
import {VirtualScrollerComponent, VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
|
||||
import {BookCardComponent} from './book-card/book-card.component';
|
||||
|
||||
import {Menu} from 'primeng/menu';
|
||||
@@ -36,7 +35,7 @@ import {Divider} from 'primeng/divider';
|
||||
import {MultiSelect} from 'primeng/multiselect';
|
||||
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||
import {TieredMenu} from 'primeng/tieredmenu';
|
||||
import {BadgeModule} from 'primeng/badge';
|
||||
import {Badge} from 'primeng/badge';
|
||||
import {BookMenuService} from '../../service/book-menu.service';
|
||||
import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service';
|
||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
@@ -74,23 +73,11 @@ export enum EntityType {
|
||||
styleUrls: ['./book-browser.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [
|
||||
Button, VirtualScrollerModule, BookCardComponent, Menu, InputText, FormsModule,
|
||||
Button, BookCardComponent, Menu, InputText, FormsModule,
|
||||
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
|
||||
Checkbox, Slider, Divider, MultiSelect, TieredMenu, BadgeModule, MultiSortPopoverComponent, TranslocoDirective
|
||||
Checkbox, Slider, Divider, MultiSelect, TieredMenu, Badge, MultiSortPopoverComponent, TranslocoDirective,
|
||||
],
|
||||
providers: [SeriesCollapseFilter],
|
||||
animations: [
|
||||
trigger('slideInOut', [
|
||||
transition(':enter', [
|
||||
style({transform: 'translateY(100%)'}),
|
||||
animate('0.1s ease-in', style({transform: 'translateY(0)'}))
|
||||
]),
|
||||
transition(':leave', [
|
||||
style({transform: 'translateY(0)'}),
|
||||
animate('0.1s ease-out', style({transform: 'translateY(100%)'}))
|
||||
])
|
||||
])
|
||||
]
|
||||
})
|
||||
export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
|
||||
@@ -123,6 +110,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
private localStorageService = inject(LocalStorageService);
|
||||
private scrollService = inject(BookBrowserScrollService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
private readonly defaultSortCriteria: SortOption[] = [{
|
||||
field: 'addedOn',
|
||||
@@ -294,6 +282,41 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
return map;
|
||||
});
|
||||
readonly compareBookItems = (a: Book, b: Book): boolean => a?.id === b?.id;
|
||||
|
||||
private readonly GRID_GAP = 21;
|
||||
private readonly containerWidth = signal(0);
|
||||
private containerResizeObserver: ResizeObserver | undefined;
|
||||
|
||||
readonly gridColumns = computed(() => {
|
||||
return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth, 10) || 180, this.GRID_GAP);
|
||||
});
|
||||
|
||||
/**
|
||||
* Estimated total content height based on totalElements from the first API page.
|
||||
* Used as min-height so the scrollbar reflects the full collection from the start.
|
||||
* Only grows, never shrinks — prevents scroll teleportation.
|
||||
*/
|
||||
readonly estimatedTotalHeight = computed(() => {
|
||||
const total = this.appBooksApi.totalElements();
|
||||
if (total === 0) return 0;
|
||||
const cols = this.gridColumns();
|
||||
const rows = Math.ceil(total / cols);
|
||||
const rowHeight = this.currentCardSize.height + this.GRID_GAP;
|
||||
return rows * rowHeight;
|
||||
});
|
||||
|
||||
/**
|
||||
* Total height of currently loaded books in grid view.
|
||||
*/
|
||||
readonly renderedHeight = computed(() => {
|
||||
const books = this.books();
|
||||
if (!books || books.length === 0) return 0;
|
||||
const cols = this.gridColumns();
|
||||
const rows = Math.ceil(books.length / cols);
|
||||
const rowHeight = this.currentCardSize.height + this.GRID_GAP;
|
||||
return rows * rowHeight;
|
||||
});
|
||||
|
||||
protected resetFilterSubject = new Subject<void>();
|
||||
|
||||
readonly skeletonSlots = Array.from({length: 24}, (_, index) => index);
|
||||
@@ -321,7 +344,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
private readonly MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference';
|
||||
|
||||
private settingFiltersFromUrl = false;
|
||||
private destroy$ = new Subject<void>();
|
||||
protected metadataMenuItems: MenuItem[] | undefined;
|
||||
protected moreActionsMenuItems: MenuItem[] | undefined;
|
||||
protected readonly onBookCardSelect = (book: Book, selected: boolean): void => {
|
||||
@@ -389,12 +411,61 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Triggers sequential page loads if the current scroll position is beyond the loaded content.
|
||||
* This is critical for scroll restoration on page reload.
|
||||
*/
|
||||
private readonly fillScrollGapEffect = effect(() => {
|
||||
const books = this.books();
|
||||
if (books && books.length > 0) {
|
||||
this.checkAndFetchIfNeeded();
|
||||
}
|
||||
});
|
||||
|
||||
@ViewChild(BookTableComponent)
|
||||
bookTableComponent!: BookTableComponent;
|
||||
@ViewChild(BookFilterComponent, {static: false})
|
||||
bookFilterComponent!: BookFilterComponent;
|
||||
@ViewChild('scroll')
|
||||
virtualScroller: VirtualScrollerComponent | undefined;
|
||||
|
||||
private scrollContainer: HTMLElement | undefined;
|
||||
private sentinelObserver: IntersectionObserver | undefined;
|
||||
|
||||
@ViewChild('scrollContainer')
|
||||
set scrollContainerRef(ref: ElementRef<HTMLElement> | undefined) {
|
||||
this.containerResizeObserver?.disconnect();
|
||||
if (this.scrollContainer) {
|
||||
this.scrollContainer.removeEventListener('scroll', this.onScroll);
|
||||
}
|
||||
this.scrollContainer = ref?.nativeElement;
|
||||
if (this.scrollContainer) {
|
||||
const el = this.scrollContainer;
|
||||
this.containerWidth.set(el.clientWidth);
|
||||
this.containerResizeObserver = new ResizeObserver(entries => {
|
||||
this.containerWidth.set(entries[0]?.contentRect.width ?? el.clientWidth);
|
||||
});
|
||||
this.containerResizeObserver.observe(el);
|
||||
el.addEventListener('scroll', this.onScroll, {passive: true});
|
||||
// Initial check in case we are already scrolled down
|
||||
globalThis.requestAnimationFrame(() => this.checkAndFetchIfNeeded());
|
||||
}
|
||||
}
|
||||
|
||||
@ViewChild('scrollSentinel')
|
||||
set scrollSentinelRef(ref: ElementRef<HTMLElement> | undefined) {
|
||||
this.sentinelObserver?.disconnect();
|
||||
const el = ref?.nativeElement;
|
||||
if (el) {
|
||||
this.sentinelObserver = new IntersectionObserver(
|
||||
entries => {
|
||||
if (entries[0]?.isIntersecting) {
|
||||
this.checkAndFetchNextPage();
|
||||
}
|
||||
},
|
||||
{root: this.scrollContainer, rootMargin: '600px'}
|
||||
);
|
||||
this.sentinelObserver.observe(el);
|
||||
}
|
||||
}
|
||||
|
||||
@HostListener('window:resize')
|
||||
onResize(): void {
|
||||
@@ -533,8 +604,37 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
if (this.scrollContainer) {
|
||||
this.scrollContainer.removeEventListener('scroll', this.onScroll);
|
||||
}
|
||||
this.containerResizeObserver?.disconnect();
|
||||
this.sentinelObserver?.disconnect();
|
||||
}
|
||||
|
||||
private onScroll = (): void => {
|
||||
this.checkAndFetchIfNeeded();
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the current scroll position plus viewport exceeds the rendered height (with a buffer)
|
||||
* and fetches the next page if necessary.
|
||||
*/
|
||||
private checkAndFetchIfNeeded(): void {
|
||||
if (!this.scrollContainer || this.currentViewMode === VIEW_MODES.TABLE) return;
|
||||
|
||||
const {scrollTop, clientHeight} = this.scrollContainer;
|
||||
const buffer = 1000; // Large buffer to facilitate scroll restoration
|
||||
const renderedHeight = untracked(() => this.renderedHeight());
|
||||
|
||||
if (scrollTop + clientHeight >= renderedHeight - buffer) {
|
||||
untracked(() => this.checkAndFetchNextPage());
|
||||
}
|
||||
}
|
||||
|
||||
private checkAndFetchNextPage(): void {
|
||||
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
|
||||
this.appBooksApi.fetchNextPage();
|
||||
}
|
||||
}
|
||||
|
||||
private getScrollPositionKey(): string {
|
||||
@@ -545,29 +645,38 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
private setupScrollPositionTracking(): void {
|
||||
this.router.events.pipe(
|
||||
filter(event => event instanceof NavigationStart),
|
||||
takeUntil(this.destroy$)
|
||||
takeUntilDestroyed(this.destroyRef)
|
||||
).subscribe(() => {
|
||||
this.saveScrollPosition();
|
||||
});
|
||||
}
|
||||
|
||||
private saveScrollPosition(): void {
|
||||
if (this.virtualScroller?.viewPortInfo) {
|
||||
if (this.scrollContainer) {
|
||||
const key = this.getScrollPositionKey();
|
||||
const position = this.virtualScroller.viewPortInfo.scrollStartPosition ?? 0;
|
||||
this.scrollService.savePosition(key, position);
|
||||
this.scrollService.savePosition(key, this.scrollContainer.scrollTop);
|
||||
}
|
||||
}
|
||||
|
||||
private setupRouteChangeHandlers(): void {
|
||||
this.activatedRoute.paramMap.pipe(takeUntil(this.destroy$)).subscribe(() => {
|
||||
this.activatedRoute.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => {
|
||||
this.searchTerm.set('');
|
||||
this.bookTitle = '';
|
||||
this.bookSelectionService.deselectAll();
|
||||
this.clearFilter();
|
||||
this.scrollToTop();
|
||||
});
|
||||
}
|
||||
|
||||
private scrollToTop(): void {
|
||||
if (this.scrollContainer) {
|
||||
this.scrollContainer.scrollTop = 0;
|
||||
}
|
||||
if (this.bookTableComponent) {
|
||||
this.bookTableComponent.scrollToTop();
|
||||
}
|
||||
}
|
||||
|
||||
private readonly syncMetadataMenuEffect = effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (!user) return;
|
||||
@@ -589,7 +698,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
this.activatedRoute.queryParamMap,
|
||||
this.currentUser$,
|
||||
]).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
takeUntilDestroyed(this.destroyRef)
|
||||
).subscribe(([entityInfo, queryParamMap, currentUser]) => {
|
||||
const parseResult = this.queryParamsService.parseQueryParams(
|
||||
queryParamMap,
|
||||
@@ -934,8 +1043,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
openShelfAssigner(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks());
|
||||
if (this.dynamicDialogRef) {
|
||||
this.dynamicDialogRef.onClose.subscribe(result => {
|
||||
if (result.assigned) {
|
||||
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(result => {
|
||||
if (result?.assigned) {
|
||||
this.bookSelectionService.deselectAll();
|
||||
}
|
||||
});
|
||||
@@ -945,7 +1054,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
lockUnlockMetadata(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks());
|
||||
if (this.dynamicDialogRef) {
|
||||
this.dynamicDialogRef.onClose.subscribe(() => {
|
||||
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(() => {
|
||||
this.bookSelectionService.deselectAll();
|
||||
});
|
||||
}
|
||||
@@ -967,7 +1076,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
bulkEditMetadata(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks());
|
||||
if (this.dynamicDialogRef) {
|
||||
this.dynamicDialogRef.onClose.subscribe(() => {
|
||||
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(() => {
|
||||
this.bookSelectionService.deselectAll();
|
||||
});
|
||||
}
|
||||
@@ -976,7 +1085,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
multiBookEditMetadata(): void {
|
||||
this.dynamicDialogRef = this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks());
|
||||
if (this.dynamicDialogRef) {
|
||||
this.dynamicDialogRef.onClose.subscribe(() => {
|
||||
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(() => {
|
||||
this.bookSelectionService.deselectAll();
|
||||
});
|
||||
}
|
||||
@@ -1096,7 +1205,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
|
||||
this.dynamicDialogRef = this.dialogHelperService.openBulkBookFileAttacherDialog(sourceBooks);
|
||||
if (this.dynamicDialogRef) {
|
||||
this.dynamicDialogRef.onClose.subscribe(result => {
|
||||
this.dynamicDialogRef.onClose.pipe(take(1)).subscribe(result => {
|
||||
if (result?.success) {
|
||||
this.bookSelectionService.deselectAll();
|
||||
}
|
||||
@@ -1129,10 +1238,4 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
this.mobileColumnCount = saved;
|
||||
}
|
||||
}
|
||||
|
||||
onScrollEnd(): void {
|
||||
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
|
||||
this.appBooksApi.fetchNextPage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+59
-64
@@ -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>
|
||||
|
||||
+14
-38
@@ -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;
|
||||
}
|
||||
|
||||
+103
-83
@@ -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();
|
||||
|
||||
|
||||
+264
-355
@@ -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;
|
||||
|
||||
+19
-12
@@ -1,9 +1,9 @@
|
||||
import {Component, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output} from '@angular/core';
|
||||
import {Component, ElementRef, 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 {Tooltip} 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';
|
||||
@@ -13,7 +13,6 @@ import {BookService} from '../../../service/book.service';
|
||||
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {RouterLink} from '@angular/router';
|
||||
import {Subject} from 'rxjs';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
@@ -27,7 +26,7 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
Rating,
|
||||
FormsModule,
|
||||
Button,
|
||||
TooltipModule,
|
||||
Tooltip,
|
||||
NgClass,
|
||||
RouterLink,
|
||||
TranslocoDirective,
|
||||
@@ -54,9 +53,10 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
private datePipe = inject(DatePipe);
|
||||
private readStatusHelper = inject(ReadStatusHelper);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private elementRef = inject(ElementRef);
|
||||
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
private destroy$ = new Subject<void>();
|
||||
private resizeListener = this.setScrollHeight.bind(this);
|
||||
|
||||
readonly allColumns: { field: string; header: string }[] = [
|
||||
{field: 'readStatus', header: this.t.translate('book.columnPref.columns.readStatus')},
|
||||
@@ -94,7 +94,7 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
this.selectedBookIds = this.preselectedBookIds;
|
||||
this.selectedBooks = this.bookService.getBooksByIds([...this.selectedBookIds]);
|
||||
this.setScrollHeight();
|
||||
window.addEventListener('resize', this.setScrollHeight.bind(this));
|
||||
window.addEventListener('resize', this.resizeListener);
|
||||
}
|
||||
|
||||
setScrollHeight() {
|
||||
@@ -105,12 +105,21 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
}
|
||||
|
||||
ngOnChanges() {
|
||||
const wrapperElements: HTMLCollection = document.getElementsByClassName('p-virtualscroller');
|
||||
Array.prototype.forEach.call(wrapperElements, function (wrapperElement) {
|
||||
wrapperElement.style["height"] = 'calc(100dvh - 160px)';
|
||||
const wrapperElements = this.elementRef.nativeElement.querySelectorAll('.p-virtualscroller');
|
||||
wrapperElements.forEach((wrapperElement: Element) => {
|
||||
if (wrapperElement instanceof HTMLElement) {
|
||||
wrapperElement.style.height = 'calc(100dvh - 160px)';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
scrollToTop(): void {
|
||||
const tableElement = this.elementRef.nativeElement.querySelector('.p-datatable-wrapper');
|
||||
if (tableElement instanceof HTMLElement) {
|
||||
tableElement.scrollTop = 0;
|
||||
}
|
||||
}
|
||||
|
||||
selectAllBooks(): void {
|
||||
this.selectedBookIds = new Set(this.books.map(book => book.id));
|
||||
this.selectedBooks = [...this.books];
|
||||
@@ -343,8 +352,6 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
window.removeEventListener('resize', this.setScrollHeight.bind(this));
|
||||
window.removeEventListener('resize', this.resizeListener);
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -1,3 +1,4 @@
|
||||
import {signal} from '@angular/core';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
@@ -16,7 +17,10 @@ describe('BookCardLiteComponent', () => {
|
||||
getThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
getAudiobookThumbnailUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let userService: {currentUser: ReturnType<typeof vi.fn>};
|
||||
let userService: {
|
||||
currentUser: ReturnType<typeof signal<unknown>>;
|
||||
getCurrentUser: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let hostService: {requestBookSwitch: ReturnType<typeof vi.fn>};
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -25,8 +29,10 @@ describe('BookCardLiteComponent', () => {
|
||||
getThumbnailUrl: vi.fn(() => '/covers/1'),
|
||||
getAudiobookThumbnailUrl: vi.fn(() => '/covers/audio/1'),
|
||||
};
|
||||
const currentUser = signal<unknown>({userSettings: {metadataCenterViewMode: 'route'}});
|
||||
userService = {
|
||||
currentUser: vi.fn(() => ({userSettings: {metadataCenterViewMode: 'route'}})),
|
||||
currentUser,
|
||||
getCurrentUser: vi.fn(() => currentUser()),
|
||||
};
|
||||
hostService = {
|
||||
requestBookSwitch: vi.fn(),
|
||||
@@ -84,7 +90,7 @@ describe('BookCardLiteComponent', () => {
|
||||
});
|
||||
|
||||
it('delegates to the metadata host when the user prefers dialog mode', () => {
|
||||
userService.currentUser.mockReturnValue({userSettings: {metadataCenterViewMode: 'dialog'}});
|
||||
userService.currentUser.set({userSettings: {metadataCenterViewMode: 'dialog'}});
|
||||
const book = buildBook();
|
||||
|
||||
component.openBookInfo(book);
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
|
||||
import {TooltipModule} from 'primeng/tooltip';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card-lite-component',
|
||||
@@ -15,7 +15,7 @@ import {TooltipModule} from 'primeng/tooltip';
|
||||
imports: [
|
||||
Button,
|
||||
NgClass,
|
||||
TooltipModule,
|
||||
Tooltip,
|
||||
CoverPlaceholderComponent
|
||||
],
|
||||
templateUrl: './book-card-lite-component.html',
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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';
|
||||
@@ -17,7 +16,6 @@ import {BookNote, BookNoteService, CreateBookNoteRequest} from '../../../../shar
|
||||
selector: 'app-book-notes-component',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
Button,
|
||||
Dialog,
|
||||
|
||||
@@ -3,7 +3,7 @@ import {toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {InputTextModule} from 'primeng/inputtext';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {SlicePipe} from '@angular/common';
|
||||
@@ -22,7 +22,7 @@ import {Popover} from 'primeng/popover';
|
||||
templateUrl: './book-searcher.component.html',
|
||||
imports: [
|
||||
FormsModule,
|
||||
InputTextModule,
|
||||
InputText,
|
||||
Button,
|
||||
SlicePipe,
|
||||
Skeleton,
|
||||
|
||||
@@ -398,7 +398,7 @@
|
||||
</p-tabs>
|
||||
@if (selectedBooks.size > 0) {
|
||||
@if (currentUser(); as user) {
|
||||
<div class="book-browser-footer" [@slideInOut]>
|
||||
<div class="book-browser-footer" [animate.enter]="'slide-in-up'" [animate.leave]="'slide-out-down'">
|
||||
<div class="footer-content">
|
||||
<div class="footer-left">
|
||||
<div class="selected-count-badge">
|
||||
|
||||
@@ -808,6 +808,24 @@
|
||||
|
||||
// ── Footer ──
|
||||
|
||||
@keyframes slide-in-up {
|
||||
from { transform: translateY(100%); }
|
||||
to { transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes slide-out-down {
|
||||
from { transform: translateY(0); }
|
||||
to { transform: translateY(100%); }
|
||||
}
|
||||
|
||||
.slide-in-up {
|
||||
animation: slide-in-up 0.1s ease-in forwards;
|
||||
}
|
||||
|
||||
.slide-out-down {
|
||||
animation: slide-out-down 0.1s ease-out forwards;
|
||||
}
|
||||
|
||||
.book-browser-footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
|
||||
@@ -3,14 +3,13 @@ import {Button} from "primeng/button";
|
||||
import {ActivatedRoute, Router} from "@angular/router";
|
||||
import {toSignal} from '@angular/core/rxjs-interop';
|
||||
import {DecimalPipe, KeyValuePipe, NgClass, NgStyle} from "@angular/common";
|
||||
import {finalize, map} from "rxjs/operators";
|
||||
import {finalize, map, take} from "rxjs/operators";
|
||||
import {Book, BookType, computeSeriesReadStatus, ReadStatus} from "../../model/book.model";
|
||||
import {BookService} from "../../service/book.service";
|
||||
import {BookMetadataManageService} from "../../service/book-metadata-manage.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 {VirtualScrollerModule} from "@iharbeck/ngx-virtual-scroller";
|
||||
import {ProgressSpinner} from "primeng/progressspinner";
|
||||
import {ProgressBar} from "primeng/progressbar";
|
||||
import {DynamicDialogRef} from "primeng/dynamicdialog";
|
||||
@@ -27,7 +26,6 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
import {Tooltip} from "primeng/tooltip";
|
||||
import {Divider} from "primeng/divider";
|
||||
import {TagComponent} from "../../../../shared/components/tag/tag.component";
|
||||
import {animate, style, transition, trigger} from "@angular/animations";
|
||||
import {AfterViewChecked, Component, computed, effect, ElementRef, inject, ViewChild} from '@angular/core';
|
||||
import {BookCardOverlayPreferenceService} from '../book-browser/book-card-overlay-preference.service';
|
||||
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
|
||||
@@ -84,26 +82,13 @@ interface SeriesStats {
|
||||
Tab,
|
||||
TabPanels,
|
||||
TabPanel,
|
||||
VirtualScrollerModule,
|
||||
TieredMenu,
|
||||
Tooltip,
|
||||
Divider,
|
||||
TranslocoDirective,
|
||||
TagComponent,
|
||||
CoverPlaceholderComponent
|
||||
CoverPlaceholderComponent,
|
||||
],
|
||||
animations: [
|
||||
trigger('slideInOut', [
|
||||
transition(':enter', [
|
||||
style({transform: 'translateY(100%)'}),
|
||||
animate('0.1s ease-in', style({transform: 'translateY(0)'}))
|
||||
]),
|
||||
transition(':leave', [
|
||||
style({transform: 'translateY(0)'}),
|
||||
animate('0.1s ease-out', style({transform: 'translateY(100%)'}))
|
||||
])
|
||||
])
|
||||
]
|
||||
})
|
||||
export class SeriesPageComponent implements AfterViewChecked {
|
||||
|
||||
@@ -606,7 +591,7 @@ export class SeriesPageComponent implements AfterViewChecked {
|
||||
openShelfAssigner(): void {
|
||||
this.dialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks);
|
||||
if (this.dialogRef) {
|
||||
this.dialogRef.onClose.subscribe(result => {
|
||||
this.dialogRef.onClose.pipe(take(1)).subscribe(result => {
|
||||
if (result.assigned) {
|
||||
this.selectedBooks.clear();
|
||||
}
|
||||
@@ -617,7 +602,7 @@ export class SeriesPageComponent implements AfterViewChecked {
|
||||
lockUnlockMetadata(): void {
|
||||
this.dialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks);
|
||||
if (this.dialogRef) {
|
||||
this.dialogRef.onClose.subscribe(() => {
|
||||
this.dialogRef.onClose.pipe(take(1)).subscribe(() => {
|
||||
this.deselectAllBooks();
|
||||
});
|
||||
}
|
||||
@@ -638,7 +623,7 @@ export class SeriesPageComponent implements AfterViewChecked {
|
||||
bulkEditMetadata(): void {
|
||||
this.dialogRef = this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks);
|
||||
if (this.dialogRef) {
|
||||
this.dialogRef.onClose.subscribe(() => {
|
||||
this.dialogRef.onClose.pipe(take(1)).subscribe(() => {
|
||||
this.deselectAllBooks();
|
||||
});
|
||||
}
|
||||
@@ -647,7 +632,7 @@ export class SeriesPageComponent implements AfterViewChecked {
|
||||
multiBookEditMetadata(): void {
|
||||
this.dialogRef = this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks);
|
||||
if (this.dialogRef) {
|
||||
this.dialogRef.onClose.subscribe(() => {
|
||||
this.dialogRef.onClose.pipe(take(1)).subscribe(() => {
|
||||
this.deselectAllBooks();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {InputText} from 'primeng/inputtext';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {CheckboxModule} from 'primeng/checkbox';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Component({
|
||||
@@ -23,7 +23,7 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
InputText,
|
||||
Tooltip,
|
||||
IconDisplayComponent,
|
||||
CheckboxModule,
|
||||
Checkbox,
|
||||
TranslocoDirective
|
||||
],
|
||||
styleUrl: './shelf-creator.component.scss',
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ import {Shelf} from '../../model/shelf.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {IconPickerService, IconSelection} from '../../../../shared/service/icon-picker.service';
|
||||
import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component';
|
||||
import {CheckboxModule} from 'primeng/checkbox';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@@ -21,7 +21,7 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
ReactiveFormsModule,
|
||||
FormsModule,
|
||||
IconDisplayComponent,
|
||||
CheckboxModule,
|
||||
Checkbox,
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './shelf-edit-dialog.component.html',
|
||||
|
||||
@@ -40,7 +40,7 @@ export class AppBooksApiService {
|
||||
getNextPageParam: (lastPage: AppPageResponse<AppBookSummary>) =>
|
||||
lastPage.hasNext ? lastPage.page + 1 : undefined,
|
||||
enabled: !!this.token(),
|
||||
staleTime: 30_000,
|
||||
staleTime: 5 * 60_000,
|
||||
}));
|
||||
|
||||
readonly filterOptionsQuery = injectQuery(() => ({
|
||||
@@ -54,7 +54,7 @@ export class AppBooksApiService {
|
||||
return lastValueFrom(this.http.get<AppFilterOptions>(this.filterOptionsUrl, {params}));
|
||||
},
|
||||
enabled: !!this.token(),
|
||||
staleTime: 60_000,
|
||||
staleTime: 10 * 60_000,
|
||||
}));
|
||||
|
||||
/** Accumulated books from all loaded pages, mapped to the Book interface. */
|
||||
|
||||
@@ -5,7 +5,7 @@ import {TranslocoService} from '@jsverse/transloco';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects} from '../../../core/testing/query-testing';
|
||||
import {createAuthServiceStub, createQueryClientHarness, flushSignalAndQueryEffects, flushQueryAsync} from '../../../core/testing/query-testing';
|
||||
import type {Book, BookMetadata} from '../model/book.model';
|
||||
import type {Shelf} from '../model/shelf.model';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
@@ -46,12 +46,7 @@ function buildBook(id: number, overrides: BuildBookOverrides = {}): Book {
|
||||
}
|
||||
|
||||
async function flushBooksQuery(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
flushSignalAndQueryEffects();
|
||||
await Promise.resolve();
|
||||
flushSignalAndQueryEffects();
|
||||
await flushQueryAsync();
|
||||
}
|
||||
|
||||
describe('BookService', () => {
|
||||
|
||||
@@ -103,7 +103,7 @@ export class BookService {
|
||||
return queryOptions({
|
||||
queryKey: BOOKS_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url, {params: {stripForListView: false}})),
|
||||
staleTime: 30_000,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user