refactor(ui): use tanstack virtual+table for book browser table view (#1047)

This commit is contained in:
Alex
2026-05-03 08:11:19 +01:00
committed by GitHub
parent 34eb6ce412
commit 1c9902448f
43 changed files with 2241 additions and 785 deletions
@@ -128,17 +128,17 @@
<button
type="button"
class="browser-grid-option-btn"
[class.active]="mobileColumnCount() === 2"
[class.active]="gridMobileColumnCount() === 2"
(click)="setMobileColumns(2)">2</button>
<button
type="button"
class="browser-grid-option-btn"
[class.active]="mobileColumnCount() === 3"
[class.active]="gridMobileColumnCount() === 3"
(click)="setMobileColumns(3)">3</button>
<button
type="button"
class="browser-grid-option-btn"
[class.active]="mobileColumnCount() === 4"
[class.active]="gridMobileColumnCount() === 4"
(click)="setMobileColumns(4)">4</button>
</div>
</div>
@@ -253,38 +253,20 @@
</div>
</div>
@if (showTableLoadingPlaceholder()) {
<div class="table-skeleton" aria-hidden="true">
<div class="table-skeleton-header">
@for (column of tableSkeletonColumns; track column) {
<div class="table-skeleton-cell table-skeleton-cell-header"></div>
}
</div>
@for (row of tableSkeletonRows; track row) {
<div class="table-skeleton-row">
@for (column of tableSkeletonColumns; track column) {
<div class="table-skeleton-cell" [class.table-skeleton-cell-short]="column !== 0"></div>
}
</div>
}
</div>
} @else if (showGridLoadingPlaceholder()) {
<div #scrollElement class="virtual-scroller">
<div class="skeleton-grid"
[style.grid-template-columns]="'repeat(auto-fill, minmax(' + skeletonMinCardWidth() + ', 1fr))'">
@for (item of skeletonSlots; track item) {
<div class="skeleton-card"
[style.width.px]="currentCardSize().width"
[style.height.px]="currentCardSize().height">
</div>
}
</div>
</div>
} @else if (booksError()) {
@if (booksError()) {
<div class="no-books-container">
<p class="no-books-text">
{{ entityType() === EntityType.LIBRARY ? t('labels.failedLibrary') : t('labels.failedShelf') }}
@switch (entityType()) {
@case (EntityType.LIBRARY) {
{{ t('labels.failedLibrary') }}
}
@case (EntityType.SHELF) {
{{ t('labels.failedShelf') }}
}
@default {
{{ t('labels.failedBooks') }}
}
}
</p>
</div>
} @else {
@@ -296,14 +278,17 @@
</p>
</div>
}
@if (currentViewMode() === 'table' && visibleBooks.length > 0) {
@if (currentViewMode() === 'table' && (visibleBooks.length > 0 || showTableLoadingPlaceholder())) {
<app-book-table
[books]="visibleBooks"
[preselectedBookIds]="selectedBooks()"
(selectedBooksChange)="onSelectedBooksChange($event)"
[virtualRowCount]="virtualRowCount()"
[loadedBookCount]="loadedBookCount()"
[isFetchingNextPage]="isFetchingNextBooksPage()"
[bookQueryToken]="bookQueryToken()"
(selectAllRequested)="selectAllBooks()"
[sortOption]="this.bookSorter.selectedSort!"
(loadNextPage)="loadNextBooksPage()"
[visibleColumns]="visibleColumns()"
[useSquareCovers]="isAudiobookOnlyLibrary()"
></app-book-table>
}
@if (currentViewMode() === 'grid') {
@@ -1,82 +1,18 @@
.skeleton-grid {
display: grid;
gap: 21px;
place-items: start center;
width: 100%;
@media (width <= 767px) {
gap: 8px;
}
}
.skeleton-card {
background: var(--p-content-border-color);
border-radius: 8px;
animation: skeleton-pulse 1.5s ease-in-out infinite;
will-change: opacity;
}
.table-skeleton {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1rem;
}
.table-skeleton-header,
.table-skeleton-row {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 1rem;
align-items: center;
}
.table-skeleton-row {
min-height: 2.75rem;
padding-bottom: 0.75rem;
border-bottom: 1px solid var(--p-content-border-color);
}
.table-skeleton-cell {
height: 0.875rem;
border-radius: 999px;
background: var(--p-content-border-color);
animation: skeleton-pulse 1.5s ease-in-out infinite;
&.table-skeleton-cell-header {
height: 0.75rem;
opacity: 0.75;
}
&.table-skeleton-cell-short {
width: 70%;
}
}
@keyframes skeleton-pulse {
0%, 100% { opacity: 0.3; }
50% { opacity: 0.6; }
}
@media (prefers-reduced-motion: reduce) {
.skeleton-card,
.table-skeleton-cell {
animation: none;
will-change: auto;
}
}
// Layout containers
.book-browser-container {
position: relative;
display: flex;
flex-direction: row;
min-width: 0;
width: 100%;
}
.book-browser-main {
display: flex;
flex-direction: column;
width: 100%;
flex: 1 1 0;
min-width: 0;
width: auto;
}
// Header bar
@@ -413,7 +349,23 @@
}
.virtual-loader-cell {
border-radius: 8px;
background: var(--p-content-border-color);
animation: skeleton-pulse 1.5s ease-in-out infinite;
pointer-events: none;
will-change: opacity;
}
@keyframes skeleton-pulse {
0%, 100% { opacity: 0.3; }
50% { opacity: 0.6; }
}
@media (prefers-reduced-motion: reduce) {
.virtual-loader-cell {
animation: none;
will-change: auto;
}
}
// No books state
@@ -107,6 +107,7 @@ interface BookBrowserHarness {
isBooksLoading: WritableSignal<boolean>;
paramMap$: BehaviorSubject<ParamMap>;
setHasNextPage: (value: boolean) => void;
setIsFetchingNextPage: (value: boolean) => void;
queryParamsService: {
shouldForceExpandSeries: ReturnType<typeof vi.fn>;
updateViewMode: ReturnType<typeof vi.fn>;
@@ -140,6 +141,7 @@ function createHarness(options?: {
);
const booksError = signal<string | null>(options?.booksError ?? null);
const isBooksLoading = signal<boolean>(options?.isBooksLoading ?? false);
const isFetchingNextPage = signal(false);
const hasNextPage = signal(false);
const currentUser = signal(makeCurrentUser());
const showFilter = signal(false);
@@ -313,7 +315,7 @@ function createHarness(options?: {
totalElements,
hasNextPage: hasNextPage.asReadonly(),
isLoading: isBooksLoading.asReadonly(),
isFetchingNextPage: computed(() => false),
isFetchingNextPage: isFetchingNextPage.asReadonly(),
isError: computed(() => !!booksError()),
error: computed(() => booksError()),
filterOptions: computed(() => null),
@@ -394,6 +396,7 @@ function createHarness(options?: {
isBooksLoading,
paramMap$,
setHasNextPage: value => hasNextPage.set(value),
setIsFetchingNextPage: value => isFetchingNextPage.set(value),
queryParamsService,
routeSnapshot,
};
@@ -464,7 +467,6 @@ describe('BookBrowserComponent', () => {
});
expect(component.showBooksLoadingPlaceholder()).toBe(false);
expect(component.showGridLoadingPlaceholder()).toBe(false);
expect(component.showTableLoadingPlaceholder()).toBe(false);
});
@@ -480,7 +482,7 @@ describe('BookBrowserComponent', () => {
});
it('triggers next page fetch when the virtual grid reaches the loaded rows', () => {
const {component, setHasNextPage} = createHarness();
const {component, setHasNextPage} = createHarness({totalElements: 100});
const appBooksApi = TestBed.inject(AppBooksApiService);
vi.runOnlyPendingTimers();
@@ -501,7 +503,72 @@ describe('BookBrowserComponent', () => {
expect(fetchNextPageSpy).toHaveBeenCalled();
});
it('uses the known total book count for virtual grid size while more pages are available', () => {
it('re-arms grid pagination after a next-page request completes without new books', () => {
const {component, books, setHasNextPage, setIsFetchingNextPage} = createHarness({totalElements: 100});
const appBooksApi = TestBed.inject(AppBooksApiService);
vi.spyOn(component.virtualGrid.virtualizer, 'getVirtualItems').mockReturnValue([
{index: 2, key: 3, start: 0, end: 241, size: 241, lane: 0}
]);
component.currentViewMode.set(VIEW_MODES.TABLE);
TestBed.flushEffects();
setHasNextPage(true);
const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage');
component.currentViewMode.set(VIEW_MODES.GRID);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(1);
setIsFetchingNextPage(true);
TestBed.flushEffects();
setIsFetchingNextPage(false);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(1);
books.update(current => [...current]);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(2);
});
it('keeps fetching grid pages when collapsed series hide newly loaded books', () => {
const {component, books, setHasNextPage} = createHarness({
books: [
makeBook(1, 1, 'Alpha', '2024-01-01T00:00:00Z'),
makeBook(2, 1, 'Bravo', '2024-02-01T00:00:00Z'),
makeBook(3, 1, 'Charlie', '2024-03-01T00:00:00Z'),
],
totalElements: 100,
});
const appBooksApi = TestBed.inject(AppBooksApiService);
const filter = TestBed.inject(SeriesCollapseFilter);
vi.mocked(filter.collapseBooks).mockImplementation((items: Book[]) => items.slice(0, 3));
vi.spyOn(component.virtualGrid.virtualizer, 'getVirtualItems').mockReturnValue([
{index: 2, key: 3, start: 0, end: 241, size: 241, lane: 0}
]);
component.currentViewMode.set(VIEW_MODES.TABLE);
TestBed.flushEffects();
setHasNextPage(true);
vi.mocked(filter.setCollapsed)(true);
const fetchNextPageSpy = vi.spyOn(appBooksApi, 'fetchNextPage');
component.currentViewMode.set(VIEW_MODES.GRID);
TestBed.flushEffects();
expect(fetchNextPageSpy).toHaveBeenCalledTimes(1);
books.update(current => [...current, makeBook(4, 1, 'Collapsed', '2024-04-01T00:00:00Z')]);
TestBed.flushEffects();
expect(component.books()).toHaveLength(3);
expect(fetchNextPageSpy).toHaveBeenCalledTimes(2);
});
it('uses the known total book count while more pages are available', () => {
const {component, setHasNextPage} = createHarness({totalElements: 100});
setHasNextPage(true);
@@ -509,9 +576,23 @@ describe('BookBrowserComponent', () => {
vi.runOnlyPendingTimers();
TestBed.flushEffects();
expect(component.virtualRowCount()).toBe(100);
expect(component.virtualGrid.virtualizer.options().count).toBe(100);
});
it('uses one unloaded slot for collapsed series while more pages are available', () => {
const {component, setHasNextPage} = createHarness({totalElements: 100});
const filter = TestBed.inject(SeriesCollapseFilter);
filter.setCollapsed(true);
setHasNextPage(true);
vi.runOnlyPendingTimers();
TestBed.flushEffects();
expect(component.virtualRowCount()).toBe(component.books().length + 1);
expect(component.virtualGrid.virtualizer.options().count).toBe(component.books().length + 1);
});
it('uses the rendered book count once pagination is exhausted', () => {
const {component} = createHarness({totalElements: 100});
const filter = TestBed.inject(SeriesCollapseFilter);
@@ -521,6 +602,7 @@ describe('BookBrowserComponent', () => {
TestBed.flushEffects();
expect(component.books()).toHaveLength(1);
expect(component.virtualRowCount()).toBe(1);
expect(component.virtualGrid.virtualizer.options().count).toBe(1);
});
});
@@ -65,6 +65,10 @@ export enum EntityType {
UNSHELVED = 'Unshelved Books',
}
const INITIAL_LOADING_ROW_COUNT = 24;
const DEFAULT_MOBILE_GRID_COLUMNS = 3;
const MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference';
@Component({
selector: 'app-book-browser',
standalone: true,
@@ -118,6 +122,7 @@ export class BookBrowserComponent implements AfterViewInit {
scrollElement: this.scrollElement,
route: this.activatedRoute,
destroyRef: this.destroyRef,
keySuffix: 'grid',
dismissOverlaysBeforeSave: true,
});
this.destroyRef.onDestroy(() => this.bookSelectionService.deselectAll());
@@ -159,7 +164,7 @@ export class BookBrowserComponent implements AfterViewInit {
readonly visibleSortOptions = signal<SortOption[]>([]);
readonly currentFilterLabel = signal<string | null>(null);
readonly rawFilterParamFromUrl = signal<string | null>(null);
readonly mobileColumnCount = signal(3);
readonly gridMobileColumnCount = signal(DEFAULT_MOBILE_GRID_COLUMNS);
private readonly seriesCollapsed = this.seriesCollapseFilter.seriesCollapsed;
readonly selectedBooks = this.bookSelectionService.selectedBooks;
readonly selectedCount = this.bookSelectionService.selectedCount;
@@ -287,17 +292,14 @@ export class BookBrowserComponent implements AfterViewInit {
private readonly MOBILE_BREAKPOINT = 768;
private readonly CARD_ASPECT_RATIO = 7 / 5;
private readonly MOBILE_GAP = 8;
private readonly MOBILE_PADDING = 48;
private readonly MOBILE_TITLE_BAR_HEIGHT = 32;
private readonly MOBILE_COLUMNS_STORAGE_KEY = 'mobileColumnsPreference';
private readonly DESKTOP_CARD_BASE_WIDTH = 135;
private readonly DESKTOP_CARD_BASE_HEIGHT = 220;
private readonly DESKTOP_MIN_SCALE = 0.5;
private readonly DESKTOP_MAX_SCALE = 1.5;
private readonly AUDIOBOOK_TITLE_BAR_HEIGHT = 31;
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute)) ?? 0;
private readonly gridBooks = this.books;
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute, 'grid')) ?? 0;
private readonly desktopBaseCardWidth = computed(() =>
this.isAudiobookOnlyLibrary()
? this.DESKTOP_CARD_BASE_WIDTH * 1.1
@@ -309,30 +311,57 @@ export class BookBrowserComponent implements AfterViewInit {
: Math.round(this.desktopBaseCardWidth() * this.coverScalePreferenceService.scaleFactor())
);
private readonly virtualGridGap = computed(() => this.isMobile() ? this.MOBILE_GAP : this.GRID_GAP);
private readonly virtualGridColumns = computed(() => this.isMobile() ? this.mobileColumnCount() : undefined);
private readonly virtualBookCount = computed(() => {
const renderedBookCount = this.gridBooks().length;
return this.appBooksApi.hasNextPage()
? Math.max(this.appBooksApi.totalElements(), renderedBookCount)
: renderedBookCount;
});
private readonly virtualGridColumns = computed(() => this.isMobile() ? this.gridMobileColumnCount() : undefined);
readonly virtualRowCount = computed(() => this.bookCountIncludingUnloadedPages(this.books().length));
private readonly hasUnloadedBooks = computed(() => this.books().length < this.virtualRowCount());
readonly loadedBookCount = computed(() => this.appBooksApi.books().length);
readonly virtualGrid = createVirtualGrid({
items: this.gridBooks,
items: this.books,
scrollElement: this.scrollElement,
minItemWidth: this.minCardWidth,
gap: this.virtualGridGap,
columns: this.virtualGridColumns,
count: this.virtualBookCount,
count: this.virtualRowCount,
initialOffset: this.initialScrollOffset,
fillItemWidth: true,
estimateItemHeight: itemWidth => this.isMobile()
? this.mobileCardSizeForWidth(itemWidth).height
: this.cardSizeForWidth(itemWidth).height,
});
readonly bookQueryToken = computed(() => ({
entity: this.entityInfo(),
search: this.debouncedSearchTerm(),
filter: this.selectedFilter(),
filterMode: this.selectedFilterMode(),
sort: this.sortCriteria(),
}));
private gridLastLoadRequestLoadedBookCount: number | undefined;
private gridLastSeenQueryToken: unknown;
private readonly gridPaginatorEffect = effect(() => {
if (this.currentViewMode() !== VIEW_MODES.GRID) return;
const queryToken = this.bookQueryToken();
if (queryToken !== this.gridLastSeenQueryToken) {
this.gridLastLoadRequestLoadedBookCount = undefined;
this.gridLastSeenQueryToken = queryToken;
}
const items = this.books();
const loadedBookCount = this.loadedBookCount();
const lastVirtualItem = this.virtualGrid.virtualizer.getVirtualItems().at(-1);
if (!lastVirtualItem || items.length === 0) return;
if (lastVirtualItem.index < items.length - 1) return;
if (!this.hasUnloadedBooks() || this.appBooksApi.isFetchingNextPage()) return;
if (this.gridLastLoadRequestLoadedBookCount === loadedBookCount) {
this.gridLastLoadRequestLoadedBookCount = undefined;
return;
}
this.gridLastLoadRequestLoadedBookCount = loadedBookCount;
this.appBooksApi.fetchNextPage();
});
readonly isFetchingNextBooksPage = this.appBooksApi.isFetchingNextPage;
skeletonSlots = Array.from({length: 24}, (_, index) => index);
readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index);
readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
parsedFilters: Record<string, string[]> = {};
dynamicDialogRef: DynamicDialogRef | undefined | null;
EntityType = EntityType;
@@ -436,24 +465,6 @@ export class BookBrowserComponent implements AfterViewInit {
);
});
private readonly fetchNextPageEffect = effect(() => {
if (this.currentViewMode() !== VIEW_MODES.GRID) return;
const virtualItems = this.virtualGrid.virtualizer.getVirtualItems();
const loadedBookCount = this.gridBooks().length;
const lastItem = virtualItems.at(-1);
if (
lastItem &&
loadedBookCount > 0 &&
lastItem.index >= loadedBookCount - 1 &&
this.appBooksApi.hasNextPage() &&
!this.appBooksApi.isFetchingNextPage()
) {
this.appBooksApi.fetchNextPage();
}
});
private readonly bookTableComponent = viewChild(BookTableComponent);
private readonly bookFilterComponent = viewChild(BookFilterComponent);
@@ -464,30 +475,6 @@ export class BookBrowserComponent implements AfterViewInit {
readonly isMobile = computed(() => this.screenWidth() < this.MOBILE_BREAKPOINT);
readonly mobileCardSize = computed(() => {
const columns = this.mobileColumnCount();
const totalGaps = (columns - 1) * this.MOBILE_GAP;
const availableWidth = this.screenWidth() - totalGaps - this.MOBILE_PADDING;
const cardWidth = Math.floor(availableWidth / columns);
const coverHeight = this.isAudiobookOnlyLibrary() ? cardWidth : Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
const cardHeight = coverHeight + this.MOBILE_TITLE_BAR_HEIGHT;
return {width: cardWidth, height: cardHeight};
});
readonly currentCardSize = computed<{width: number; height: number}>(() => {
if (this.isMobile()) {
const width = this.virtualGrid.viewportWidth() > 0
? this.virtualGrid.itemWidth()
: this.mobileCardSize().width;
return this.mobileCardSizeForWidth(width);
}
return this.cardSizeForWidth(this.virtualGrid.itemWidth());
});
readonly skeletonMinCardWidth = computed(() =>
`${this.isMobile() ? this.mobileCardSize().width : this.minCardWidth()}px`
);
private cardSizeForWidth(width: number): { width: number; height: number } {
const cardWidth = Math.round(width);
if (this.isAudiobookOnlyLibrary()) {
@@ -515,9 +502,18 @@ export class BookBrowserComponent implements AfterViewInit {
this.showBooksLoadingPlaceholder() && this.currentViewMode() === VIEW_MODES.TABLE
);
readonly showGridLoadingPlaceholder = computed(() =>
this.showBooksLoadingPlaceholder() && this.currentViewMode() === VIEW_MODES.GRID
);
private bookCountIncludingUnloadedPages(renderedBookCount: number): number {
if (this.showBooksLoadingPlaceholder()) {
return INITIAL_LOADING_ROW_COUNT;
}
if (!this.appBooksApi.hasNextPage()) {
return renderedBookCount;
}
if (!this.seriesCollapsed() || this.forceExpandSeries()) {
return Math.max(this.appBooksApi.totalElements(), renderedBookCount);
}
return renderedBookCount + 1;
}
readonly viewIcon = computed(() =>
this.currentViewMode() === VIEW_MODES.TABLE ? 'pi pi-table' : 'pi pi-objects-column'
@@ -581,6 +577,7 @@ export class BookBrowserComponent implements AfterViewInit {
scrollElement.scrollTop = 0;
}
this.bookTableComponent()?.scrollToTop();
this.virtualGrid.virtualizer.scrollToOffset(0);
}
private readonly syncMetadataMenuEffect = effect(() => {
@@ -696,10 +693,7 @@ export class BookBrowserComponent implements AfterViewInit {
}
onVisibleColumnsChange(selected: { field: string; header: string }[]): void {
const bookTableComponent = this.bookTableComponent();
if (!bookTableComponent) return;
const allFields = bookTableComponent.allColumns.map(col => col.field);
const allFields = this.columnPreferenceService.allColumns.map(column => column.field);
this.visibleColumns.set(selected.sort(
(a, b) => allFields.indexOf(a.field) - allFields.indexOf(b.field)
));
@@ -713,10 +707,6 @@ export class BookBrowserComponent implements AfterViewInit {
this.bookSelectionService.handleBookSelection(book, selected);
}
onSelectedBooksChange(selectedBookIds: Set<number>): void {
this.bookSelectionService.setSelectedBooks(selectedBookIds);
}
selectAllBooks(): void {
this.appBooksApi.fetchAllBookIds().pipe(take(1)).subscribe({
next: (allIds) => {
@@ -728,9 +718,14 @@ export class BookBrowserComponent implements AfterViewInit {
});
}
loadNextBooksPage(): void {
if (this.appBooksApi.hasNextPage() && !this.appBooksApi.isFetchingNextPage()) {
this.appBooksApi.fetchNextPage();
}
}
deselectAllBooks(): void {
this.bookSelectionService.deselectAll();
this.bookTableComponent()?.clearSelectedBooks();
}
confirmDeleteBooks(): void {
@@ -1109,8 +1104,8 @@ export class BookBrowserComponent implements AfterViewInit {
}
setMobileColumns(columns: number): void {
this.mobileColumnCount.set(columns);
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
this.gridMobileColumnCount.set(columns);
this.localStorageService.set(MOBILE_COLUMNS_STORAGE_KEY, columns);
}
adjustDesktopGridDensity(direction: 'smaller' | 'larger'): void {
@@ -1132,9 +1127,9 @@ export class BookBrowserComponent implements AfterViewInit {
}
private loadMobileColumnsPreference(): void {
const saved = this.localStorageService.get<number>(this.MOBILE_COLUMNS_STORAGE_KEY);
const saved = this.localStorageService.get<number>(MOBILE_COLUMNS_STORAGE_KEY);
if (saved !== null && [2, 3, 4].includes(saved)) {
this.mobileColumnCount.set(saved);
this.gridMobileColumnCount.set(saved);
}
}
}
@@ -0,0 +1,100 @@
<ng-container *transloco="let t">
@let currentBook = book();
@let currentMetadata = metadata();
@let metadataLocked = isMetadataLocked();
@let lockPending = isLockPending();
@let squareCover = useSquareCover();
@let imageUrl = coverUrl();
@let coverLabel = currentMetadata.title || currentBook.fileName || t('book.table.bookCoverAlt');
@for (cell of cells(); track cell.id; let columnIndex = $index) {
<div
class="book-table-cell"
role="gridcell"
[attr.aria-colindex]="columnIndex + 1"
[ngClass]="cell.className"
[attr.title]="getCellTitle(cell)">
@switch (cell.kind) {
@case ('select') {
<p-checkbox
class="book-table-checkbox"
[binary]="true"
[ngModel]="isSelected()"
(ngModelChange)="onSelectionChange($event)"
[ariaLabel]="currentMetadata.title ? t('book.table.selectBook', {title: currentMetadata.title}) : t('book.table.selectBookFallback')"></p-checkbox>
}
@case ('lock') {
<button
type="button"
class="metadata-lock-button"
[class.metadata-lock-button-locked]="metadataLocked"
[disabled]="lockPending"
[title]="metadataLocked ? t('book.table.locked') : t('book.table.unlocked')"
[attr.aria-label]="metadataLocked ? t('book.table.locked') : t('book.table.unlocked')"
[attr.aria-pressed]="metadataLocked"
[attr.aria-busy]="lockPending"
(click)="metadataLockToggleRequested.emit(currentMetadata)">
<i [class]="lockPending ? 'pi pi-spin pi-spinner' : (metadataLocked ? 'pi pi-lock' : 'pi pi-lock-open')"></i>
</button>
}
@case ('cover') {
<a
cdkOverlayOrigin
#coverOrigin="cdkOverlayOrigin"
[routerLink]="urlHelper.getBookUrl(currentBook)"
class="cover-link"
[attr.aria-label]="coverLabel"
(mouseenter)="showCoverPreview(coverOrigin)"
(mouseleave)="coverPreviewHide.emit(currentBook.id)"
(focusin)="showCoverPreview(coverOrigin)"
(focusout)="coverPreviewHide.emit(currentBook.id)">
@if (imageUrl) {
<img
[attr.src]="imageUrl"
alt=""
class="cover-thumbnail"
[class.square-cover]="squareCover" />
} @else {
<app-cover-placeholder
class="cover-thumbnail"
aria-hidden="true"
[class.square-cover]="squareCover"
[title]="currentMetadata.title ?? ''"
[author]="(currentMetadata.authors ?? []).join(', ')"
size="sm" />
}
</a>
}
@case ('readStatus') {
@if (showReadStatus()) {
<div
class="read-status-indicator"
[ngClass]="readStatusClass()"
[pTooltip]="t('book.table.statusWithPrefix', {status: readStatusTooltip()})"
tooltipPosition="top">
<i [class]="readStatusIcon()"></i>
</div>
}
}
@case ('rating') {
<span class="rating-wrapper" [title]="cell.rating === null ? '' : cell.display">
<app-rating
[value]="cell.rating"
[ariaLabel]="cell.rating === null ? t('book.table.noRating') : t('book.table.ratingOutOf', {rating: cell.display, max: 5})" />
@if (cell.rating !== null) {
<span class="rating-value">({{ cell.display }})</span>
}
</span>
}
@case ('clickable') {
@for (item of cell.links; track $index; let isLast = $last) {
<a [routerLink]="item.url" class="cell-link">{{ item.anchor }}</a>@if (!isLast) {<span>, </span>}
}
}
@case ('text') {
{{ cell.value }}
}
}
</div>
}
</ng-container>
@@ -0,0 +1,179 @@
:host {
box-sizing: border-box;
display: grid;
grid-template-columns: var(--book-table-grid-template);
position: absolute;
left: 0;
right: 0;
min-width: 100%;
border-bottom: 1px solid var(--book-table-cell-border-color);
background: var(--book-table-row-background);
color: var(--book-table-row-color);
}
:host(.book-table-row-striped) {
background: var(--book-table-row-striped-background);
}
:host(:hover) {
z-index: 3;
background: var(--book-table-row-hover-background);
color: var(--book-table-row-hover-color);
}
.book-table-cell {
box-sizing: border-box;
display: flex;
align-items: center;
height: inherit;
min-width: 0;
padding: var(--book-table-cell-padding);
border-right: 1px solid var(--book-table-cell-border-color);
overflow: hidden;
color: inherit;
line-height: 1.2;
text-align: start;
}
.book-table-checkbox {
display: inline-flex;
line-height: 0;
vertical-align: top;
}
.metadata-lock-button {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1.5rem;
padding: 0;
border: 0;
border-radius: 5px;
color: var(--book-table-lock-unlocked-color);
background: transparent;
cursor: pointer;
&:hover:not(:disabled) {
background: color-mix(in srgb, var(--book-table-lock-unlocked-color) 16%, transparent);
}
&:disabled {
cursor: default;
opacity: 0.65;
}
&.metadata-lock-button-locked {
color: var(--book-table-lock-locked-color);
&:hover:not(:disabled) {
background: color-mix(in srgb, var(--book-table-lock-locked-color) 16%, transparent);
}
}
}
.cover-link {
position: relative;
display: inline-flex;
align-items: center;
}
.cover-thumbnail {
height: 2rem;
aspect-ratio: 5 / 7;
object-fit: cover;
border-radius: 4px;
&.square-cover {
aspect-ratio: 1 / 1;
}
}
.read-status-indicator {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
margin: 0 auto;
font-size: 0.875rem;
font-weight: 700;
}
.status-read {
color: var(--book-table-status-read-color);
}
.status-reading {
color: var(--book-table-status-reading-color);
}
.status-re-reading {
color: var(--book-table-status-re-reading-color);
}
.status-partially-read {
color: var(--book-table-status-partially-read-color);
}
.status-paused {
color: var(--book-table-status-paused-color);
}
.status-abandoned {
color: var(--book-table-status-abandoned-color);
}
.status-wont-read {
color: var(--book-table-status-wont-read-color);
}
.cell-status,
.cell-number {
justify-content: center;
text-align: center;
}
.cell-rating {
justify-content: flex-start;
text-align: start;
}
.cell-action,
.cell-cover {
justify-content: center;
padding-inline: 0.5rem;
}
.cell-cover {
overflow: visible;
}
.cell-text {
white-space: nowrap;
text-overflow: ellipsis;
}
.rating-wrapper {
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--book-table-rating-gap);
min-width: 7rem;
}
.rating-value {
color: inherit;
font-variant-numeric: tabular-nums;
}
.cell-link {
overflow: hidden;
color: var(--p-primary-color);
text-overflow: ellipsis;
white-space: nowrap;
&:hover {
text-decoration: underline;
}
}
@@ -0,0 +1,128 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {provideRouter} from '@angular/router';
import {beforeEach, describe, expect, it} from 'vitest';
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {Book, ReadStatus} from '../../../model/book.model';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {BookTableRowComponent} from './book-table-row.component';
function makeBook(id: number, title: string): Book {
return {
id,
libraryId: 1,
libraryName: 'Library',
metadata: {
bookId: id,
title,
authors: ['Test Author'],
categories: ['Fantasy'],
amazonRating: 4.2,
allMetadataLocked: false,
},
readStatus: ReadStatus.READING,
fileSizeKb: 1536,
primaryFile: {
id: id * 10,
bookId: id,
bookType: 'EPUB',
fileName: `${title}.epub`,
},
};
}
describe('BookTableRowComponent', () => {
let fixture: ComponentFixture<BookTableRowComponent>;
let component: BookTableRowComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [BookTableRowComponent, getTranslocoModule()],
providers: [
provideRouter([]),
{
provide: UrlHelperService,
useValue: {
getBookUrl: (book: Book) => `/book/${book.id}`,
filterBooksBy: (filterKey: string, filterValue: string) => `/all-books?filter=${filterKey}:${filterValue}`,
getThumbnailUrl: () => null,
getAudiobookThumbnailUrl: () => null,
},
},
{
provide: ReadStatusHelper,
useValue: {
getReadStatusIcon: () => 'pi pi-book',
getReadStatusClass: () => 'status-reading',
getReadStatusTooltip: () => 'Reading',
shouldShowStatusIcon: () => true,
},
},
],
});
fixture = TestBed.createComponent(BookTableRowComponent);
component = fixture.componentInstance;
fixture.componentRef.setInput('rowIndex', 0);
fixture.componentRef.setInput('rowHeight', 46);
fixture.componentRef.setInput('rowStart', 0);
fixture.componentRef.setInput('isSelected', false);
fixture.componentRef.setInput('useSquareCovers', false);
});
it('renders visible book fields as table cells', () => {
fixture.componentRef.setInput('book', makeBook(1, 'Alpha'));
fixture.componentRef.setInput('cellIds', ['title', 'authors', 'amazonRating', 'fileSizeKb']);
fixture.detectChanges();
const host = fixture.nativeElement as HTMLElement;
const cells = host.querySelectorAll<HTMLElement>('.book-table-cell');
const links = host.querySelectorAll<HTMLAnchorElement>('.cell-link');
const rating = host.querySelector<HTMLElement>('.rating-wrapper');
expect(cells).toHaveLength(4);
expect(links[0]?.textContent?.trim()).toBe('Alpha');
expect(links[0]?.getAttribute('href')).toBe('/book/1');
expect(links[1]?.textContent?.trim()).toBe('Test Author');
expect(rating?.textContent).toContain('(4.2)');
expect(cells[3]?.textContent?.trim()).toBe('1.5 MB');
});
it('labels icon actions and cover links for assistive tech', () => {
fixture.componentRef.setInput('book', makeBook(1, 'Alpha'));
fixture.componentRef.setInput('cellIds', ['lock', 'cover', 'readStatus']);
fixture.detectChanges();
const host = fixture.nativeElement as HTMLElement;
const lockButton = host.querySelector<HTMLButtonElement>('.metadata-lock-button');
const coverLink = host.querySelector<HTMLAnchorElement>('.cover-link');
const placeholder = host.querySelector<HTMLElement>('app-cover-placeholder');
expect(lockButton?.getAttribute('aria-label')).toBe('Unlocked');
expect(lockButton?.getAttribute('aria-pressed')).toBe('false');
expect(coverLink?.getAttribute('aria-label')).toBe('Alpha');
expect(placeholder?.getAttribute('aria-hidden')).toBe('true');
});
it('formats file sizes with the matching unit', () => {
fixture.componentRef.setInput('cellIds', ['fileSizeKb']);
fixture.componentRef.setInput('book', {...makeBook(1, 'Alpha'), fileSizeKb: 512});
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).textContent).toContain('512 KB');
fixture.componentRef.setInput('book', {...makeBook(1, 'Alpha'), fileSizeKb: 2 * 1024 * 1024});
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).textContent).toContain('2.0 GB');
});
it('uses empty metadata for books without metadata instead of treating them as loading', () => {
fixture.componentRef.setInput('book', {...makeBook(1, 'Alpha'), metadata: undefined});
fixture.componentRef.setInput('cellIds', ['title']);
fixture.detectChanges();
expect(component.metadata().bookId).toBe(1);
expect(component.cells()[0]).toEqual(expect.objectContaining({id: 'title', kind: 'clickable', title: ''}));
});
});
@@ -0,0 +1,327 @@
import {ChangeDetectionStrategy, Component, computed, inject, input, output} from '@angular/core';
import {CdkOverlayOrigin} from '@angular/cdk/overlay';
import {DatePipe, NgClass} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {RouterLink, UrlTree} from '@angular/router';
import {TranslocoDirective} from '@jsverse/transloco';
import {Checkbox} from 'primeng/checkbox';
import {Tooltip} from 'primeng/tooltip';
import {Book, BookMetadata} from '../../../model/book.model';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {RatingComponent} from '../../../../../shared/components/rating/rating.component';
import {RATING_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
interface BookTableCellLink {
url: string | UrlTree;
anchor?: string | number | null;
}
interface BookTableBaseCellView {
id: string;
className: string;
}
interface BookTableActionCellView extends BookTableBaseCellView {
kind: 'select' | 'lock' | 'cover';
}
interface BookTableReadStatusCellView extends BookTableBaseCellView {
kind: 'readStatus';
label: string;
}
interface BookTableRatingCellView extends BookTableBaseCellView {
kind: 'rating';
rating: number | null;
display: string;
}
interface BookTableClickableCellView extends BookTableBaseCellView {
kind: 'clickable';
links: BookTableCellLink[];
title: string | number;
}
interface BookTableTextCellView extends BookTableBaseCellView {
kind: 'text';
value: string | number;
}
type BookTableCellView =
| BookTableActionCellView
| BookTableReadStatusCellView
| BookTableRatingCellView
| BookTableClickableCellView
| BookTableTextCellView;
type BookTableCellKind = BookTableCellView['kind'];
export interface BookTableRowCoverPreview {
book: Book;
metadata: BookMetadata;
origin: CdkOverlayOrigin;
coverUrl: string | null;
useSquareCover: boolean;
}
export interface BookTableSelectionChange {
book: Book;
checked: boolean;
}
const CLICKABLE_FIELDS = new Set(['title', 'authors', 'publisher', 'seriesName', 'categories', 'language']);
const CLICKABLE_FILTER_KEYS: Record<string, string> = {
authors: 'author',
publisher: 'publisher',
categories: 'category',
language: 'language',
};
@Component({
selector: 'app-book-table-row',
standalone: true,
templateUrl: './book-table-row.component.html',
styleUrls: ['./book-table-row.component.scss'],
imports: [
CdkOverlayOrigin,
Checkbox,
CoverPlaceholderComponent,
FormsModule,
NgClass,
RatingComponent,
RouterLink,
Tooltip,
TranslocoDirective,
],
providers: [DatePipe],
host: {
role: 'row',
'[attr.aria-rowindex]': 'rowIndex() + 2',
'[attr.aria-selected]': 'isSelected()',
'[class.book-table-row-striped]': 'rowIndex() % 2 === 0',
'[style.height.px]': 'rowHeight()',
'[style.transform]': '"translateY(" + rowStart() + "px)"',
},
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BookTableRowComponent {
readonly book = input.required<Book>();
readonly cellIds = input.required<string[]>();
readonly rowIndex = input.required<number>();
readonly rowHeight = input.required<number>();
readonly rowStart = input.required<number>();
readonly isSelected = input(false);
readonly isLockPending = input(false);
readonly useSquareCovers = input(false);
readonly selectionChange = output<BookTableSelectionChange>();
readonly metadataLockToggleRequested = output<BookMetadata>();
readonly coverPreviewShow = output<BookTableRowCoverPreview>();
readonly coverPreviewHide = output<number>();
private readonly datePipe = inject(DatePipe);
private readonly readStatusHelper = inject(ReadStatusHelper);
protected readonly urlHelper = inject(UrlHelperService);
readonly metadata = computed<BookMetadata>(() => {
const book = this.book();
return book.metadata ?? {bookId: book.id};
});
readonly useSquareCover = computed(() => this.isAudiobook() || this.useSquareCovers());
readonly coverUrl = computed(() => {
const book = this.book();
const metadata = this.metadata();
return this.useSquareCover()
? this.urlHelper.getAudiobookThumbnailUrl(book.id, metadata.audiobookCoverUpdatedOn)
: this.urlHelper.getThumbnailUrl(book.id, metadata.coverUpdatedOn);
});
readonly readStatusClass = computed(() => this.readStatusHelper.getReadStatusClass(this.book().readStatus));
readonly readStatusIcon = computed(() => this.readStatusHelper.getReadStatusIcon(this.book().readStatus));
readonly readStatusTooltip = computed(() => this.readStatusHelper.getReadStatusTooltip(this.book().readStatus));
readonly showReadStatus = computed(() => this.readStatusHelper.shouldShowStatusIcon(this.book().readStatus));
readonly isMetadataLocked = computed(() => isMetadataFullyLocked(this.metadata()));
readonly cells = computed(() => this.cellIds().map(field => this.createCellView(field)));
onSelectionChange(checked: boolean): void {
this.selectionChange.emit({book: this.book(), checked});
}
showCoverPreview(origin: CdkOverlayOrigin): void {
this.coverPreviewShow.emit({
book: this.book(),
metadata: this.metadata(),
origin,
coverUrl: this.coverUrl(),
useSquareCover: this.useSquareCover(),
});
}
private createCellView(field: string): BookTableCellView {
const metadata = this.metadata();
const book = this.book();
const kind = this.getCellKind(field);
const cell = {
id: field,
className: this.getCellClass(field),
};
switch (kind) {
case 'select':
case 'lock':
case 'cover':
return {...cell, kind};
case 'readStatus':
return {...cell, kind, label: this.readStatusHelper.getReadStatusTooltip(book.readStatus)};
case 'rating': {
const rating = this.getRatingValue(metadata, field);
return {...cell, kind, rating, display: rating === null ? '' : rating.toFixed(1)};
}
case 'clickable':
return {...cell, kind, links: this.getCellClickableValue(metadata, book, field), title: this.getCellValue(metadata, book, field)};
case 'text':
return {...cell, kind, value: this.getCellValue(metadata, book, field)};
}
}
getCellTitle(cell: BookTableCellView): string | number | null {
switch (cell.kind) {
case 'readStatus':
return cell.label;
case 'clickable':
return cell.title;
case 'text':
return cell.value;
default:
return null;
}
}
private getCellKind(field: string): BookTableCellKind {
if (field === 'select') return 'select';
if (field === 'lock') return 'lock';
if (field === 'cover') return 'cover';
if (field === 'readStatus') return 'readStatus';
if (RATING_FIELDS.has(field)) return 'rating';
if (CLICKABLE_FIELDS.has(field)) return 'clickable';
return 'text';
}
private getCellClass(field: string): string {
if (field === 'select' || field === 'lock') return 'cell-action';
if (field === 'cover') return 'cell-cover';
if (field === 'readStatus') return 'cell-status';
if (RATING_FIELDS.has(field)) return 'cell-rating';
if (field.endsWith('ReviewCount') || field === 'pageCount' || field === 'seriesNumber') return 'cell-number';
return 'cell-text';
}
private getCellClickableValue(metadata: BookMetadata, book: Book, field: string): BookTableCellLink[] {
let values: string[];
switch (field) {
case 'title':
return [{
url: this.urlHelper.getBookUrl(book),
anchor: metadata.title ?? book.fileName
}];
case 'categories':
values = metadata.categories ?? [];
break;
case 'authors':
values = metadata.authors ?? [];
break;
case 'seriesName': {
const seriesName = metadata.seriesName;
if (!seriesName) return [];
return [{
url: this.urlHelper.filterBooksBy('series', seriesName),
anchor: seriesName
}];
}
default: {
const value = this.getMetadataValue(metadata, field);
values = typeof value === 'string' && value ? [value] : [];
}
}
return values.map(item => ({
url: this.urlHelper.filterBooksBy(CLICKABLE_FILTER_KEYS[field] ?? field, item),
anchor: item
}));
}
private getCellValue(metadata: BookMetadata, book: Book, field: string): string | number {
switch (field) {
case 'title':
return metadata.title ?? '';
case 'authors':
return this.getAuthorNames(metadata.authors);
case 'publisher':
return metadata.publisher ?? '';
case 'seriesName':
return metadata.seriesName ?? '';
case 'seriesNumber':
return metadata.seriesNumber ?? '';
case 'categories':
return this.getGenres(metadata.categories);
case 'publishedDate':
return metadata.publishedDate ? this.datePipe.transform(metadata.publishedDate, 'dd-MMM-yyyy') ?? '' : '';
case 'lastReadTime':
return book.lastReadTime ? this.datePipe.transform(book.lastReadTime, 'dd-MMM-yyyy') ?? '' : '';
case 'addedOn':
return book.addedOn ? this.datePipe.transform(book.addedOn, 'dd-MMM-yyyy') ?? '' : '';
case 'fileName':
return book.primaryFile?.fileName ?? '';
case 'fileSizeKb':
return this.formatFileSize(book.fileSizeKb);
case 'language':
return metadata.language ?? '';
case 'pageCount':
return metadata.pageCount ?? '';
case 'amazonReviewCount':
case 'goodreadsReviewCount':
case 'hardcoverReviewCount':
return metadata[field] ?? '';
case 'isbn':
return metadata.isbn13 ?? metadata.isbn10 ?? '';
default:
return '';
}
}
private getAuthorNames(authors?: string[] | null): string {
return authors?.join(', ') || '';
}
private getGenres(genres?: string[] | null): string {
return genres?.join(', ') || '';
}
private formatFileSize(kb?: number): string {
if (kb == null || Number.isNaN(kb)) return '-';
if (kb < 1024) {
return `${Number.isInteger(kb) ? kb.toFixed(0) : kb.toFixed(1)} KB`;
}
if (kb < 1024 * 1024) {
return `${(kb / 1024).toFixed(1)} MB`;
}
return `${(kb / (1024 * 1024)).toFixed(1)} GB`;
}
private getRatingValue(metadata: BookMetadata, field: string): number | null {
const rating = this.getMetadataValue(metadata, field);
return typeof rating === 'number' ? rating : null;
}
private getMetadataValue(metadata: BookMetadata, field: string): unknown {
return this.isKeyOf(metadata, field) ? metadata[field] : undefined;
}
private isKeyOf<T extends object>(value: T, field: PropertyKey): field is keyof T {
return Object.prototype.hasOwnProperty.call(value, field);
}
private isAudiobook(): boolean {
return this.book().primaryFile?.bookType === 'AUDIOBOOK';
}
}
@@ -1,128 +1,113 @@
<ng-container *transloco="let t; prefix: 'book.table'">
<p-table
[value]="books"
[columns]="visibleColumns"
[dataKey]="'id'"
[resizableColumns]="true"
[reorderableColumns]="true"
columnResizeMode="expand"
[rowTrackBy]="trackByBookId"
[metaKeySelection]="true"
showGridlines
stripedRows
[scrollable]="true"
[scrollHeight]="scrollHeight"
[virtualScroll]="true"
[virtualScrollItemSize]="46"
[(selection)]="selectedBooks"
(onHeaderCheckboxToggle)="onHeaderCheckboxToggle($event)"
(onRowSelect)="onRowSelect($event)"
(onRowUnselect)="onRowUnselect($event)"
>
<ng-template pTemplate="header">
<tr>
<th>
<p-tableHeaderCheckbox/>
</th>
<th></th>
<th class="cover-header-cell"></th>
@for (col of visibleColumns; track col.field) {
<th pResizableColumn>{{ col.header }}</th>
}
</tr>
</ng-template>
<ng-template pTemplate="body" let-book>
@if (book.metadata; as metadata) {
<tr style="height:46px">
<td>
<p-tableCheckbox [value]="book"/>
</td>
<td class="cell-center">
<p-button
[icon]="isMetadataFullyLocked(metadata) ? 'pi pi-lock' : 'pi pi-lock-open'"
[severity]="isMetadataFullyLocked(metadata) ? 'danger' : 'success'"
[text]="true"
[title]="isMetadataFullyLocked(metadata) ? t('locked') : t('unlocked')"
size="small"
[style]="{ width: '1.5rem', height: '1.5rem', padding: '0', fontSize: '0.75rem' }"
(click)="toggleMetadataLock(metadata)">
</p-button>
</td>
<td>
<a [routerLink]="urlHelper.getBookUrl(book)">
@if (urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn); as coverUrl) {
<img
[attr.src]="coverUrl"
[alt]="t('bookCoverAlt')"
class="cover-thumbnail"
tooltipPosition="left"
[pTooltip]="tooltipContent"
tooltipStyleClass="cover-tooltip"
/>
} @else {
<app-cover-placeholder class="cover-thumbnail" [title]="metadata.title ?? ''" [author]="(metadata.authors ?? []).join(', ')" size="sm" />
}
</a>
<ng-template #tooltipContent>
<div class="tooltip-cover-container">
@if (urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn); as coverUrl) {
<img
[attr.src]="coverUrl"
[alt]="t('bookCoverAlt')"
class="tooltip-cover-image"
/>
<ng-container *transloco="let t">
<div
#scrollElement
class="book-table-scroll p-datatable p-component p-datatable-scrollable p-datatable-striped p-datatable-gridlines p-datatable-resizable"
role="grid"
(scroll)="clearCoverPreview()"
(wheel)="clearCoverPreview()"
[attr.aria-label]="t('book.table.label')"
[attr.aria-rowcount]="ariaRowCount()"
[attr.aria-colcount]="ariaColumnCount()">
<div class="book-table p-datatable-table p-datatable-scrollable-table p-datatable-resizable-table" [style]="columnSizeVars()" [style.width.px]="tableWidth()">
@for (headerGroup of table.getHeaderGroups(); track headerGroup.id) {
<div class="book-table-header-row" role="row" aria-rowindex="1">
@for (header of headerGroup.headers; track header.id; let columnIndex = $index) {
<div
class="book-table-header-cell p-datatable-header-cell p-datatable-resizable-column"
role="columnheader"
[attr.aria-colindex]="columnIndex + 1"
[class.cell-action]="header.column.id === 'select' || header.column.id === 'lock'"
[class.cell-cover]="header.column.id === 'cover'">
@if (header.column.id === 'select') {
<p-checkbox
class="book-table-checkbox"
[binary]="true"
[ngModel]="allLoadedBooksSelected()"
[indeterminate]="someBooksSelected()"
(ngModelChange)="onHeaderCheckboxChange($event)"
[ariaLabel]="t('book.browser.tooltip.selectAll')"></p-checkbox>
} @else {
<app-cover-placeholder class="tooltip-cover-image" [title]="metadata.title ?? ''" [author]="(metadata.authors ?? []).join(', ')" />
<span class="p-datatable-column-title">{{ header.column.columnDef.header }}</span>
}
<em class="tooltip-cover-title">{{ metadata.title }}</em>
</div>
</ng-template>
</td>
@for (col of visibleColumns; track col.field) {
@if (col.field === 'readStatus') {
<td class="cell-status">
@if (shouldShowStatusIcon(book.readStatus)) {
<div class="read-status-indicator"
[ngClass]="getReadStatusClass(book.readStatus)"
[pTooltip]="t('statusPrefix') + getReadStatusTooltip(book.readStatus)"
tooltipPosition="top">
<i [class]="getReadStatusIcon(book.readStatus)"></i>
@if (header.column.getCanResize()) {
<span
class="column-resizer p-datatable-column-resizer"
(mousedown)="startColumnResize(header, $event)"
(touchstart)="startColumnResize(header, $event)"
aria-hidden="true"></span>
}
</div>
}
</div>
}
<div class="book-table-body" [style.height.px]="rowVirtualizer.getTotalSize()">
@for (virtualRow of rowVirtualizer.getVirtualItems(); track virtualRow.key) {
@if (books()[virtualRow.index]; as book) {
<app-book-table-row
[book]="book"
[cellIds]="visibleCellIds()"
[rowIndex]="virtualRow.index"
[rowHeight]="virtualRow.size"
[rowStart]="virtualRow.start"
[isSelected]="isRowSelected(book)"
[isLockPending]="isMetadataLockPending(book.id)"
[useSquareCovers]="useSquareCovers()"
(selectionChange)="onBookSelectionChange($event)"
(metadataLockToggleRequested)="toggleMetadataLock($event)"
(coverPreviewShow)="showCoverPreview($event)"
(coverPreviewHide)="hideCoverPreview($event)" />
} @else {
<div
class="book-table-row book-table-row-loading"
role="row"
aria-busy="true"
[attr.aria-rowindex]="virtualRow.index + 2"
[class.book-table-row-striped]="virtualRow.index % 2 === 0"
[style.height.px]="virtualRow.size"
[style.transform]="'translateY(' + virtualRow.start + 'px)'">
@for (columnId of visibleCellIds(); track columnId; let columnIndex = $index) {
<div
class="book-table-cell"
role="gridcell"
[attr.aria-colindex]="columnIndex + 1"
[class.cell-action]="columnId === 'select' || columnId === 'lock'"
[class.cell-cover]="columnId === 'cover'">
<span class="loading-line" [class.loading-line-short]="columnId !== 'title'"></span>
</div>
}
</td>
} @else if (col.field === 'amazonRating' || col.field === 'goodreadsRating' || col.field === 'hardcoverRating' || col.field === 'ranobedbRating') {
<td class="cell-rating">
<span class="rating-wrapper">
<p-rating
[(ngModel)]="metadata[col.field]"
readonly
stars="5"
[style.--p-rating-icon-active-color]="getStarColor(metadata[col.field])"
></p-rating>
@if (metadata[col.field] !== null && metadata[col.field] !== undefined) {
<span>({{ metadata[col.field]?.toFixed(1) }})</span>
}
</span>
</td>
} @else {
<td
[title]="getCellValue(metadata, book, col.field)"
class="cell-text">
@if(['title', 'authors', 'publisher', 'seriesName', 'categories', 'language'].includes(col.field)) {
@for (item of getCellClickableValue(metadata, book, col.field); track $index; let isLast = $last) {
<a [routerLink]="item.url" class="cell-link">
{{ item.anchor }}</a>@if (!isLast) {<span>, </span>}
}
} @else {
{{ getCellValue(metadata, book, col.field) }}
}
</td>
</div>
}
}
</tr>
}
</ng-template>
</p-table>
</div>
</div>
</div>
@if (coverPreview(); as preview) {
<ng-template
cdkConnectedOverlay
[cdkConnectedOverlayOrigin]="preview.origin"
[cdkConnectedOverlayOpen]="true"
[cdkConnectedOverlayPositions]="coverOverlayPositions"
[cdkConnectedOverlayViewportMargin]="8"
[cdkConnectedOverlayPush]="true"
[cdkConnectedOverlayFlexibleDimensions]="true">
<div class="cover-preview">
@if (preview.coverUrl; as coverUrl) {
<img
[attr.src]="coverUrl"
[alt]="t('book.table.bookCoverAlt')"
class="cover-preview-image"
[class.square-cover]="preview.useSquareCover" />
} @else {
<app-cover-placeholder
class="cover-preview-image"
[class.square-cover]="preview.useSquareCover"
[title]="preview.metadata.title ?? ''"
[author]="(preview.metadata.authors ?? []).join(', ')" />
}
</div>
</ng-template>
}
</ng-container>
@@ -1,110 +1,192 @@
.read-status-indicator {
display: flex;
align-items: center;
justify-content: center;
font-size: 0.875rem;
font-weight: bold;
width: 20px;
height: 20px;
margin: 0 auto;
:host {
display: block;
min-height: 0;
--book-table-border-color: var(--p-datatable-border-color, color-mix(in srgb, var(--p-content-border-color) 82%, black));
--book-table-header-background: var(--p-datatable-header-cell-background, var(--p-content-background));
--book-table-header-color: var(--p-datatable-header-cell-color, var(--p-text-color));
--book-table-header-padding: var(--p-datatable-header-cell-padding, 0.75rem 1rem);
--book-table-header-weight: var(--p-datatable-column-title-font-weight, 600);
--book-table-row-background: var(--p-datatable-row-background, var(--p-content-background));
--book-table-row-color: var(--p-datatable-row-color, var(--p-text-color));
--book-table-row-hover-background: var(--p-datatable-row-hover-background, var(--p-content-hover-background));
--book-table-row-hover-color: var(--p-datatable-row-hover-color, var(--p-text-color));
--book-table-row-striped-background: var(--p-datatable-row-striped-background, var(--p-surface-950));
--book-table-cell-border-color: var(--p-datatable-body-cell-border-color, var(--book-table-border-color));
--book-table-cell-padding: var(--p-datatable-body-cell-padding, 0.75rem 1rem);
--book-table-rating-gap: var(--p-rating-gap, 0.25rem);
--book-table-lock-unlocked-color: var(--color-lock-unlocked, #16a34a);
--book-table-lock-locked-color: var(--color-lock-locked, #dc2626);
--book-table-status-read-color: #22c55e;
--book-table-status-reading-color: #3b82f6;
--book-table-status-re-reading-color: #06b6d4;
--book-table-status-partially-read-color: #f59e0b;
--book-table-status-paused-color: #eab308;
--book-table-status-abandoned-color: #ef4444;
--book-table-status-wont-read-color: #ec4899;
}
.status-read {
color: #22c55e;
}
.book-table-scroll {
box-sizing: border-box;
height: calc(100dvh - 150px);
border: 1px solid var(--book-table-border-color);
overflow: auto;
background: var(--book-table-row-background);
.status-reading {
color: #3b82f6;
}
.status-re-reading {
color: #06b6d4;
}
.status-partially-read {
color: #f59e0b;
}
.status-paused {
color: #eab308;
}
.status-abandoned {
color: #ef4444;
}
.status-wont-read {
color: #ec4899;
}
.cover-header-cell {
max-width: 3.5rem;
min-width: 3.5rem;
}
.cell-center {
text-align: center;
}
.cover-thumbnail {
width: 1.75rem;
height: 1.75rem;
}
.tooltip-cover-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
}
.tooltip-cover-image {
width: 40rem;
aspect-ratio: 5 / 7;
}
.tooltip-cover-title {
font-size: 0.875rem;
text-wrap: balance;
text-align: center;
}
.cell-status {
text-align: center;
min-width: 4rem;
max-width: 4rem;
}
.cell-rating {
min-width: 10rem;
max-width: 10rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rating-wrapper {
display: flex;
align-items: center;
gap: 0.25rem;
}
.cell-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: right;
min-width: 6rem;
max-width: 12rem;
}
.cell-link {
&:hover {
text-decoration: underline;
color: #60a5fa;
@media (width <= 768px) {
height: calc(100dvh - 125px);
}
}
::ng-deep .cover-tooltip > .p-tooltip-text {
padding: 0.25rem;
.book-table {
min-width: 100%;
position: relative;
}
.book-table-header-row,
.book-table-row {
box-sizing: border-box;
display: grid;
grid-template-columns: var(--book-table-grid-template);
min-width: 100%;
}
.book-table-header-row {
position: sticky;
top: 0;
z-index: 20;
min-height: 46px;
background: var(--book-table-header-background);
border-bottom: 1px solid var(--book-table-border-color);
}
.book-table-header-cell,
.book-table-cell {
box-sizing: border-box;
height: inherit;
min-width: 0;
border-right: 1px solid var(--book-table-cell-border-color);
}
.book-table-header-cell {
position: relative;
display: flex;
align-items: center;
padding: var(--book-table-header-padding);
color: var(--book-table-header-color);
font-weight: normal;
text-align: start;
white-space: nowrap;
.p-datatable-column-title {
overflow: hidden;
font-weight: var(--book-table-header-weight);
text-overflow: ellipsis;
}
}
.column-resizer {
position: absolute;
top: 0;
right: -3px;
width: 6px;
height: 100%;
padding: 0;
border: 0;
background: transparent;
cursor: col-resize;
touch-action: none;
}
.book-table-body {
position: relative;
}
.book-table-row {
position: absolute;
left: 0;
right: 0;
border-bottom: 1px solid var(--book-table-cell-border-color);
background: var(--book-table-row-background);
color: var(--book-table-row-color);
}
.book-table-row-striped {
background: var(--book-table-row-striped-background);
}
.book-table-cell {
display: flex;
align-items: center;
padding: var(--book-table-cell-padding);
overflow: hidden;
color: inherit;
line-height: 1.2;
text-align: start;
}
.book-table-checkbox {
display: inline-flex;
line-height: 0;
vertical-align: top;
}
.cover-preview {
width: 14rem;
max-height: calc(100dvh - 2rem);
border-radius: 6px;
box-shadow:
0 18px 48px rgb(0 0 0 / 42%),
0 4px 14px rgb(0 0 0 / 32%);
overflow: hidden;
}
.cover-preview-image {
width: 100%;
max-height: calc(100dvh - 6rem);
aspect-ratio: 5 / 7;
object-fit: cover;
border-radius: inherit;
&.square-cover {
aspect-ratio: 1 / 1;
}
}
.cell-action,
.cell-cover {
justify-content: center;
padding-inline: 0.5rem;
}
.cell-cover {
overflow: visible;
}
.book-table-row-loading {
pointer-events: none;
}
.loading-line {
display: block;
width: 85%;
height: 0.75rem;
border-radius: 999px;
background: color-mix(in srgb, var(--p-text-color) 14%, transparent);
animation: loading-line-pulse 1.5s ease-in-out infinite;
}
.loading-line-short {
width: 48%;
}
@keyframes loading-line-pulse {
0%, 100% { opacity: 0.3; }
50% { opacity: 0.6; }
}
@media (prefers-reduced-motion: reduce) {
.loading-line {
animation: none;
}
}
@@ -1,14 +1,296 @@
import {describe, it} from 'vitest';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {provideRouter} from '@angular/router';
import {of, Subject} from 'rxjs';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {MessageService} from 'primeng/api';
// NOTE(frontend-seam): Real coverage here needs seams around DOM sizing, table selection events,
// router-link rendering, and metadata-lock helpers so table interactions can be asserted without
// mounting the full PrimeNG virtual-table runtime.
describe.skip('BookTableComponent', () => {
it('needs browser seams to verify responsive scroll-height updates and virtual scroller resizing', () => {
// TODO(seam): Cover setScrollHeight and ngOnChanges after window/document globals are isolated behind deterministic adapters.
import {getTranslocoModule} from '../../../../../core/testing/transloco-testing';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {Book, BookMetadata, ReadStatus} from '../../../model/book.model';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {BookSelectionService} from '../book-selection.service';
import {BookTableComponent} from './book-table.component';
import {BookTableRowComponent} from './book-table-row.component';
function makeBook(id: number, title: string): Book & {metadata: BookMetadata} {
return {
id,
libraryId: 1,
libraryName: 'Library',
metadata: {
bookId: id,
title,
authors: ['Test Author'],
categories: ['Fantasy'],
amazonRating: 4.2,
allMetadataLocked: false,
},
readStatus: ReadStatus.READING,
primaryFile: {
id: id * 10,
bookId: id,
bookType: 'EPUB',
fileName: `${title}.epub`,
},
};
}
describe('BookTableComponent', () => {
let fixture: ComponentFixture<BookTableComponent>;
let component: BookTableComponent;
let bookSelectionService: BookSelectionService;
let bookMetadataManageService: { toggleAllLock: ReturnType<typeof vi.fn> };
let queryClient: { setQueriesData: ReturnType<typeof vi.fn> };
beforeEach(() => {
queryClient = {setQueriesData: vi.fn()};
bookMetadataManageService = {
toggleAllLock: vi.fn(() => of(null)),
};
TestBed.configureTestingModule({
imports: [BookTableComponent, getTranslocoModule()],
providers: [
provideRouter([]),
{provide: QueryClient, useValue: queryClient},
{provide: MessageService, useValue: {add: vi.fn()}},
{
provide: UrlHelperService,
useValue: {
getBookUrl: (book: Book) => `/book/${book.id}`,
filterBooksBy: (filterKey: string, filterValue: string) => `/all-books?filter=${filterKey}:${filterValue}`,
getThumbnailUrl: () => null,
getAudiobookThumbnailUrl: () => null,
},
},
{
provide: BookMetadataManageService,
useValue: bookMetadataManageService,
},
{
provide: ReadStatusHelper,
useValue: {
getReadStatusIcon: () => 'pi pi-book',
getReadStatusClass: () => 'status-reading',
getReadStatusTooltip: () => 'Reading',
shouldShowStatusIcon: () => true,
},
},
],
});
fixture = TestBed.createComponent(BookTableComponent);
component = fixture.componentInstance;
bookSelectionService = TestBed.inject(BookSelectionService);
});
it('needs table-event seams to verify row selection, bulk selection, and clickable metadata cell generation', () => {
// TODO(seam): Cover selection methods and getCellClickableValue after the PrimeNG table event surface is extracted into a stable test harness.
afterEach(() => {
TestBed.resetTestingModule();
});
it('renders grid semantics and keeps resize handles out of the tab order', () => {
fixture.componentRef.setInput('books', [makeBook(1, 'Alpha')]);
fixture.componentRef.setInput('visibleColumns', [
{field: 'title', header: 'Title'},
{field: 'amazonRating', header: 'Amazon Rating'},
]);
fixture.detectChanges();
const host = fixture.nativeElement as HTMLElement;
const grid = host.querySelector<HTMLElement>('.book-table-scroll');
const headerCells = host.querySelectorAll<HTMLElement>('.book-table-header-cell');
const resizer = host.querySelector<HTMLElement>('.column-resizer');
expect(grid?.getAttribute('role')).toBe('grid');
expect(grid?.getAttribute('aria-rowcount')).toBe('2');
expect(grid?.getAttribute('aria-colcount')).toBe('5');
expect(headerCells[0]?.getAttribute('role')).toBe('columnheader');
expect(headerCells[0]?.getAttribute('aria-colindex')).toBe('1');
expect(resizer?.tagName).toBe('SPAN');
expect(resizer?.getAttribute('aria-hidden')).toBe('true');
expect(resizer?.hasAttribute('tabindex')).toBe(false);
});
it('does not recreate a rendered row when selection changes', () => {
const book = makeBook(1, 'Alpha');
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
{index: 0, key: 1, start: 0, size: 46, end: 46, lane: 0}
]);
fixture.componentRef.setInput('books', [book]);
fixture.componentRef.setInput('visibleColumns', [
{field: 'title', header: 'Title'},
{field: 'amazonRating', header: 'Amazon Rating'},
]);
fixture.detectChanges();
const initialRowDebugElement = fixture.debugElement.query(By.directive(BookTableRowComponent));
const initialRowInstance = initialRowDebugElement.componentInstance as BookTableRowComponent;
const selectionSpy = vi.spyOn(bookSelectionService, 'handleBookSelection');
const initialRowElement = initialRowDebugElement.nativeElement as HTMLElement;
const checkboxInput = initialRowElement.querySelector<HTMLInputElement>('input[type="checkbox"]');
expect(checkboxInput).toBeTruthy();
checkboxInput!.click();
fixture.detectChanges();
const updatedRowDebugElement = fixture.debugElement.query(By.directive(BookTableRowComponent));
const updatedRowInstance = updatedRowDebugElement.componentInstance as BookTableRowComponent;
expect(updatedRowDebugElement.nativeElement).toBe(initialRowDebugElement.nativeElement);
expect(updatedRowInstance).toBe(initialRowInstance);
expect(selectionSpy).toHaveBeenCalledWith(book, true);
expect(updatedRowInstance.isSelected()).toBe(true);
expect(bookSelectionService.isBookSelected(book)).toBe(true);
expect(component.isRowSelected(book)).toBe(true);
});
it('does not request the next page again after a same-size book refresh', () => {
const loadNextPageSpy = vi.fn();
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
]);
component.loadNextPage.subscribe(loadNextPageSpy);
fixture.componentRef.setInput('books', books);
fixture.componentRef.setInput('virtualRowCount', 100);
fixture.componentRef.setInput('isFetchingNextPage', false);
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
fixture.componentRef.setInput('books', books.map(book => ({
...book,
metadata: {...book.metadata},
})));
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
});
it('can request the next page again after the parent signals a query swap', () => {
const loadNextPageSpy = vi.fn();
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
const nextBooks = Array.from({length: 50}, (_, index) => makeBook(index + 101, `Next Book ${index + 1}`));
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
]);
component.loadNextPage.subscribe(loadNextPageSpy);
const initialQueryToken = {query: 'first'};
fixture.componentRef.setInput('books', books);
fixture.componentRef.setInput('virtualRowCount', 51);
fixture.componentRef.setInput('isFetchingNextPage', false);
fixture.componentRef.setInput('bookQueryToken', initialQueryToken);
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
fixture.componentRef.setInput('books', nextBooks);
fixture.componentRef.setInput('bookQueryToken', {query: 'second'});
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(2);
});
it('re-arms pagination after a next-page request completes without new rows', () => {
const loadNextPageSpy = vi.fn();
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
]);
component.loadNextPage.subscribe(loadNextPageSpy);
fixture.componentRef.setInput('books', books);
fixture.componentRef.setInput('virtualRowCount', 51);
fixture.componentRef.setInput('isFetchingNextPage', false);
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
fixture.componentRef.setInput('isFetchingNextPage', true);
fixture.detectChanges();
fixture.componentRef.setInput('isFetchingNextPage', false);
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
fixture.componentRef.setInput('virtualRowCount', 52);
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(2);
});
it('can request the next page again when loaded books grow but rendered rows do not', () => {
const loadNextPageSpy = vi.fn();
const books = Array.from({length: 50}, (_, index) => makeBook(index + 1, `Book ${index + 1}`));
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
{index: 49, key: 50, start: 2254, size: 46, end: 2300, lane: 0}
]);
component.loadNextPage.subscribe(loadNextPageSpy);
fixture.componentRef.setInput('books', books);
fixture.componentRef.setInput('virtualRowCount', 51);
fixture.componentRef.setInput('loadedBookCount', 50);
fixture.componentRef.setInput('isFetchingNextPage', false);
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(1);
fixture.componentRef.setInput('isFetchingNextPage', true);
fixture.detectChanges();
fixture.componentRef.setInput('loadedBookCount', 60);
fixture.componentRef.setInput('isFetchingNextPage', false);
fixture.detectChanges();
expect(loadNextPageSpy).toHaveBeenCalledTimes(2);
});
it('requests metadata lock without mutating the input book', () => {
const book = makeBook(1, 'Alpha');
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
{index: 0, key: 1, start: 0, size: 46, end: 46, lane: 0}
]);
fixture.componentRef.setInput('books', [book]);
fixture.componentRef.setInput('visibleColumns', [{field: 'title', header: 'Title'}]);
fixture.detectChanges();
component.toggleMetadataLock(book.metadata);
fixture.detectChanges();
expect(book.metadata?.allMetadataLocked).toBe(false);
expect(bookMetadataManageService.toggleAllLock).toHaveBeenCalledWith(new Set([1]), 'LOCK');
expect(queryClient.setQueriesData).toHaveBeenCalledWith({queryKey: ['app-books']}, expect.any(Function));
});
it('disables a row lock button while that book lock request is in flight', () => {
const lockRequest = new Subject<void>();
bookMetadataManageService.toggleAllLock.mockReturnValue(lockRequest.asObservable());
const book = makeBook(1, 'Alpha');
vi.spyOn(component.rowVirtualizer, 'getVirtualItems').mockReturnValue([
{index: 0, key: 1, start: 0, size: 46, end: 46, lane: 0}
]);
fixture.componentRef.setInput('books', [book]);
fixture.componentRef.setInput('visibleColumns', [{field: 'title', header: 'Title'}]);
fixture.detectChanges();
component.toggleMetadataLock(book.metadata);
fixture.detectChanges();
const host = fixture.nativeElement as HTMLElement;
const button = host.querySelector<HTMLButtonElement>('.metadata-lock-button');
expect(button?.disabled).toBe(true);
component.toggleMetadataLock(book.metadata);
expect(bookMetadataManageService.toggleAllLock).toHaveBeenCalledTimes(1);
lockRequest.next();
lockRequest.complete();
fixture.detectChanges();
expect(button?.disabled).toBe(false);
});
});
@@ -1,370 +1,328 @@
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 {ChangeDetectionStrategy, Component, DestroyRef, ElementRef, computed, effect, inject, input, output, signal, viewChild} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {CdkConnectedOverlay, ConnectedPosition} from '@angular/cdk/overlay';
import {FormsModule} from '@angular/forms';
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';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {Button} from 'primeng/button';
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 {UserService} from '../../../../settings/user-management/user.service';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {ActivatedRoute} from '@angular/router';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {finalize} from 'rxjs';
import {ColumnDef, ColumnSizingState, Header, createAngularTable, functionalUpdate, getCoreRowModel} from '@tanstack/angular-table';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {injectVirtualizer} from '@tanstack/angular-virtual';
import {Checkbox} from 'primeng/checkbox';
import {Book, BookMetadata} from '../../../model/book.model';
import {RouteScrollPositionService} from '../../../../../shared/service/route-scroll-position.service';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {patchAppBooksMetadataLockInCache} from '../../../service/book-query-cache';
import {MessageService} from 'primeng/api';
import {BookSelectionService} from '../book-selection.service';
import {BookTableRowComponent, type BookTableRowCoverPreview, type BookTableSelectionChange} from './book-table-row.component';
import {RATING_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
interface BookTableColumn {
field: string;
header: string;
}
const ROW_HEIGHT = 46;
const RENDER_OVERSCAN_ROWS = 16;
const RESIZE_OVERSCAN_ROWS = 2;
const PAGE_LOAD_AHEAD_ROWS = 40;
const DEFAULT_COLUMN_SIZES: Record<string, number> = {
readStatus: 72,
title: 260,
fileName: 240,
authors: 220,
categories: 220,
pageCount: 120,
seriesNumber: 120,
};
const DEFAULT_RATING_COLUMN_SIZE = 148;
const DEFAULT_REVIEW_COUNT_COLUMN_SIZE = 120;
const DEFAULT_TEXT_COLUMN_SIZE = 180;
const MIN_COLUMN_SIZES: Record<string, number> = {
readStatus: 64,
pageCount: 96,
seriesNumber: 96,
};
const DEFAULT_MIN_COLUMN_SIZE = 120;
const MAX_COLUMN_SIZES: Record<string, number> = {
title: 420,
fileName: 420,
authors: 360,
categories: 360,
};
const DEFAULT_MAX_COLUMN_SIZE = 280;
const COVER_OVERLAY_POSITIONS: ConnectedPosition[] = [
{originX: 'end', originY: 'center', overlayX: 'start', overlayY: 'center', offsetX: 8},
{originX: 'start', originY: 'center', overlayX: 'end', overlayY: 'center', offsetX: -8},
{originX: 'end', originY: 'top', overlayX: 'start', overlayY: 'top', offsetX: 8},
{originX: 'end', originY: 'bottom', overlayX: 'start', overlayY: 'bottom', offsetX: 8},
];
@Component({
selector: 'app-book-table',
standalone: true,
templateUrl: './book-table.component.html',
imports: [
TableModule,
Rating,
CdkConnectedOverlay,
BookTableRowComponent,
Checkbox,
FormsModule,
Button,
Tooltip,
NgClass,
RouterLink,
TranslocoDirective,
CoverPlaceholderComponent
],
styleUrls: ['./book-table.component.scss'],
providers: [DatePipe]
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
selectedBooks: Book[] = [];
selectedBookIds = new Set<number>();
export class BookTableComponent {
readonly selectAllRequested = output<void>();
readonly loadNextPage = output<void>();
@Output() selectedBooksChange = new EventEmitter<Set<number>>();
@Output() selectAllRequested = new EventEmitter<void>();
@Input() books: Book[] = [];
@Input() sortOption: SortOption | null = null;
@Input() visibleColumns: { field: string; header: string }[] = [];
@Input() preselectedBookIds = new Set<number>();
readonly books = input<Book[]>([]);
readonly visibleColumns = input<BookTableColumn[]>([]);
readonly virtualRowCount = input(0);
readonly loadedBookCount = input<number | null>(null);
readonly isFetchingNextPage = input(false);
readonly useSquareCovers = input(false);
readonly bookQueryToken = input<unknown>(undefined);
protected urlHelper = inject(UrlHelperService);
private bookService = inject(BookService);
private bookMetadataManageService = inject(BookMetadataManageService);
private messageService = inject(MessageService);
private userService = inject(UserService);
private datePipe = inject(DatePipe);
private readStatusHelper = inject(ReadStatusHelper);
private readonly activatedRoute = inject(ActivatedRoute);
private readonly scrollService = inject(RouteScrollPositionService);
protected readonly bookSelectionService = inject(BookSelectionService);
private readonly bookMetadataManageService = inject(BookMetadataManageService);
private readonly messageService = inject(MessageService);
private readonly queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
private elementRef = inject(ElementRef);
private readonly destroyRef = inject(DestroyRef);
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
private readonly initialScrollOffset = () => this.scrollService.getPosition(this.scrollService.keyFor(this.activatedRoute, 'table')) ?? 0;
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
private resizeListener = this.setScrollHeight.bind(this);
private readonly columnSizing = signal<ColumnSizingState>({});
protected readonly coverPreview = signal<BookTableRowCoverPreview | null>(null);
private readonly pendingLockBookIds = signal<Set<number>>(new Set());
readonly allColumns: { field: string; header: string }[] = [
{field: 'readStatus', header: this.t.translate('book.columnPref.columns.readStatus')},
{field: 'title', header: this.t.translate('book.columnPref.columns.title')},
{field: 'authors', header: this.t.translate('book.columnPref.columns.authors')},
{field: 'publisher', header: this.t.translate('book.columnPref.columns.publisher')},
{field: 'seriesName', header: this.t.translate('book.columnPref.columns.seriesName')},
{field: 'seriesNumber', header: this.t.translate('book.columnPref.columns.seriesNumber')},
{field: 'categories', header: this.t.translate('book.columnPref.columns.categories')},
{field: 'publishedDate', header: this.t.translate('book.columnPref.columns.publishedDate')},
{field: 'lastReadTime', header: this.t.translate('book.columnPref.columns.lastReadTime')},
{field: 'addedOn', header: this.t.translate('book.columnPref.columns.addedOn')},
{field: 'fileName', header: this.t.translate('book.columnPref.columns.fileName')},
{field: 'fileSizeKb', header: this.t.translate('book.columnPref.columns.fileSizeKb')},
{field: 'language', header: this.t.translate('book.columnPref.columns.language')},
{field: 'isbn', header: this.t.translate('book.columnPref.columns.isbn')},
{field: 'pageCount', header: this.t.translate('book.columnPref.columns.pageCount')},
{field: 'amazonRating', header: this.t.translate('book.columnPref.columns.amazonRating')},
{field: 'amazonReviewCount', header: this.t.translate('book.columnPref.columns.amazonReviewCount')},
{field: 'goodreadsRating', header: this.t.translate('book.columnPref.columns.goodreadsRating')},
{field: 'goodreadsReviewCount', header: this.t.translate('book.columnPref.columns.goodreadsReviewCount')},
{field: 'hardcoverRating', header: this.t.translate('book.columnPref.columns.hardcoverRating')},
{field: 'hardcoverReviewCount', header: this.t.translate('book.columnPref.columns.hardcoverReviewCount')},
{field: 'ranobedbRating', header: this.t.translate('book.columnPref.columns.ranobedbRating')},
];
protected readonly coverOverlayPositions = COVER_OVERLAY_POSITIONS;
scrollHeight = 'calc(100dvh - 160px)';
private readonly columnDefs = computed<ColumnDef<Book>[]>(() => [
{id: 'select', header: '', size: 42, minSize: 42, maxSize: 42, enableResizing: false},
{id: 'lock', header: '', size: 42, minSize: 42, maxSize: 42, enableResizing: false},
{id: 'cover', header: '', size: 56, minSize: 56, maxSize: 56, enableResizing: false},
...this.visibleColumns().map(column => ({
id: column.field,
header: column.header,
size: this.defaultColumnSize(column.field),
minSize: this.minColumnSize(column.field),
maxSize: this.maxColumnSize(column.field),
})),
]);
ngOnInit(): void {
const user = this.userService.currentUser();
if (user) {
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
readonly table = createAngularTable(() => ({
data: this.books(),
columns: this.columnDefs(),
getCoreRowModel: getCoreRowModel(),
getRowId: book => String(book.id),
columnResizeMode: 'onChange',
state: {
columnSizing: this.columnSizing(),
},
onColumnSizingChange: updater => {
this.columnSizing.update(current => functionalUpdate(updater, current));
},
}));
readonly visibleCellIds = computed(() => ['select', 'lock', 'cover', ...this.visibleColumns().map(column => column.field)]);
readonly ariaRowCount = computed(() => this.rowCount() + 1);
readonly ariaColumnCount = computed(() => this.visibleCellIds().length);
readonly isColumnResizing = computed(() => Boolean(this.table.getState().columnSizingInfo.isResizingColumn));
readonly rowCount = computed(() => Math.max(this.virtualRowCount(), this.books().length));
readonly columnSizeVars = computed<Record<string, number | string>>(() => {
this.columnSizing();
this.visibleColumns();
const headers = this.table.getFlatHeaders();
const styles = headers.reduce<Record<string, number | string>>((columnStyles, header) => {
columnStyles[`--book-table-col-${header.column.id}-size`] = header.column.getSize();
return columnStyles;
}, {});
styles['--book-table-grid-template'] = this.table.getVisibleFlatColumns()
.map(column => `calc(var(--book-table-col-${column.id}-size) * 1px)`)
.join(' ');
return styles;
});
readonly tableWidth = computed(() => {
this.columnSizing();
this.visibleColumns();
return this.table.getVisibleFlatColumns().reduce((width, column) => width + column.getSize(), 0);
});
readonly allLoadedBooksSelected = computed(() => {
const books = this.books();
return books.length > 0 && books.every(book => this.bookSelectionService.isBookSelected(book));
});
readonly someBooksSelected = computed(() => {
return this.bookSelectionService.selectedCount() > 0 && !this.allLoadedBooksSelected();
});
readonly rowVirtualizer = injectVirtualizer<HTMLElement, HTMLElement>(() => ({
scrollElement: this.scrollElement(),
count: this.rowCount(),
estimateSize: () => ROW_HEIGHT,
overscan: this.isColumnResizing() ? RESIZE_OVERSCAN_ROWS : RENDER_OVERSCAN_ROWS,
initialOffset: this.initialScrollOffset,
getItemKey: index => this.books()[index]?.id ?? `loading-${index}`,
}));
constructor() {
this.scrollService.trackRoute({
scrollElement: this.scrollElement,
route: this.activatedRoute,
destroyRef: this.destroyRef,
keySuffix: 'table',
dismissOverlaysBeforeSave: true,
beforeSave: () => this.clearCoverPreview(),
});
}
private readonly measureRowsEffect = effect(() => {
this.rowCount();
this.visibleColumns();
queueMicrotask(() => this.rowVirtualizer.measure());
});
private lastLoadRequestLoadedBookCount: number | undefined;
private lastSeenQueryToken: unknown;
private readonly paginatorEffect = effect(() => {
const queryToken = this.bookQueryToken();
if (queryToken !== this.lastSeenQueryToken) {
this.lastLoadRequestLoadedBookCount = undefined;
this.lastSeenQueryToken = queryToken;
}
this.selectedBookIds = new Set(this.preselectedBookIds);
this.syncSelectedBooks();
this.setScrollHeight();
window.addEventListener('resize', this.resizeListener);
}
setScrollHeight() {
const isMobile = window.innerWidth <= 768;
this.scrollHeight = isMobile
? 'calc(100dvh - 125px)'
: 'calc(100dvh - 150px)';
}
ngOnChanges(changes: import('@angular/core').SimpleChanges) {
if (changes['preselectedBookIds'] || changes['books']) {
this.selectedBookIds = new Set(this.preselectedBookIds);
this.syncSelectedBooks();
const items = this.books();
const loadedBookCount = this.loadedBookCount() ?? items.length;
const lastVirtualItem = this.rowVirtualizer.getVirtualItems().at(-1);
if (!lastVirtualItem || items.length === 0) return;
if (lastVirtualItem.index < items.length - PAGE_LOAD_AHEAD_ROWS) return;
if (items.length >= this.virtualRowCount() || this.isFetchingNextPage()) return;
if (this.lastLoadRequestLoadedBookCount === loadedBookCount) {
this.lastLoadRequestLoadedBookCount = undefined;
return;
}
this.lastLoadRequestLoadedBookCount = loadedBookCount;
this.loadNextPage.emit();
});
private defaultColumnSize(field: string): number {
const defaultSize = DEFAULT_COLUMN_SIZES[field];
if (defaultSize !== undefined) return defaultSize;
if (RATING_FIELDS.has(field)) return DEFAULT_RATING_COLUMN_SIZE;
if (field.endsWith('ReviewCount')) return DEFAULT_REVIEW_COUNT_COLUMN_SIZE;
return DEFAULT_TEXT_COLUMN_SIZE;
}
private syncSelectedBooks(): void {
// Only include in 'selectedBooks' the objects that are actually in 'this.books'
// so that p-table correctly shows them as selected in the UI.
this.selectedBooks = this.books.filter(book => this.isBookSelected(book));
private minColumnSize(field: string): number {
return MIN_COLUMN_SIZES[field] ?? DEFAULT_MIN_COLUMN_SIZE;
}
private getSelectableBookIds(book: Book): number[] {
return book.seriesBooks?.length
? book.seriesBooks.map(seriesBook => seriesBook.id)
: [book.id];
private maxColumnSize(field: string): number {
return MAX_COLUMN_SIZES[field] ?? DEFAULT_MAX_COLUMN_SIZE;
}
private isBookSelected(book: Book): boolean {
return this.getSelectableBookIds(book).every(bookId => this.selectedBookIds.has(bookId));
isRowSelected(book: Book): boolean {
return this.bookSelectionService.isBookSelected(book);
}
startColumnResize(header: Header<Book, unknown>, event: MouseEvent | TouchEvent): void {
event.stopPropagation();
if (event.cancelable) {
event.preventDefault();
}
header.getResizeHandler()(event);
}
scrollToTop(): void {
const tableElement = this.elementRef.nativeElement.querySelector('.p-datatable-wrapper');
if (tableElement instanceof HTMLElement) {
tableElement.scrollTop = 0;
const scrollElement = this.scrollElement()?.nativeElement;
if (scrollElement) {
scrollElement.scrollTop = 0;
}
this.rowVirtualizer.scrollToOffset(0);
}
selectAllBooks(): void {
// We delegate the "Select All" logic to the parent component
// which can fetch all book IDs from the API.
this.selectAllRequested.emit();
}
clearSelectedBooks(): void {
this.selectedBookIds.clear();
this.selectedBooks = [];
this.selectedBooksChange.emit(this.selectedBookIds);
}
onRowSelect(event: { data?: Book | Book[] }): void {
if (event.data && !Array.isArray(event.data)) {
this.getSelectableBookIds(event.data).forEach(bookId => this.selectedBookIds.add(bookId));
this.selectedBooksChange.emit(new Set(this.selectedBookIds));
}
}
onRowUnselect(event: { data?: Book | Book[] }): void {
if (event.data && !Array.isArray(event.data)) {
this.getSelectableBookIds(event.data).forEach(bookId => this.selectedBookIds.delete(bookId));
this.selectedBooksChange.emit(new Set(this.selectedBookIds));
}
}
onHeaderCheckboxToggle(event: { checked: boolean }): void {
if (event.checked) {
onHeaderCheckboxChange(checked: boolean): void {
if (checked) {
this.selectAllRequested.emit();
} else {
this.clearSelectedBooks();
return;
}
this.bookSelectionService.deselectAll();
}
onBookSelectionChange(change: BookTableSelectionChange): void {
this.bookSelectionService.handleBookSelection(change.book, change.checked);
}
showCoverPreview(preview: BookTableRowCoverPreview): void {
this.coverPreview.set(preview);
}
clearCoverPreview(): void {
this.coverPreview.set(null);
}
hideCoverPreview(bookId: number): void {
if (this.coverPreview()?.book.id === bookId) {
this.clearCoverPreview();
}
}
getStarColor(rating: number): string {
if (rating >= 4.5) {
return 'rgb(34, 197, 94)';
} else if (rating >= 4) {
return 'rgb(52, 211, 153)';
} else if (rating >= 3.5) {
return 'rgb(234, 179, 8)';
} else if (rating >= 2.5) {
return 'rgb(249, 115, 22)';
} else {
return 'rgb(239, 68, 68)';
}
}
getAuthorNames(authors: string[]): string {
return authors?.join(', ') || '';
}
getGenres(genres: string[]) {
return genres?.join(', ') || '';
}
trackByBookId(index: number, book: Book): number {
return book.id;
}
isMetadataFullyLocked(metadata: BookMetadata): boolean {
const lockedKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
if (lockedKeys.length === 0) return false;
return lockedKeys.every(key => metadata[key] === true);
}
formatFileSize(kb?: number): string {
if (kb == null || isNaN(kb)) return '-';
const mb = kb / 1024;
return mb >= 1 ? `${mb.toFixed(1)} MB` : `${mb.toFixed(2)} MB`;
}
getReadStatusIcon(readStatus: ReadStatus | undefined): string {
return this.readStatusHelper.getReadStatusIcon(readStatus);
}
getReadStatusClass(readStatus: ReadStatus | undefined): string {
return this.readStatusHelper.getReadStatusClass(readStatus);
}
getReadStatusTooltip(readStatus: ReadStatus | undefined): string {
return this.readStatusHelper.getReadStatusTooltip(readStatus);
}
shouldShowStatusIcon(readStatus: ReadStatus | undefined): boolean {
return this.readStatusHelper.shouldShowStatusIcon(readStatus);
}
getCellClickableValue(metadata: BookMetadata, book: Book, field: string) {
const filterKeys: Record<string, string> = {
'authors': 'author',
'publisher': 'publisher',
'categories': 'category',
'language': 'language',
'title': 'title',
'isbn': 'isbn'
} as const;
let data: string[] = [metadata[field] as string];
switch (field) {
case 'title':
return [
{
url: this.urlHelper.getBookUrl(book),
anchor: metadata.title ?? book.fileName
}
];
case 'categories':
data = metadata.categories ?? [];
break;
case 'authors':
data = metadata.authors ?? [];
break;
case 'seriesName':
return [
{
url: this.urlHelper.filterBooksBy('series', metadata.seriesName ?? ''),
anchor: metadata.seriesName
}
]
case 'isbn':
return [
{
url: '',
anchor: this.getCellValue(metadata, book, 'isbn')
}
];
}
return data.map(item => {
return {
url: this.urlHelper.filterBooksBy(filterKeys[field] ?? field, item),
anchor: item
}
});
}
getCellValue(metadata: BookMetadata, book: Book, field: string): string | number {
switch (field) {
case 'readStatus':
return this.readStatusHelper.getReadStatusTooltip(book?.readStatus);
case 'title':
return metadata.title ?? '';
case 'authors':
return this.getAuthorNames(metadata.authors!);
case 'publisher':
return metadata.publisher ?? '';
case 'seriesName':
return metadata.seriesName ?? '';
case 'seriesNumber':
return metadata.seriesNumber ?? '';
case 'categories':
return this.getGenres(metadata.categories!);
case 'publishedDate':
return metadata.publishedDate ? this.datePipe.transform(metadata.publishedDate, 'dd-MMM-yyyy') ?? '' : '';
case 'lastReadTime':
return book.lastReadTime ? this.datePipe.transform(book.lastReadTime, 'dd-MMM-yyyy') ?? '' : '';
case 'addedOn':
return book.addedOn ? this.datePipe.transform(book.addedOn, 'dd-MMM-yyyy') ?? '' : '';
case 'fileName':
return book.primaryFile?.fileName ?? '';
case 'fileSizeKb':
return this.formatFileSize(book.fileSizeKb);
case 'language':
return metadata.language ?? '';
case 'pageCount':
return metadata.pageCount ?? '';
case 'amazonRating':
case 'goodreadsRating':
case 'hardcoverRating':
case 'ranobedbRating': {
const rating = metadata[field];
return typeof rating === 'number' ? rating.toFixed(1) : '';
}
case 'amazonReviewCount':
case 'goodreadsReviewCount':
case 'hardcoverReviewCount':
return metadata[field] ?? '';
case 'isbn':
return metadata.isbn13 || metadata.isbn10 || '';
default:
return '';
}
isMetadataLockPending(bookId: number): boolean {
return this.pendingLockBookIds().has(bookId);
}
toggleMetadataLock(metadata: BookMetadata): void {
const lockKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
const allLocked = lockKeys.every(key => metadata[key] === true);
const lockAction = allLocked ? 'UNLOCK' : 'LOCK';
if (this.isMetadataLockPending(metadata.bookId)) return;
this.bookMetadataManageService.toggleAllLock(new Set([metadata.bookId]), lockAction).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedSummary') : this.t.translate('book.table.toast.metadataUnlockedSummary'),
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedDetail') : this.t.translate('book.table.toast.metadataUnlockedDetail'),
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedSummary') : this.t.translate('book.table.toast.unlockFailedSummary'),
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedDetail') : this.t.translate('book.table.toast.unlockFailedDetail'),
});
const lockAction = isMetadataFullyLocked(metadata) ? 'UNLOCK' : 'LOCK';
this.setMetadataLockPending(metadata.bookId, true);
this.bookMetadataManageService.toggleAllLock(new Set([metadata.bookId]), lockAction)
.pipe(
finalize(() => this.setMetadataLockPending(metadata.bookId, false)),
takeUntilDestroyed(this.destroyRef)
)
.subscribe({
next: () => {
patchAppBooksMetadataLockInCache(this.queryClient, metadata.bookId, lockAction === 'LOCK');
this.messageService.add({
severity: 'success',
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedSummary') : this.t.translate('book.table.toast.metadataUnlockedSummary'),
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.metadataLockedDetail') : this.t.translate('book.table.toast.metadataUnlockedDetail'),
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedSummary') : this.t.translate('book.table.toast.unlockFailedSummary'),
detail: lockAction === 'LOCK' ? this.t.translate('book.table.toast.lockFailedDetail') : this.t.translate('book.table.toast.unlockFailedDetail'),
});
}
});
}
private setMetadataLockPending(bookId: number, pending: boolean): void {
this.pendingLockBookIds.update(current => {
if (current.has(bookId) === pending) return current;
const next = new Set(current);
if (pending) {
next.add(bookId);
} else {
next.delete(bookId);
}
return next;
});
}
ngOnDestroy(): void {
window.removeEventListener('resize', this.resizeListener);
}
}
@@ -0,0 +1,25 @@
import {describe, expect, it} from 'vitest';
import {BookMetadata} from '../../../model/book.model';
import {LOCK_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
describe('book-table helpers', () => {
it('uses the explicit allMetadataLocked value when present', () => {
expect(isMetadataFullyLocked({bookId: 1, allMetadataLocked: true})).toBe(true);
expect(isMetadataFullyLocked({bookId: 1, allMetadataLocked: false, titleLocked: true})).toBe(false);
});
it('does not infer a full lock from partial metadata', () => {
expect(isMetadataFullyLocked({bookId: 1, titleLocked: true, authorsLocked: true})).toBe(false);
});
it('requires every metadata lock field to be true when the explicit flag is absent', () => {
const metadata = {
bookId: 1,
...Object.fromEntries(LOCK_FIELDS.map(field => [field, true])),
} satisfies BookMetadata;
expect(isMetadataFullyLocked(metadata)).toBe(true);
expect(isMetadataFullyLocked({...metadata, titleLocked: false})).toBe(false);
});
});
@@ -0,0 +1,66 @@
import {BookMetadata} from '../../../model/book.model';
const RATING_FIELD_KEYS = [
'rating',
'amazonRating',
'goodreadsRating',
'hardcoverRating',
'ranobedbRating',
'lubimyczytacRating',
'audibleRating',
] satisfies readonly (keyof BookMetadata)[];
export const RATING_FIELDS = new Set<keyof BookMetadata>(RATING_FIELD_KEYS);
export const LOCK_FIELDS = [
'titleLocked',
'subtitleLocked',
'publisherLocked',
'publishedDateLocked',
'descriptionLocked',
'seriesNameLocked',
'seriesNumberLocked',
'seriesTotalLocked',
'isbn13Locked',
'isbn10Locked',
'asinLocked',
'comicvineIdLocked',
'goodreadsIdLocked',
'hardcoverIdLocked',
'hardcoverBookIdLocked',
'googleIdLocked',
'pageCountLocked',
'languageLocked',
'amazonRatingLocked',
'amazonReviewCountLocked',
'goodreadsRatingLocked',
'goodreadsReviewCountLocked',
'hardcoverRatingLocked',
'hardcoverReviewCountLocked',
'lubimyczytacIdLocked',
'lubimyczytacRatingLocked',
'ranobedbIdLocked',
'ranobedbRatingLocked',
'audibleIdLocked',
'audibleRatingLocked',
'audibleReviewCountLocked',
'coverUpdatedOnLocked',
'authorsLocked',
'categoriesLocked',
'moodsLocked',
'tagsLocked',
'coverLocked',
'audiobookCoverLocked',
'reviewsLocked',
'narratorLocked',
'abridgedLocked',
'ageRatingLocked',
'contentRatingLocked',
] satisfies readonly (keyof BookMetadata)[];
export function isMetadataFullyLocked(metadata: BookMetadata): boolean {
if (typeof metadata.allMetadataLocked === 'boolean') {
return metadata.allMetadataLocked;
}
return LOCK_FIELDS.every(field => metadata[field] === true);
}
@@ -2,7 +2,8 @@ import {Shelf} from './shelf.model';
import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageSplitOption, CbxPageViewMode, CbxScrollMode, NewPdfReaderSetting} from '../../settings/user-management/user.service';
import {BookReview} from '../components/book-reviews/book-review-service';
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3" | "AUDIOBOOK";
export const BOOK_TYPES = ['PDF', 'EPUB', 'CBX', 'FB2', 'MOBI', 'AZW3', 'AUDIOBOOK'] as const;
export type BookType = typeof BOOK_TYPES[number];
export enum AdditionalFileType {
ALTERNATIVE_FORMAT = 'ALTERNATIVE_FORMAT',
@@ -11,9 +11,11 @@ import {
AppFilterOptions,
AppPageResponse,
} from '../model/app-book.model';
import {Book, BookFile, BookType, ReadStatus} from '../model/book.model';
import {Book, BOOK_TYPES, BookFile, BookType, ReadStatus} from '../model/book.model';
const PAGE_SIZE = 50;
const BOOK_TYPE_SET = new Set<BookType>(BOOK_TYPES);
const READ_STATUSES = new Set<ReadStatus>(Object.values(ReadStatus) as ReadStatus[]);
@Injectable({providedIn: 'root'})
export class AppBooksApiService {
@@ -222,16 +224,17 @@ export class AppBooksApiService {
/**
* Maps a server-side AppBookSummary to a Book-shaped object
* compatible with BookCardComponent's @Input() book property.
* compatible with book browser card and table views.
*/
function summaryToBook(summary: AppBookSummary): Book {
return {
id: summary.id,
libraryId: summary.libraryId,
readStatus: (summary.readStatus as ReadStatus) ?? ReadStatus.UNSET,
personalRating: summary.personalRating ?? 0,
addedOn: summary.addedOn,
lastReadTime: summary.lastReadTime,
libraryName: '',
readStatus: summaryToReadStatus(summary.readStatus),
personalRating: summary.personalRating,
addedOn: summary.addedOn ?? undefined,
lastReadTime: summary.lastReadTime ?? undefined,
isPhysical: summary.isPhysical ?? false,
fileSizeKb: summary.fileSizeKb ?? undefined,
metadataMatchScore: summary.metadataMatchScore,
@@ -240,7 +243,7 @@ function summaryToBook(summary: AppBookSummary): Book {
title: summary.title,
authors: summary.authors ?? [],
publisher: summary.publisher ?? undefined,
seriesName: summary.seriesName,
seriesName: summary.seriesName ?? undefined,
seriesNumber: summary.seriesNumber,
categories: summary.categories ?? [],
tags: summary.tags ?? [],
@@ -249,8 +252,8 @@ function summaryToBook(summary: AppBookSummary): Book {
narrator: summary.narrator ?? undefined,
isbn13: summary.isbn13 ?? undefined,
isbn10: summary.isbn10 ?? undefined,
coverUpdatedOn: summary.coverUpdatedOn,
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn,
coverUpdatedOn: summary.coverUpdatedOn ?? undefined,
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn ?? undefined,
publishedDate: summary.publishedDate ?? undefined,
pageCount: summary.pageCount,
ageRating: summary.ageRating,
@@ -270,32 +273,40 @@ function summaryToBook(summary: AppBookSummary): Book {
primaryFile: summaryToPrimaryFile(summary),
pdfProgress: summary.readProgress != null
? {page: 0, percentage: summary.readProgress}
: null,
epubProgress: null,
cbxProgress: null,
: undefined,
shelves: [],
} as unknown as Book;
};
}
function summaryToPrimaryFile(summary: AppBookSummary): Partial<BookFile> | null {
if (!summary.primaryFileType) return null;
function summaryToPrimaryFile(summary: AppBookSummary): BookFile | undefined {
if (summary.primaryFileId == null) return undefined;
const primaryFile: Partial<BookFile> = {
const primaryFile: BookFile = {
id: summary.primaryFileId,
bookId: summary.id,
bookType: summary.primaryFileType,
extension: summaryToPrimaryFileExtension(summary, summary.primaryFileType),
extension: summaryToPrimaryFileExtension(summary),
fileSizeKb: summary.fileSizeKb ?? undefined,
fileName: summary.primaryFileName ?? undefined,
};
if (summary.primaryFileId != null) {
primaryFile.id = summary.primaryFileId;
const bookType = summaryToBookType(summary.primaryFileType);
if (bookType) {
primaryFile.bookType = bookType;
}
return primaryFile;
}
function summaryToPrimaryFileExtension(summary: AppBookSummary, bookType: BookType): string | undefined {
function summaryToBookType(value: string | null): BookType | undefined {
return value != null && BOOK_TYPE_SET.has(value as BookType) ? value as BookType : undefined;
}
function summaryToReadStatus(value: string | null): ReadStatus {
const readStatus = value as ReadStatus;
return value != null && READ_STATUSES.has(readStatus) ? readStatus : ReadStatus.UNREAD;
}
function summaryToPrimaryFileExtension(summary: AppBookSummary): string | undefined {
const fileName = summary.primaryFileName;
if (fileName) {
const dotIndex = fileName.lastIndexOf('.');
@@ -304,5 +315,5 @@ function summaryToPrimaryFileExtension(summary: AppBookSummary, bookType: BookTy
}
}
return bookType.toLowerCase();
return summary.primaryFileType?.toLowerCase();
}
@@ -129,3 +129,22 @@ export function patchAppBooksCoverInCache(
}
);
}
export function patchAppBooksMetadataLockInCache(queryClient: QueryClient, bookId: number, allMetadataLocked: boolean): void {
queryClient.setQueriesData<InfiniteData<AppPageResponse<AppBookSummary>>>(
{queryKey: APP_BOOKS_QUERY_PREFIX},
current => {
if (!current) return current;
return {
...current,
pages: current.pages.map(page => ({
...page,
content: page.content.map(summary =>
summary.id === bookId ? {...summary, allMetadataLocked} : summary
),
})),
};
}
);
}
@@ -0,0 +1,17 @@
<span
[class]="'app-rating ' + ratingClass()"
[style.--app-rating-color]="color()"
[style.--app-rating-size]="size()"
[attr.aria-label]="ratingAriaLabel()"
role="img">
@for (fill of starFills(); track $index) {
<span class="app-rating-star" [style.--app-rating-star-fill]="fill">
<svg class="app-rating-star-empty" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" focusable="false">
<path stroke-linecap="round" stroke-linejoin="round" d="M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.562.562 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z" />
</svg>
<svg class="app-rating-star-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path fill-rule="evenodd" d="M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005Z" clip-rule="evenodd" />
</svg>
</span>
}
</span>
@@ -0,0 +1,64 @@
:host {
display: inline-flex;
align-items: center;
line-height: 1;
--app-rating-color: var(--p-rating-icon-active-color, var(--p-primary-color));
--app-rating-empty-color: var(--p-rating-icon-color, var(--p-text-muted-color));
--app-rating-gap: var(--p-rating-gap, 0.25rem);
--app-rating-size: 18px;
}
.app-rating {
display: inline-flex;
align-items: center;
gap: var(--app-rating-gap);
line-height: 1;
&.app-rating-excellent {
--app-rating-color: rgb(34 197 94);
}
&.app-rating-good {
--app-rating-color: rgb(52 211 153);
}
&.app-rating-mixed {
--app-rating-color: rgb(234 179 8);
}
&.app-rating-low {
--app-rating-color: rgb(249 115 22);
}
&.app-rating-poor {
--app-rating-color: rgb(239 68 68);
}
}
.app-rating-star {
--app-rating-star-fill: 0%;
position: relative;
display: inline-flex;
width: var(--app-rating-size);
height: var(--app-rating-size);
line-height: 0;
}
.app-rating-star svg {
display: block;
width: 100%;
height: 100%;
}
.app-rating-star-empty {
color: var(--app-rating-empty-color);
}
.app-rating-star-filled {
position: absolute;
inset: 0;
fill: var(--app-rating-color);
clip-path: inset(0 calc(100% - var(--app-rating-star-fill)) 0 0);
}
@@ -0,0 +1,46 @@
import {ChangeDetectionStrategy, Component, computed, input} from '@angular/core';
@Component({
selector: 'app-rating',
standalone: true,
templateUrl: './rating.component.html',
styleUrls: ['./rating.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RatingComponent {
value = input<number | null>(null);
color = input<string | null>(null);
max = input(5);
size = input('18px');
ariaLabel = input<string | null>(null);
protected readonly ratingClass = computed(() => this.getRatingClass(this.value()));
protected readonly ratingAriaLabel = computed(() => {
const label = this.ariaLabel();
if (label) return label;
const rating = this.value();
return rating === null ? null : `${rating.toFixed(1)} / ${this.max()}`;
});
protected readonly starFills = computed(() => {
const rating = this.value();
return Array.from({length: this.max()}, (_, index) => this.getStarFill(rating, index));
});
private getStarFill(rating: number | null, starIndex: number): string {
if (rating === null) return '0%';
const fill = Math.max(0, Math.min(1, rating - starIndex));
return `${Math.round(fill * 100)}%`;
}
private getRatingClass(rating: number | null): string {
if (rating === null) return 'app-rating-unrated';
if (rating >= 4.5) return 'app-rating-excellent';
if (rating >= 4) return 'app-rating-good';
if (rating >= 3.5) return 'app-rating-mixed';
if (rating >= 2.5) return 'app-rating-low';
return 'app-rating-poor';
}
}
@@ -55,6 +55,21 @@ describe('RouteScrollPositionService', () => {
expect(service.keyFor(route)).toBe('authors/42:id=42');
});
it('can suffix route keys for independent view scroll positions', () => {
const route = {
snapshot: {
pathFromRoot: [
{url: []},
{url: [{path: 'books'}]},
],
params: {libraryId: '1'},
},
} as unknown as ActivatedRoute;
expect(service.keyFor(route, 'grid')).toBe('books:libraryId=1:grid');
expect(service.keyFor(route, 'table')).toBe('books:libraryId=1:table');
});
it('encodes route key values and falls back to the path when params are empty', () => {
expect(service.createKey('/books', {slug: 'one-two', type: 'magic&shelf'})).toBe('/books:slug=one-two;type=magic%26shelf');
expect(service.createKey('/books', {})).toBe('/books');
@@ -7,6 +7,7 @@ interface TrackRouteOptions {
scrollElement: Signal<ElementRef<HTMLElement> | undefined>;
route: ActivatedRoute;
destroyRef: DestroyRef;
keySuffix?: string;
dismissOverlaysBeforeSave?: boolean;
beforeSave?: () => void;
}
@@ -47,13 +48,14 @@ export class RouteScrollPositionService {
return paramPairs ? `${path}:${paramPairs}` : path;
}
keyFor(route: ActivatedRoute): string {
keyFor(route: ActivatedRoute, suffix?: string): string {
const path = route.snapshot.pathFromRoot
.flatMap(snapshot => snapshot.url)
.map(segment => segment.path)
.filter(Boolean)
.join('/');
return this.createKey(path, route.snapshot.params);
const key = this.createKey(path, route.snapshot.params);
return suffix ? `${key}:${suffix}` : key;
}
dismissBodyOverlays(): void {
@@ -71,7 +73,7 @@ export class RouteScrollPositionService {
options.beforeSave?.();
const element = options.scrollElement()?.nativeElement;
if (element) {
this.savePosition(this.keyFor(options.route), element.scrollTop);
this.savePosition(this.keyFor(options.route, options.keySuffix), element.scrollTop);
}
});
}