From 05de312518d50e9357cc0534f7865d0e8a33ea36 Mon Sep 17 00:00:00 2001 From: Alex <25013571+alexhb1@users.noreply.github.com> Date: Thu, 4 Jun 2026 07:33:34 +0100 Subject: [PATCH] refactor(ui): convert book details tab state to signals (#1629) --- .../metadata-tabs.component.html | 166 ++++++++---------- .../metadata-tabs.component.spec.ts | 12 +- .../metadata-tabs/metadata-tabs.component.ts | 148 +++++++++------- 3 files changed, 168 insertions(+), 158 deletions(-) diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html index e6a983c5d..16cbf2b82 100644 --- a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html @@ -1,47 +1,27 @@ - +@let currentBook = book(); +@let seriesBooks = bookInSeries(); +@let recommendations = recommendedBooks(); +@let currentAudiobookInfo = audiobookInfo(); +@let currentFileState = fileState(); + - @if (hasSeries) { - - {{ t('moreInSeries') }} + @for (tab of availableTabs(); track tab.value) { + + {{ t(tab.labelKey) }} } - - {{ t('similarBooks') }} - - @if (supportsDualCovers()) { - - {{ t('covers') }} - - } - @if (hasAudiobookFormat()) { - - {{ t('chapters') }} - - } - - {{ t('files') }} - - - {{ t('notes') }} - - - {{ t('readingSessions') }} - - - {{ t('reviews') }} -
- @if (bookInSeries.length > 1) { + @if (seriesBooks.length > 1) {
- @for (bookInSeriesItem of bookInSeries; track bookInSeriesItem.id) { - @if (bookInSeriesItem.id !== book.id) { + @for (bookInSeriesItem of seriesBooks; track bookInSeriesItem.id) { + @if (bookInSeriesItem.id !== currentBook.id) {
- +
} } @@ -53,9 +33,9 @@
- @if (recommendedBooks.length > 0) { + @if (recommendations.length > 0) {
- @for (recBook of recommendedBooks; track recBook.book.id) { + @for (recBook of recommendations; track recBook.book.id) {
@@ -73,7 +53,7 @@
{{ t('ebookCover') }}
- @if (urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn); as coverUrl) { + @if (urlHelper.getCoverUrl(currentBook.id, currentBook.metadata?.coverUpdatedOn); as coverUrl) { } @else { - + }
{{ t('audiobookCover') }}
- @if (urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn); as coverUrl) { + @if (urlHelper.getAudiobookCoverUrl(currentBook.id, currentBook.metadata?.audiobookCoverUpdatedOn); as coverUrl) { } @else { - + }
@@ -108,45 +88,45 @@
- + - + - +
- @if (chaptersLoading) { + @if (chaptersLoading()) {
- } @else if (audiobookInfo) { + } @else if (currentAudiobookInfo) {
- {{ formatDuration(audiobookInfo.durationMs) }} + {{ formatDuration(currentAudiobookInfo.durationMs) }} - @if (audiobookInfo.codec) { - {{ audiobookInfo.codec.toUpperCase() }} + @if (currentAudiobookInfo.codec) { + {{ currentAudiobookInfo.codec.toUpperCase() }} } - @if (audiobookInfo.bitrate) { - {{ audiobookInfo.bitrate }} kbps + @if (currentAudiobookInfo.bitrate) { + {{ currentAudiobookInfo.bitrate }} kbps } - @if (audiobookInfo.sampleRate) { - {{ formatSampleRate(audiobookInfo.sampleRate) }} + @if (currentAudiobookInfo.sampleRate) { + {{ formatSampleRate(currentAudiobookInfo.sampleRate) }} } - @if (audiobookInfo.channels) { - {{ getChannelLabel(audiobookInfo.channels) }} + @if (currentAudiobookInfo.channels) { + {{ getChannelLabel(currentAudiobookInfo.channels) }} }
- @if (audiobookInfo.folderBased && audiobookInfo.tracks?.length) { + @if (currentAudiobookInfo.folderBased && currentAudiobookInfo.tracks?.length) {
@@ -159,7 +139,7 @@ - @for (track of audiobookInfo.tracks; track track.index) { + @for (track of currentAudiobookInfo.tracks; track track.index) { @@ -171,7 +151,7 @@
{{ track.index + 1 }} {{ track.title }}
- } @else if (audiobookInfo.chapters?.length) { + } @else if (currentAudiobookInfo.chapters?.length) {
@@ -184,7 +164,7 @@ - @for (chapter of audiobookInfo.chapters; track chapter.index) { + @for (chapter of currentAudiobookInfo.chapters; track chapter.index) { @@ -208,7 +188,7 @@
- @if (isPhysicalBook()) { + @if (currentFileState.isPhysical) {

{{ t('physicalBookTitle') }}

@@ -216,33 +196,33 @@

{{ t('physicalBookHint') }}

} @else { - @if (hasMultipleFiles(book)) { + @if (currentFileState.hasMultipleContentFiles) {
} - @if (book.primaryFile) { + @if (currentBook.primaryFile) {

{{ t('primaryFile') }}

- - {{ book.primaryFile.extension | uppercase }} + + {{ currentBook.primaryFile.extension | uppercase }} - {{ book.primaryFile.fileName }} - {{ getFileSizeInMB(book.primaryFile) }} + {{ currentBook.primaryFile.fileName }} + {{ getFileSizeInMB(currentBook.primaryFile) }}
- @if (book.primaryFile.bookType === 'EPUB') { + @if (currentBook.primaryFile.bookType === 'EPUB') { + (onClick)="read(currentBook.id)"> + (onClick)="read(currentBook.id, 'epub-streaming')"> - } @else if (book.primaryFile.bookType && ['PDF', 'FB2', 'MOBI', 'AZW3', 'CBX'].includes(book.primaryFile.bookType)) { + } @else if (currentBook.primaryFile.bookType && ['PDF', 'FB2', 'MOBI', 'AZW3', 'CBX'].includes(currentBook.primaryFile.bookType)) { + (onClick)="read(currentBook.id)"> - } @else if (book.primaryFile.bookType === 'AUDIOBOOK') { + } @else if (currentBook.primaryFile.bookType === 'AUDIOBOOK') { + (onClick)="read(currentBook.id)"> } + (onClick)="download(currentBook)"> - @if (canDetach(book)) { + @if (currentFileState.canDetach) { + (onClick)="detachFile(currentBook, currentBook.primaryFile!.id, currentBook.primaryFile!.fileName || 'file')"> } + (onClick)="deleteFile(currentBook, currentBook.primaryFile!.id, currentBook.primaryFile!.fileName || 'file', true)">
} - @if (book.alternativeFormats && book.alternativeFormats.length > 0) { + @if (currentBook.alternativeFormats && currentBook.alternativeFormats.length > 0) {

{{ t('alternativeFormats') }}

- @for (format of book.alternativeFormats; track format.id) { + @for (format of currentBook.alternativeFormats; track format.id) {
@@ -338,7 +318,7 @@ severity="primary" [pTooltip]="t('readTooltip')" tooltipPosition="top" - (onClick)="read(book.id, undefined, format.bookType)"> + (onClick)="read(currentBook.id, undefined, format.bookType)"> + (onClick)="read(currentBook.id, 'epub-streaming', format.bookType)"> } @else if (format.bookType && ['PDF', 'FB2', 'MOBI', 'AZW3', 'CBX'].includes(format.bookType)) { + (onClick)="read(currentBook.id, undefined, format.bookType)"> } @else if (format.bookType === 'AUDIOBOOK') { + (onClick)="read(currentBook.id, undefined, format.bookType)"> } + (onClick)="downloadAdditionalFile(currentBook, format.id)"> - @if (canDetach(book)) { + @if (currentFileState.canDetach) { + (onClick)="detachFile(currentBook, format.id, format.fileName || 'file')"> } + (onClick)="deleteFile(currentBook, format.id, format.fileName || 'file', false)">
@@ -405,11 +385,11 @@
} - @if (book.supplementaryFiles && book.supplementaryFiles.length > 0) { + @if (currentBook.supplementaryFiles && currentBook.supplementaryFiles.length > 0) {

{{ t('supplementaryFiles') }}

- @for (file of book.supplementaryFiles; track file.id) { + @for (file of currentBook.supplementaryFiles; track file.id) {
@@ -424,9 +404,9 @@ severity="success" [pTooltip]="t('downloadTooltip')" tooltipPosition="top" - (onClick)="downloadAdditionalFile(book, file.id)"> + (onClick)="downloadAdditionalFile(currentBook, file.id)"> - @if (canDetach(book)) { + @if (currentFileState.canDetach) { + (onClick)="detachFile(currentBook, file.id, file.fileName || 'file')"> } + (onClick)="deleteSupplementary(currentBook.id, file.id, file.fileName || 'file')">
diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts index 2665f116a..30e17159a 100644 --- a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.spec.ts @@ -29,23 +29,23 @@ describe('MetadataTabsComponent default tab selection', () => { getTranslocoModule({translocoConfig: {reRenderOnLangChange: false}}), ], providers: [ - {provide: UrlHelperService, useValue: {}}, + {provide: UrlHelperService, useValue: {getCoverUrl: () => null, getAudiobookCoverUrl: () => null}}, {provide: BookMetadataManageService, useValue: {supportsDualCovers: () => false}}, {provide: AudiobookService, useValue: {getAudiobookInfo: () => undefined}}, ], }); const fixture = TestBed.createComponent(MetadataTabsComponent); - fixture.componentInstance.book = { + fixture.componentRef.setInput('book', { id: 21, libraryId: 1, libraryName: 'Library', metadata: {bookId: 21, title: 'Test Book', authors: []}, alternativeFormats: [], supplementaryFiles: [], - } satisfies Book; - fixture.componentInstance.hasSeries = hasSeries; - fixture.componentInstance.bookInSeries = []; + } satisfies Book); + fixture.componentRef.setInput('hasSeries', hasSeries); + fixture.componentRef.setInput('bookInSeries', []); fixture.detectChanges(); return fixture; @@ -55,7 +55,7 @@ describe('MetadataTabsComponent default tab selection', () => { const fixture = createFixture(true); const component = fixture.componentInstance; - expect(component.defaultTabValue).toBe('series'); + expect(component.activeTab()).toBe('series'); }); }); diff --git a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts index 08bf30b4e..140df9248 100644 --- a/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts +++ b/frontend/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts @@ -1,5 +1,6 @@ -import {Component, EventEmitter, inject, Input, Output} from '@angular/core'; +import {ChangeDetectionStrategy, computed, Component, DestroyRef, effect, inject, input, linkedSignal, output, untracked} from '@angular/core'; import {UpperCasePipe} from '@angular/common'; +import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {Book, BookRecommendation, BookType, FileInfo} from '../../../../../book/model/book.model'; import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs'; import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; @@ -16,6 +17,7 @@ import {BookMetadataManageService} from '../../../../../book/service/book-metada import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; import {AudiobookService} from '../../../../../readers/audiobook-player/audiobook.service'; import {AudiobookInfo} from '../../../../../readers/audiobook-player/audiobook.model'; +import {finalize} from 'rxjs/operators'; export interface ReadEvent { bookId: number; @@ -56,9 +58,19 @@ export interface DetachBookFileEvent { fileName: string; } +type MetadataTabValue = 'series' | 'similar' | 'covers' | 'chapters' | 'files' | 'notes' | 'sessions' | 'reviews'; +interface MetadataTab { + value: MetadataTabValue; + icon: string; + labelKey: string; +} + +const metadataTab = (value: MetadataTabValue, icon: string, labelKey: string): MetadataTab => ({value, icon, labelKey}); + @Component({ selector: 'app-metadata-tabs', standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, imports: [ Tab, TabList, @@ -81,29 +93,73 @@ export interface DetachBookFileEvent { styleUrl: './metadata-tabs.component.scss' }) export class MetadataTabsComponent { - @Input() book!: Book; - @Input() bookInSeries: Book[] = []; - @Input() hasSeries = false; - @Input() recommendedBooks: BookRecommendation[] = []; + readonly book = input.required(); + readonly bookInSeries = input([]); + readonly hasSeries = input(false); + readonly recommendedBooks = input([]); protected urlHelper = inject(UrlHelperService); private bookMetadataManageService = inject(BookMetadataManageService); private audiobookService = inject(AudiobookService); private t = inject(TranslocoService); + private destroyRef = inject(DestroyRef); - audiobookInfo: AudiobookInfo | null = null; - chaptersLoading = false; + readonly audiobookInfo = linkedSignal({ + source: () => this.book().id, + computation: () => null, + }); + readonly chaptersLoading = linkedSignal({ + source: () => this.book().id, + computation: () => false, + }); - @Output() readBook = new EventEmitter(); - @Output() downloadBook = new EventEmitter(); - @Output() downloadFile = new EventEmitter(); - @Output() downloadAllFiles = new EventEmitter(); - @Output() deleteBookFile = new EventEmitter(); - @Output() deleteSupplementaryFile = new EventEmitter(); - @Output() detachBookFile = new EventEmitter(); + readonly readBook = output(); + readonly downloadBook = output(); + readonly downloadFile = output(); + readonly downloadAllFiles = output(); + readonly deleteBookFile = output(); + readonly deleteSupplementaryFile = output(); + readonly detachBookFile = output(); - get defaultTabValue(): string { - return this.hasSeries ? 'series' : 'similar'; + readonly supportsDualCovers = computed(() => this.bookMetadataManageService.supportsDualCovers(this.book())); + readonly fileState = computed(() => { + const book = this.book(); + const contentFileCount = (book.primaryFile ? 1 : 0) + (book.alternativeFormats?.length ?? 0); + const allFileCount = contentFileCount + (book.supplementaryFiles?.length ?? 0); + + return { + canDetach: allFileCount > 1, + hasAudiobookFormat: book.primaryFile?.bookType === 'AUDIOBOOK' || book.alternativeFormats?.some(file => file.bookType === 'AUDIOBOOK') === true, + hasMultipleContentFiles: contentFileCount > 1, + isPhysical: contentFileCount === 0, + totalContentFiles: contentFileCount, + }; + }); + readonly availableTabs = computed(() => [ + ...(this.hasSeries() ? [metadataTab('series', 'pi pi-ethereum', 'moreInSeries')] : []), + metadataTab('similar', 'pi pi-bookmark', 'similarBooks'), + ...(this.supportsDualCovers() ? [metadataTab('covers', 'pi pi-images', 'covers')] : []), + ...(this.fileState().hasAudiobookFormat ? [metadataTab('chapters', 'pi pi-headphones', 'chapters')] : []), + metadataTab('files', 'pi pi-folder-open', 'files'), + metadataTab('notes', 'pi pi-pen-to-square', 'notes'), + metadataTab('sessions', 'pi pi-clock', 'readingSessions'), + metadataTab('reviews', 'pi pi-comments', 'reviews'), + ]); + readonly activeTab = linkedSignal({ + source: this.availableTabs, + computation: (availableTabs, previous) => + previous && availableTabs.some(tab => tab.value === previous.value) + ? previous.value + : availableTabs[0]?.value ?? 'similar', + }); + + constructor() { + effect(() => { + const bookId = this.book().id; + if (this.activeTab() === 'chapters') { + untracked(() => this.loadChapters(bookId)); + } + }); } read(bookId: number, reader?: 'epub-streaming', bookType?: BookType): void { @@ -135,25 +191,6 @@ export class MetadataTabsComponent { this.detachBookFile.emit({ book, fileId, fileName }); } - canDetach(book: Book): boolean { - const totalFiles = (book.primaryFile ? 1 : 0) - + (book.alternativeFormats?.length ?? 0) - + (book.supplementaryFiles?.length ?? 0); - return totalFiles > 1; - } - - hasMultipleFiles(book: Book): boolean { - const primaryCount = book.primaryFile ? 1 : 0; - const altCount = book.alternativeFormats?.length ?? 0; - return (primaryCount + altCount) > 1; - } - - getTotalFileCount(book: Book): number { - const primaryCount = book.primaryFile ? 1 : 0; - const altCount = book.alternativeFormats?.length ?? 0; - return primaryCount + altCount; - } - getFileSizeInMB(fileInfo: FileInfo | null | undefined): string { const sizeKb = fileInfo?.fileSizeKb; return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-'; @@ -196,36 +233,29 @@ export class MetadataTabsComponent { return `var(--book-type-${type}-color, var(--p-gray-500))`; } - isPhysicalBook(): boolean { - return !this.book?.primaryFile && (!this.book?.alternativeFormats || this.book.alternativeFormats.length === 0); - } - - supportsDualCovers(): boolean { - return this.bookMetadataManageService.supportsDualCovers(this.book); - } - onTabChange(value: string | number | undefined): void { - if (value === 'chapters') { - this.loadChapters(); + if (typeof value === 'string' && this.availableTabs().some(tab => tab.value === value)) { + this.activeTab.set(value as MetadataTabValue); } } - hasAudiobookFormat(): boolean { - const allFiles = [this.book.primaryFile, ...(this.book.alternativeFormats || [])].filter(f => f?.bookType); - return allFiles.some(f => f!.bookType === 'AUDIOBOOK'); - } - - loadChapters(): void { - if (this.audiobookInfo || this.chaptersLoading) return; - this.chaptersLoading = true; - this.audiobookService.getAudiobookInfo(this.book.id).subscribe({ + loadChapters(bookId = this.book().id): void { + if (this.audiobookInfo() || this.chaptersLoading()) return; + this.chaptersLoading.set(true); + this.audiobookService.getAudiobookInfo(bookId).pipe( + takeUntilDestroyed(this.destroyRef), + finalize(() => { + if (this.book().id === bookId) { + this.chaptersLoading.set(false); + } + }) + ).subscribe({ next: info => { - this.audiobookInfo = info; - this.chaptersLoading = false; + if (this.book().id === bookId) { + this.audiobookInfo.set(info); + } }, - error: () => { - this.chaptersLoading = false; - } + error: () => undefined }); }
{{ chapter.index + 1 }} {{ chapter.title }}