From 1c9902448fd6811f8df172521e63318e378e6c36 Mon Sep 17 00:00:00 2001 From: Alex <25013571+alexhb1@users.noreply.github.com> Date: Sun, 3 May 2026 08:11:19 +0100 Subject: [PATCH] refactor(ui): use tanstack virtual+table for book browser table view (#1047) --- frontend/package.json | 1 + .../book-browser/book-browser.component.html | 59 +- .../book-browser/book-browser.component.scss | 90 +-- .../book-browser.component.spec.ts | 90 ++- .../book-browser/book-browser.component.ts | 145 ++--- .../book-table/book-table-row.component.html | 100 +++ .../book-table/book-table-row.component.scss | 179 ++++++ .../book-table-row.component.spec.ts | 128 ++++ .../book-table/book-table-row.component.ts | 327 ++++++++++ .../book-table/book-table.component.html | 225 +++---- .../book-table/book-table.component.scss | 288 ++++++--- .../book-table/book-table.component.spec.ts | 300 ++++++++- .../book-table/book-table.component.ts | 602 ++++++++---------- .../book-table/book-table.helpers.spec.ts | 25 + .../book-table/book-table.helpers.ts | 66 ++ .../src/app/features/book/model/book.model.ts | 3 +- .../book/service/app-books-api.service.ts | 55 +- .../features/book/service/book-query-cache.ts | 19 + .../components/rating/rating.component.html | 17 + .../components/rating/rating.component.scss | 64 ++ .../components/rating/rating.component.ts | 46 ++ .../route-scroll-position.service.spec.ts | 15 + .../service/route-scroll-position.service.ts | 8 +- frontend/src/i18n/da/book.json | 8 +- frontend/src/i18n/de/book.json | 8 +- frontend/src/i18n/en/book.json | 8 +- frontend/src/i18n/es/book.json | 8 +- frontend/src/i18n/fr/book.json | 8 +- frontend/src/i18n/hr/book.json | 8 +- frontend/src/i18n/hu/book.json | 8 +- frontend/src/i18n/id/book.json | 8 +- frontend/src/i18n/it/book.json | 8 +- frontend/src/i18n/ja/book.json | 8 +- frontend/src/i18n/nl/book.json | 8 +- frontend/src/i18n/pl/book.json | 8 +- frontend/src/i18n/pt/book.json | 8 +- frontend/src/i18n/ru/book.json | 8 +- frontend/src/i18n/sk/book.json | 8 +- frontend/src/i18n/sl/book.json | 8 +- frontend/src/i18n/sv/book.json | 8 +- frontend/src/i18n/uk/book.json | 8 +- frontend/src/i18n/zh/book.json | 8 +- frontend/yarn.lock | 22 +- 43 files changed, 2241 insertions(+), 785 deletions(-) create mode 100644 frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html create mode 100644 frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss create mode 100644 frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts create mode 100644 frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts create mode 100644 frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.spec.ts create mode 100644 frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.ts create mode 100644 frontend/src/app/shared/components/rating/rating.component.html create mode 100644 frontend/src/app/shared/components/rating/rating.component.scss create mode 100644 frontend/src/app/shared/components/rating/rating.component.ts diff --git a/frontend/package.json b/frontend/package.json index 6c12cc27e..5ed68ad9e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -39,6 +39,7 @@ "@stomp/rx-stomp": "^2.3.0", "@stomp/stompjs": "^7.3.0", "@tanstack/angular-query-experimental": "5.100.1", + "@tanstack/angular-table": "^8.21.4", "@tanstack/angular-virtual": "^4.0.13", "chart.js": "^4.5.1", "chartjs-chart-matrix": "^3.0.0", diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.html b/frontend/src/app/features/book/components/book-browser/book-browser.component.html index ee6e9e623..c88fe7c37 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.html +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.html @@ -128,17 +128,17 @@ @@ -253,38 +253,20 @@ - @if (showTableLoadingPlaceholder()) { - - } @else if (showGridLoadingPlaceholder()) { -
-
- @for (item of skeletonSlots; track item) { -
-
- } -
-
- } @else if (booksError()) { + @if (booksError()) {

- {{ 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') }} + } + }

} @else { @@ -296,14 +278,17 @@

} - @if (currentViewMode() === 'table' && visibleBooks.length > 0) { + @if (currentViewMode() === 'table' && (visibleBooks.length > 0 || showTableLoadingPlaceholder())) { } @if (currentViewMode() === 'grid') { diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.scss b/frontend/src/app/features/book/components/book-browser/book-browser.component.scss index 15acfc0b2..c690be647 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.scss +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.scss @@ -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 diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts index 3821c0ca6..55510dd3e 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts @@ -107,6 +107,7 @@ interface BookBrowserHarness { isBooksLoading: WritableSignal; paramMap$: BehaviorSubject; setHasNextPage: (value: boolean) => void; + setIsFetchingNextPage: (value: boolean) => void; queryParamsService: { shouldForceExpandSeries: ReturnType; updateViewMode: ReturnType; @@ -140,6 +141,7 @@ function createHarness(options?: { ); const booksError = signal(options?.booksError ?? null); const isBooksLoading = signal(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); }); }); diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.ts index 947fc9c49..271084df0 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.ts @@ -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([]); readonly currentFilterLabel = signal(null); readonly rawFilterParamFromUrl = signal(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>('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 = {}; 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): 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(this.MOBILE_COLUMNS_STORAGE_KEY); + const saved = this.localStorageService.get(MOBILE_COLUMNS_STORAGE_KEY); if (saved !== null && [2, 3, 4].includes(saved)) { - this.mobileColumnCount.set(saved); + this.gridMobileColumnCount.set(saved); } } } diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html new file mode 100644 index 000000000..d301fd710 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.html @@ -0,0 +1,100 @@ + + @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) { +
+ @switch (cell.kind) { + @case ('select') { + + } + @case ('lock') { + + } + @case ('cover') { + + @if (imageUrl) { + + } @else { + + } + @case ('readStatus') { + @if (showReadStatus()) { +
+ +
+ } + } + @case ('rating') { + + + @if (cell.rating !== null) { + ({{ cell.display }}) + } + + } + @case ('clickable') { + @for (item of cell.links; track $index; let isLast = $last) { + {{ item.anchor }}@if (!isLast) {, } + } + } + @case ('text') { + {{ cell.value }} + } + } +
+ } +
diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss new file mode 100644 index 000000000..46f05eaa7 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.scss @@ -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; + } +} diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts new file mode 100644 index 000000000..4856fe388 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.spec.ts @@ -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; + 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('.book-table-cell'); + const links = host.querySelectorAll('.cell-link'); + const rating = host.querySelector('.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('.metadata-lock-button'); + const coverLink = host.querySelector('.cover-link'); + const placeholder = host.querySelector('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: ''})); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts new file mode 100644 index 000000000..94f753748 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table-row.component.ts @@ -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 = { + 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(); + readonly cellIds = input.required(); + readonly rowIndex = input.required(); + readonly rowHeight = input.required(); + readonly rowStart = input.required(); + readonly isSelected = input(false); + readonly isLockPending = input(false); + readonly useSquareCovers = input(false); + + readonly selectionChange = output(); + readonly metadataLockToggleRequested = output(); + readonly coverPreviewShow = output(); + readonly coverPreviewHide = output(); + + private readonly datePipe = inject(DatePipe); + private readonly readStatusHelper = inject(ReadStatusHelper); + protected readonly urlHelper = inject(UrlHelperService); + + readonly metadata = computed(() => { + 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(value: T, field: PropertyKey): field is keyof T { + return Object.prototype.hasOwnProperty.call(value, field); + } + + private isAudiobook(): boolean { + return this.book().primaryFile?.bookType === 'AUDIOBOOK'; + } +} diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.html b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.html index 764bcb405..dac78a076 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.html +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.html @@ -1,128 +1,113 @@ - - - - - - - - - - @for (col of visibleColumns; track col.field) { - {{ col.header }} - } - - - - - @if (book.metadata; as metadata) { - - - - - - - - - - - @if (urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn); as coverUrl) { - - } @else { - - } - - -
- @if (urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn); as coverUrl) { - + +
+
+ @for (headerGroup of table.getHeaderGroups(); track headerGroup.id) { +
+ @for (header of headerGroup.headers; track header.id; let columnIndex = $index) { +
+ @if (header.column.id === 'select') { + } @else { - + {{ header.column.columnDef.header }} } - {{ metadata.title }} -
- - - @for (col of visibleColumns; track col.field) { - @if (col.field === 'readStatus') { - - @if (shouldShowStatusIcon(book.readStatus)) { -
- + @if (header.column.getCanResize()) { + + } +
+ } +
+ } + +
+ @for (virtualRow of rowVirtualizer.getVirtualItems(); track virtualRow.key) { + @if (books()[virtualRow.index]; as book) { + + } @else { +
+ @for (columnId of visibleCellIds(); track columnId; let columnIndex = $index) { +
+
} - - } @else if (col.field === 'amazonRating' || col.field === 'goodreadsRating' || col.field === 'hardcoverRating' || col.field === 'ranobedbRating') { - - - - @if (metadata[col.field] !== null && metadata[col.field] !== undefined) { - ({{ metadata[col.field]?.toFixed(1) }}) - } - - - } @else { - - @if(['title', 'authors', 'publisher', 'seriesName', 'categories', 'language'].includes(col.field)) { - @for (item of getCellClickableValue(metadata, book, col.field); track $index; let isLast = $last) { - - {{ item.anchor }}@if (!isLast) {, } - } - } @else { - {{ getCellValue(metadata, book, col.field) }} - } - +
} } - - } - - +
+
+
+ + @if (coverPreview(); as preview) { + +
+ @if (preview.coverUrl; as coverUrl) { + + } @else { + + } +
+
+ }
diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.scss b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.scss index 54beb915e..45acce66f 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.scss +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.scss @@ -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; + } } diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts index 698ed4115..2d90f2dfe 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.spec.ts @@ -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; + let component: BookTableComponent; + let bookSelectionService: BookSelectionService; + let bookMetadataManageService: { toggleAllLock: ReturnType }; + let queryClient: { setQueriesData: ReturnType }; + + 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('.book-table-scroll'); + const headerCells = host.querySelectorAll('.book-table-header-cell'); + const resizer = host.querySelector('.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('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(); + 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('.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); }); }); diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts index 4a3a76be4..7d6d24d9b 100644 --- a/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.component.ts @@ -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 = { + 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 = { + readStatus: 64, + pageCount: 96, + seriesNumber: 96, +}; +const DEFAULT_MIN_COLUMN_SIZE = 120; +const MAX_COLUMN_SIZES: Record = { + 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(); +export class BookTableComponent { + readonly selectAllRequested = output(); + readonly loadNextPage = output(); - @Output() selectedBooksChange = new EventEmitter>(); - @Output() selectAllRequested = new EventEmitter(); - @Input() books: Book[] = []; - @Input() sortOption: SortOption | null = null; - @Input() visibleColumns: { field: string; header: string }[] = []; - @Input() preselectedBookIds = new Set(); + readonly books = input([]); + readonly visibleColumns = input([]); + readonly virtualRowCount = input(0); + readonly loadedBookCount = input(null); + readonly isFetchingNextPage = input(false); + readonly useSquareCovers = input(false); + readonly bookQueryToken = input(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>('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({}); + protected readonly coverPreview = signal(null); + private readonly pendingLockBookIds = signal>(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[]>(() => [ + {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>(() => { + this.columnSizing(); + this.visibleColumns(); + + const headers = this.table.getFlatHeaders(); + const styles = headers.reduce>((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(() => ({ + 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, 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 = { - '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); - } } diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.spec.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.spec.ts new file mode 100644 index 000000000..16b35660d --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.spec.ts @@ -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); + }); +}); diff --git a/frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.ts b/frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.ts new file mode 100644 index 000000000..80a6fee48 --- /dev/null +++ b/frontend/src/app/features/book/components/book-browser/book-table/book-table.helpers.ts @@ -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(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); +} diff --git a/frontend/src/app/features/book/model/book.model.ts b/frontend/src/app/features/book/model/book.model.ts index b35152066..64ef3568c 100644 --- a/frontend/src/app/features/book/model/book.model.ts +++ b/frontend/src/app/features/book/model/book.model.ts @@ -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', diff --git a/frontend/src/app/features/book/service/app-books-api.service.ts b/frontend/src/app/features/book/service/app-books-api.service.ts index b32a3550c..e44b5f341 100644 --- a/frontend/src/app/features/book/service/app-books-api.service.ts +++ b/frontend/src/app/features/book/service/app-books-api.service.ts @@ -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(BOOK_TYPES); +const READ_STATUSES = new Set(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 | null { - if (!summary.primaryFileType) return null; +function summaryToPrimaryFile(summary: AppBookSummary): BookFile | undefined { + if (summary.primaryFileId == null) return undefined; - const primaryFile: Partial = { + 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(); } diff --git a/frontend/src/app/features/book/service/book-query-cache.ts b/frontend/src/app/features/book/service/book-query-cache.ts index 1dd8b2239..4399613bb 100644 --- a/frontend/src/app/features/book/service/book-query-cache.ts +++ b/frontend/src/app/features/book/service/book-query-cache.ts @@ -129,3 +129,22 @@ export function patchAppBooksCoverInCache( } ); } + +export function patchAppBooksMetadataLockInCache(queryClient: QueryClient, bookId: number, allMetadataLocked: boolean): void { + queryClient.setQueriesData>>( + {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 + ), + })), + }; + } + ); +} diff --git a/frontend/src/app/shared/components/rating/rating.component.html b/frontend/src/app/shared/components/rating/rating.component.html new file mode 100644 index 000000000..3a2151a83 --- /dev/null +++ b/frontend/src/app/shared/components/rating/rating.component.html @@ -0,0 +1,17 @@ + + @for (fill of starFills(); track $index) { + + + + + } + diff --git a/frontend/src/app/shared/components/rating/rating.component.scss b/frontend/src/app/shared/components/rating/rating.component.scss new file mode 100644 index 000000000..505e18ab3 --- /dev/null +++ b/frontend/src/app/shared/components/rating/rating.component.scss @@ -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); +} diff --git a/frontend/src/app/shared/components/rating/rating.component.ts b/frontend/src/app/shared/components/rating/rating.component.ts new file mode 100644 index 000000000..60d07135f --- /dev/null +++ b/frontend/src/app/shared/components/rating/rating.component.ts @@ -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(null); + color = input(null); + max = input(5); + size = input('18px'); + ariaLabel = input(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'; + } +} diff --git a/frontend/src/app/shared/service/route-scroll-position.service.spec.ts b/frontend/src/app/shared/service/route-scroll-position.service.spec.ts index 2d530ad5e..9a7e75f6e 100644 --- a/frontend/src/app/shared/service/route-scroll-position.service.spec.ts +++ b/frontend/src/app/shared/service/route-scroll-position.service.spec.ts @@ -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'); diff --git a/frontend/src/app/shared/service/route-scroll-position.service.ts b/frontend/src/app/shared/service/route-scroll-position.service.ts index d0f6ef706..6d71e35e3 100644 --- a/frontend/src/app/shared/service/route-scroll-position.service.ts +++ b/frontend/src/app/shared/service/route-scroll-position.service.ts @@ -7,6 +7,7 @@ interface TrackRouteOptions { scrollElement: Signal | 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); } }); } diff --git a/frontend/src/i18n/da/book.json b/frontend/src/i18n/da/book.json index a31940f37..adbfb84c4 100644 --- a/frontend/src/i18n/da/book.json +++ b/frontend/src/i18n/da/book.json @@ -48,6 +48,7 @@ "noBooks": "", "failedLibrary": "", "failedShelf": "", + "failedBooks": "", "activeFilters": "" }, "tooltip": { @@ -662,7 +663,12 @@ }, "table": { "bookCoverAlt": "", - "statusPrefix": "", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "{{ status }}", "locked": "", "unlocked": "", "toast": { diff --git a/frontend/src/i18n/de/book.json b/frontend/src/i18n/de/book.json index 48fe0d2f9..e3157b33a 100644 --- a/frontend/src/i18n/de/book.json +++ b/frontend/src/i18n/de/book.json @@ -48,6 +48,7 @@ "noBooks": "Diese Sammlung enthält keine Bücher!", "failedLibrary": "Bücher der Bibliothek konnten nicht geladen werden!", "failedShelf": "Bücher des Regals konnten nicht geladen werden!", + "failedBooks": "", "activeFilters": "{{ count }} aktive Filter" }, "tooltip": { @@ -619,7 +620,12 @@ }, "table": { "bookCoverAlt": "Buchcover", - "statusPrefix": "Status: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Status: {{ status }}", "locked": "Gesperrt", "unlocked": "Entsperrt", "toast": { diff --git a/frontend/src/i18n/en/book.json b/frontend/src/i18n/en/book.json index 1ed1c7d0a..3b02791b9 100644 --- a/frontend/src/i18n/en/book.json +++ b/frontend/src/i18n/en/book.json @@ -48,6 +48,7 @@ "noBooks": "This collection has no books!", "failedLibrary": "Failed to load library's books!", "failedShelf": "Failed to load shelf's books!", + "failedBooks": "Failed to load books!", "activeFilters": "{{ count }} Active Filters" }, "tooltip": { @@ -665,8 +666,13 @@ } }, "table": { + "label": "Books table", "bookCoverAlt": "Book Cover", - "statusPrefix": "Status: ", + "selectBook": "Select {{ title }}", + "selectBookFallback": "Select book", + "noRating": "No rating", + "ratingOutOf": "{{ rating }} out of {{ max }}", + "statusWithPrefix": "Status: {{ status }}", "locked": "Locked", "unlocked": "Unlocked", "toast": { diff --git a/frontend/src/i18n/es/book.json b/frontend/src/i18n/es/book.json index 39bd807cf..3ad4fc2e9 100644 --- a/frontend/src/i18n/es/book.json +++ b/frontend/src/i18n/es/book.json @@ -48,6 +48,7 @@ "noBooks": "¡Esta colección no tiene libros!", "failedLibrary": "¡Error al cargar los libros de la biblioteca!", "failedShelf": "¡Error al cargar los libros del estante!", + "failedBooks": "", "activeFilters": "{{ count }} filtros activos" }, "tooltip": { @@ -663,7 +664,12 @@ }, "table": { "bookCoverAlt": "Portada del libro", - "statusPrefix": "Estado: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Estado: {{ status }}", "locked": "Bloqueado", "unlocked": "Desbloqueado", "toast": { diff --git a/frontend/src/i18n/fr/book.json b/frontend/src/i18n/fr/book.json index 173467ce8..f508624b7 100644 --- a/frontend/src/i18n/fr/book.json +++ b/frontend/src/i18n/fr/book.json @@ -48,6 +48,7 @@ "noBooks": "Cette collection ne contient aucun livre !", "failedLibrary": "Échec du chargement des livres de la bibliothèque !", "failedShelf": "Échec du chargement des livres de l'étagère !", + "failedBooks": "", "activeFilters": "{{ count }} filtres actifs" }, "tooltip": { @@ -614,7 +615,12 @@ }, "table": { "bookCoverAlt": "Couverture du livre", - "statusPrefix": "Statut : ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Statut : {{ status }}", "locked": "Verrouillé", "unlocked": "Déverrouillé", "toast": { diff --git a/frontend/src/i18n/hr/book.json b/frontend/src/i18n/hr/book.json index 9f480301a..b2e6e8835 100644 --- a/frontend/src/i18n/hr/book.json +++ b/frontend/src/i18n/hr/book.json @@ -48,6 +48,7 @@ "noBooks": "Ova kolekcija nema knjiga!", "failedLibrary": "Učitavanje knjiga zbirke nije uspjelo!", "failedShelf": "Učitavanje knjiga police nije uspjelo!", + "failedBooks": "", "activeFilters": "{{ count }} aktivnih filtera" }, "tooltip": { @@ -618,7 +619,12 @@ }, "table": { "bookCoverAlt": "Naslovnica knjige", - "statusPrefix": "Status: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Status: {{ status }}", "locked": "Zaključano", "unlocked": "Otključano", "toast": { diff --git a/frontend/src/i18n/hu/book.json b/frontend/src/i18n/hu/book.json index 1d5c2b805..63a91ae0e 100644 --- a/frontend/src/i18n/hu/book.json +++ b/frontend/src/i18n/hu/book.json @@ -48,6 +48,7 @@ "noBooks": "Ebben a gyűjteményben nem találhatóak könyvek!", "failedLibrary": "Nem sikerült betölteni a könyvtárban lévő könyveket!", "failedShelf": "Nem sikerült betölteni a polcon lévő könyveket!", + "failedBooks": "", "activeFilters": "{{ count }} aktív szűrő" }, "tooltip": { @@ -614,7 +615,12 @@ }, "table": { "bookCoverAlt": "", - "statusPrefix": "", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "{{ status }}", "locked": "", "unlocked": "", "toast": { diff --git a/frontend/src/i18n/id/book.json b/frontend/src/i18n/id/book.json index aba562976..00c21e88e 100644 --- a/frontend/src/i18n/id/book.json +++ b/frontend/src/i18n/id/book.json @@ -48,6 +48,7 @@ "noBooks": "Tidak ada buku di koleksi ini!", "failedLibrary": "Gagal memuat buku perpustakaan!", "failedShelf": "Gagal memuat rak buku!", + "failedBooks": "", "activeFilters": "{{ count }} Saringan Aktif" }, "tooltip": { @@ -615,7 +616,12 @@ }, "table": { "bookCoverAlt": "", - "statusPrefix": "", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "{{ status }}", "locked": "", "unlocked": "", "toast": { diff --git a/frontend/src/i18n/it/book.json b/frontend/src/i18n/it/book.json index 690f8c864..c795ffc21 100644 --- a/frontend/src/i18n/it/book.json +++ b/frontend/src/i18n/it/book.json @@ -48,6 +48,7 @@ "noBooks": "Questa collezione non ha libri!", "failedLibrary": "Impossibile caricare i libri della libreria!", "failedShelf": "Impossibile caricare i libri dello scaffale!", + "failedBooks": "", "activeFilters": "{{ count }} filtri attivi" }, "tooltip": { @@ -611,7 +612,12 @@ }, "table": { "bookCoverAlt": "Copertina libro", - "statusPrefix": "Stato: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Stato: {{ status }}", "locked": "Bloccato", "unlocked": "Sbloccato", "toast": { diff --git a/frontend/src/i18n/ja/book.json b/frontend/src/i18n/ja/book.json index 992bbd9c5..1ac5e3ce4 100644 --- a/frontend/src/i18n/ja/book.json +++ b/frontend/src/i18n/ja/book.json @@ -48,6 +48,7 @@ "noBooks": "このコレクションには本がありません!", "failedLibrary": "ライブラリの本の読み込みに失敗しました!", "failedShelf": "シェルフの本の読み込みに失敗しました!", + "failedBooks": "", "activeFilters": "{{ count }}件のアクティブフィルター" }, "tooltip": { @@ -611,7 +612,12 @@ }, "table": { "bookCoverAlt": "ブックカバー", - "statusPrefix": "状態: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "状態: {{ status }}", "locked": "ロック済み", "unlocked": "ロック解除", "toast": { diff --git a/frontend/src/i18n/nl/book.json b/frontend/src/i18n/nl/book.json index 3d9351bd8..459613234 100644 --- a/frontend/src/i18n/nl/book.json +++ b/frontend/src/i18n/nl/book.json @@ -48,6 +48,7 @@ "noBooks": "", "failedLibrary": "", "failedShelf": "", + "failedBooks": "", "activeFilters": "{{ count }} Actieve filters" }, "tooltip": { @@ -614,7 +615,12 @@ }, "table": { "bookCoverAlt": "", - "statusPrefix": "", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "{{ status }}", "locked": "", "unlocked": "", "toast": { diff --git a/frontend/src/i18n/pl/book.json b/frontend/src/i18n/pl/book.json index 3ab3f3cbe..0abdcb7d6 100644 --- a/frontend/src/i18n/pl/book.json +++ b/frontend/src/i18n/pl/book.json @@ -48,6 +48,7 @@ "noBooks": "Ta kolekcja nie zawiera książek!", "failedLibrary": "Nie udało się załadować książek biblioteki!", "failedShelf": "Nie udało się załadować książek półki!", + "failedBooks": "", "activeFilters": "{{ count }} aktywnych filtrów" }, "tooltip": { @@ -611,7 +612,12 @@ }, "table": { "bookCoverAlt": "Okładka książki", - "statusPrefix": "Status: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Status: {{ status }}", "locked": "Zablokowane", "unlocked": "Odblokowane", "toast": { diff --git a/frontend/src/i18n/pt/book.json b/frontend/src/i18n/pt/book.json index 08b7dfed7..409526e1c 100644 --- a/frontend/src/i18n/pt/book.json +++ b/frontend/src/i18n/pt/book.json @@ -48,6 +48,7 @@ "noBooks": "Esta coleção não possui livros!", "failedLibrary": "Falha ao carregar os livros da biblioteca!", "failedShelf": "Falha ao carregar os livros da prateleira!", + "failedBooks": "", "activeFilters": "{{ count }} Filtros Ativos" }, "tooltip": { @@ -611,7 +612,12 @@ }, "table": { "bookCoverAlt": "Capa do Livro", - "statusPrefix": "Status: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Status: {{ status }}", "locked": "Bloqueado", "unlocked": "Desbloqueado", "toast": { diff --git a/frontend/src/i18n/ru/book.json b/frontend/src/i18n/ru/book.json index 12067207b..79e93f8a8 100644 --- a/frontend/src/i18n/ru/book.json +++ b/frontend/src/i18n/ru/book.json @@ -48,6 +48,7 @@ "noBooks": "В этой коллекции нет книг!", "failedLibrary": "Не удалось загрузить книги библиотеки!", "failedShelf": "Не удалось загрузить книги полки!", + "failedBooks": "", "activeFilters": "{{ count }} активных фильтров" }, "tooltip": { @@ -611,7 +612,12 @@ }, "table": { "bookCoverAlt": "Обложка книги", - "statusPrefix": "Статус: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Статус: {{ status }}", "locked": "Заблокировано", "unlocked": "Разблокировано", "toast": { diff --git a/frontend/src/i18n/sk/book.json b/frontend/src/i18n/sk/book.json index 43c3d9720..aee3e1532 100644 --- a/frontend/src/i18n/sk/book.json +++ b/frontend/src/i18n/sk/book.json @@ -48,6 +48,7 @@ "noBooks": "", "failedLibrary": "", "failedShelf": "", + "failedBooks": "", "activeFilters": "" }, "tooltip": { @@ -611,7 +612,12 @@ }, "table": { "bookCoverAlt": "", - "statusPrefix": "", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "{{ status }}", "locked": "", "unlocked": "", "toast": { diff --git a/frontend/src/i18n/sl/book.json b/frontend/src/i18n/sl/book.json index 70264cfd8..858a7f955 100644 --- a/frontend/src/i18n/sl/book.json +++ b/frontend/src/i18n/sl/book.json @@ -48,6 +48,7 @@ "noBooks": "Ta zbirka nima knjig!", "failedLibrary": "Napaka pri nalaganju knjig iz knjižnice!", "failedShelf": "Napaka pri nalaganju knjig s police!", + "failedBooks": "", "activeFilters": "{{ count }} aktivnih filtrov" }, "tooltip": { @@ -619,7 +620,12 @@ }, "table": { "bookCoverAlt": "Naslovnica knjige", - "statusPrefix": "Status: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Status: {{ status }}", "locked": "Zaklenjeno", "unlocked": "Odklenjeno", "toast": { diff --git a/frontend/src/i18n/sv/book.json b/frontend/src/i18n/sv/book.json index f6d7ec093..27a64fa5f 100644 --- a/frontend/src/i18n/sv/book.json +++ b/frontend/src/i18n/sv/book.json @@ -48,6 +48,7 @@ "noBooks": "Denna samling har inga böcker!", "failedLibrary": "Kunde inte ladda bibliotekets böcker!", "failedShelf": "Kunde inte ladda hyllans böcker!", + "failedBooks": "", "activeFilters": "{{ count }} aktiva filter" }, "tooltip": { @@ -619,7 +620,12 @@ }, "table": { "bookCoverAlt": "Bokomslag", - "statusPrefix": "Status: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Status: {{ status }}", "locked": "Låst", "unlocked": "Upplåst", "toast": { diff --git a/frontend/src/i18n/uk/book.json b/frontend/src/i18n/uk/book.json index 497d32900..2ff2224d0 100644 --- a/frontend/src/i18n/uk/book.json +++ b/frontend/src/i18n/uk/book.json @@ -48,6 +48,7 @@ "noBooks": "У цій колекції немає книг!", "failedLibrary": "Не вдалося завантажити книги з бібліотеки!", "failedShelf": "Не вдалося завантажити книги з полиці!", + "failedBooks": "", "activeFilters": "{{ count }} активних фільтрів" }, "tooltip": { @@ -619,7 +620,12 @@ }, "table": { "bookCoverAlt": "Обкладинка книги", - "statusPrefix": "Статус: ", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "Статус: {{ status }}", "locked": "Заблоковано", "unlocked": "Розблоковано", "toast": { diff --git a/frontend/src/i18n/zh/book.json b/frontend/src/i18n/zh/book.json index dcb20d177..332e59c3c 100644 --- a/frontend/src/i18n/zh/book.json +++ b/frontend/src/i18n/zh/book.json @@ -48,6 +48,7 @@ "noBooks": "此集合没有图书!", "failedLibrary": "加载书库图书失败!", "failedShelf": "加载书架图书失败!", + "failedBooks": "", "activeFilters": "{{ count }} 个活跃筛选条件" }, "tooltip": { @@ -612,7 +613,12 @@ }, "table": { "bookCoverAlt": "图书封面", - "statusPrefix": "状态:", + "label": "", + "selectBook": "", + "selectBookFallback": "", + "noRating": "", + "ratingOutOf": "", + "statusWithPrefix": "状态:{{ status }}", "locked": "已锁定", "unlocked": "已解锁", "toast": { diff --git a/frontend/yarn.lock b/frontend/yarn.lock index e713589d0..474084978 100644 --- a/frontend/yarn.lock +++ b/frontend/yarn.lock @@ -3693,6 +3693,18 @@ __metadata: languageName: node linkType: hard +"@tanstack/angular-table@npm:^8.21.4": + version: 8.21.4 + resolution: "@tanstack/angular-table@npm:8.21.4" + dependencies: + "@tanstack/table-core": "npm:8.21.3" + tslib: "npm:^2.6.2" + peerDependencies: + "@angular/core": ">=17" + checksum: 10c0/5bac4e850b04b25dca98ce37356d9ae431bf8b22a983988ebf6251636c9cb2d7f7cd0949d036c75a60383926987d87d0e53c229b8c1114c3cba9ccaf61705e07 + languageName: node + linkType: hard + "@tanstack/angular-virtual@npm:^4.0.13": version: 4.0.13 resolution: "@tanstack/angular-virtual@npm:4.0.13" @@ -3719,6 +3731,13 @@ __metadata: languageName: node linkType: hard +"@tanstack/table-core@npm:8.21.3": + version: 8.21.3 + resolution: "@tanstack/table-core@npm:8.21.3" + checksum: 10c0/40e3560e6d55e07cc047024aa7f83bd47a9323d21920d4adabba8071fd2d21230c48460b26cedf392588f8265b9edc133abb1b0d6d0adf4dae0970032900a8c9 + languageName: node + linkType: hard + "@tanstack/virtual-core@npm:3.14.0": version: 3.14.0 resolution: "@tanstack/virtual-core@npm:3.14.0" @@ -6129,6 +6148,7 @@ __metadata: "@stomp/rx-stomp": "npm:^2.3.0" "@stomp/stompjs": "npm:^7.3.0" "@tanstack/angular-query-experimental": "npm:5.100.1" + "@tanstack/angular-table": "npm:^8.21.4" "@tanstack/angular-virtual": "npm:^4.0.13" "@testing-library/angular": "npm:^19.2.1" "@testing-library/dom": "npm:^10.4.1" @@ -9034,7 +9054,7 @@ __metadata: languageName: node linkType: hard -"tslib@npm:^2.1.0, tslib@npm:^2.2.0, tslib@npm:^2.3.0, tslib@npm:^2.3.1, tslib@npm:^2.4.0, tslib@npm:^2.8.1": +"tslib@npm:^2.1.0, tslib@npm:^2.2.0, tslib@npm:^2.3.0, tslib@npm:^2.3.1, tslib@npm:^2.4.0, tslib@npm:^2.6.2, tslib@npm:^2.8.1": version: 2.8.1 resolution: "tslib@npm:2.8.1" checksum: 10c0/9c4759110a19c53f992d9aae23aac5ced636e99887b51b9e61def52611732872ff7668757d4e4c61f19691e36f4da981cd9485e869b4a7408d689f6bf1f14e62