fix(ui): convert book metadata suggestions to signals (#1583)
This commit is contained in:
@@ -136,7 +136,7 @@ export class BookService {
|
||||
});
|
||||
}
|
||||
|
||||
private getBookRecommendationsQueryOptions(bookId: number, limit: number) {
|
||||
bookRecommendationsQueryOptions(bookId: number, limit: number) {
|
||||
return queryOptions({
|
||||
queryKey: bookRecommendationsQueryKey(bookId, limit),
|
||||
queryFn: () => lastValueFrom(this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
|
||||
@@ -183,7 +183,7 @@ export class BookService {
|
||||
}
|
||||
|
||||
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
|
||||
return from(this.queryClient.ensureQueryData(this.getBookRecommendationsQueryOptions(bookId, limit)));
|
||||
return from(this.queryClient.ensureQueryData(this.bookRecommendationsQueryOptions(bookId, limit)));
|
||||
}
|
||||
|
||||
/*------------------ Book Operations ------------------*/
|
||||
|
||||
+5
-5
@@ -25,13 +25,13 @@
|
||||
<i [class]="'pi pi-book'"></i>
|
||||
{{ t('tabView') }}
|
||||
</p-tab>
|
||||
@if (admin || canEditMetadata) {
|
||||
@if (admin() || canEditMetadata()) {
|
||||
<p-tab value="edit">
|
||||
<i [class]="'pi pi-pencil'"></i>
|
||||
{{ t('tabEdit') }}
|
||||
</p-tab>
|
||||
}
|
||||
@if (admin || canEditMetadata) {
|
||||
@if (admin() || canEditMetadata()) {
|
||||
<p-tab value="match">
|
||||
<i [class]="'pi pi-search'"></i>
|
||||
{{ t('tabSearch') }}
|
||||
@@ -48,17 +48,17 @@
|
||||
<p-tabpanel value="view">
|
||||
<app-metadata-viewer
|
||||
[book]="book()"
|
||||
[recommendedBooks]="recommendedBooks">
|
||||
[recommendedBooks]="recommendedBooks()">
|
||||
</app-metadata-viewer>
|
||||
</p-tabpanel>
|
||||
@if (admin || canEditMetadata) {
|
||||
@if (admin() || canEditMetadata()) {
|
||||
<p-tabpanel value="edit">
|
||||
<app-metadata-editor
|
||||
[book]="book()">
|
||||
</app-metadata-editor>
|
||||
</p-tabpanel>
|
||||
}
|
||||
@if (admin || canEditMetadata) {
|
||||
@if (admin() || canEditMetadata()) {
|
||||
<p-tabpanel value="match">
|
||||
<app-metadata-searcher [book]="book()" [isActiveTab]="tab === 'match'"></app-metadata-searcher>
|
||||
</p-tabpanel>
|
||||
|
||||
+26
-35
@@ -1,4 +1,4 @@
|
||||
import {computed, Component, effect, inject, OnDestroy, OnInit, signal} from '@angular/core';
|
||||
import {computed, Component, inject, OnDestroy, OnInit, signal} from '@angular/core';
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {Book, BookRecommendation} from '../../../book/model/book.model';
|
||||
@@ -15,7 +15,8 @@ import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.compone
|
||||
import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component';
|
||||
import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component';
|
||||
import {SidecarViewerComponent} from './sidecar-viewer/sidecar-viewer.component';
|
||||
import {injectQuery} from '@tanstack/angular-query-experimental';
|
||||
import {injectQuery, queryOptions} from '@tanstack/angular-query-experimental';
|
||||
import {bookRecommendationsQueryKey} from '../../../book/service/book-query-keys';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-metadata-center',
|
||||
@@ -64,33 +65,41 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
||||
return this.bookService.bookDetailQueryOptions(bookId, true);
|
||||
});
|
||||
readonly book = computed(() => this.bookQuery.data() ?? null);
|
||||
private readonly fetchRecommendations = effect(() => {
|
||||
private readonly recommendationsQuery = injectQuery(() => {
|
||||
const bookId = this.currentBookId();
|
||||
if (bookId == null) {
|
||||
this.recommendedBooks = [];
|
||||
return;
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
|
||||
if (bookId == null || !(settings?.similarBookRecommendation ?? false)) {
|
||||
return queryOptions({
|
||||
queryKey: bookRecommendationsQueryKey(-1, 20),
|
||||
queryFn: async (): Promise<BookRecommendation[]> => [],
|
||||
enabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
this.fetchBookRecommendationsIfNeeded(bookId);
|
||||
return this.bookService.bookRecommendationsQueryOptions(bookId, 20);
|
||||
});
|
||||
|
||||
recommendedBooks: BookRecommendation[] = [];
|
||||
readonly recommendedBooks = computed(() =>
|
||||
[...(this.recommendationsQuery.data() ?? [])].sort(
|
||||
(a, b) => (b.similarityScore ?? 0) - (a.similarityScore ?? 0)
|
||||
)
|
||||
);
|
||||
private _tab: string = 'view';
|
||||
canEditMetadata: boolean = false;
|
||||
admin: boolean = false;
|
||||
private readonly syncUserPermissionsEffect = effect(() => {
|
||||
readonly canEditMetadata = computed(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (!user) return;
|
||||
this.canEditMetadata = user.permissions?.canEditMetadata ?? false;
|
||||
this.admin = user.permissions?.admin ?? false;
|
||||
return user?.permissions?.canEditMetadata ?? false;
|
||||
});
|
||||
readonly admin = computed(() => {
|
||||
const user = this.userService.currentUser();
|
||||
return user?.permissions?.admin ?? false;
|
||||
});
|
||||
get isPhysical(): boolean { return this.book()?.isPhysical ?? false; }
|
||||
isLocalStorage: boolean = true;
|
||||
readonly isLocalStorage = computed(() => this.appSettingsService.appSettings()?.diskType === 'LOCAL');
|
||||
get canShowSidecarTab(): boolean {
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
const sidecarEnabled = settings?.metadataPersistenceSettings?.sidecarSettings?.enabled ?? false;
|
||||
|
||||
return (this.admin || this.canEditMetadata) && !this.isPhysical && this.isLocalStorage && sidecarEnabled;
|
||||
return (this.admin() || this.canEditMetadata()) && !this.isPhysical && this.isLocalStorage() && sidecarEnabled;
|
||||
}
|
||||
private validTabs = ['view', 'edit', 'match', 'sidecar'];
|
||||
|
||||
@@ -142,24 +151,6 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
||||
this._tab = this.validTabs.includes(tabParam) ? tabParam : 'view';
|
||||
});
|
||||
|
||||
const currentSettings = this.appSettingsService.appSettings();
|
||||
if (currentSettings) {
|
||||
this.isLocalStorage = currentSettings.diskType === 'LOCAL';
|
||||
}
|
||||
}
|
||||
|
||||
private fetchBookRecommendationsIfNeeded(bookId: number): void {
|
||||
const settings = this.appSettingsService.appSettings();
|
||||
if (!settings || !(settings.similarBookRecommendation ?? false)) {
|
||||
return;
|
||||
}
|
||||
this.bookService.getBookRecommendations(bookId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(recommendations => {
|
||||
this.recommendedBooks = recommendations.sort(
|
||||
(a, b) => (b.similarityScore ?? 0) - (a.similarityScore ?? 0)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
<ng-container *transloco="let t; prefix: 'metadata.tabs'">
|
||||
<p-tabs lazy class="custom-p-tabs" [value]="defaultTabValue" scrollable (valueChange)="onTabChange($event)">
|
||||
<p-tablist>
|
||||
@if (bookInSeries.length > 1) {
|
||||
@if (hasSeries) {
|
||||
<p-tab value="series">
|
||||
<i class="pi pi-ethereum"></i> {{ t('moreInSeries') }}
|
||||
</p-tab>
|
||||
|
||||
+60
-1
@@ -1,4 +1,63 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
import {ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {AudiobookService} from '../../../../../readers/audiobook-player/audiobook.service';
|
||||
import {BookMetadataManageService} from '../../../../../book/service/book-metadata-manage.service';
|
||||
import {UrlHelperService} from '../../../../../../shared/service/url-helper.service';
|
||||
import {MetadataTabsComponent} from './metadata-tabs.component';
|
||||
import {Book} from '../../../../../book/model/book.model';
|
||||
import {getTranslocoModule} from '../../../../../../core/testing/transloco-testing';
|
||||
|
||||
describe('MetadataTabsComponent default tab selection', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', class {
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
function createFixture(hasSeries = false): ComponentFixture<MetadataTabsComponent> {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [
|
||||
MetadataTabsComponent,
|
||||
getTranslocoModule({translocoConfig: {reRenderOnLangChange: false}}),
|
||||
],
|
||||
providers: [
|
||||
{provide: UrlHelperService, useValue: {}},
|
||||
{provide: BookMetadataManageService, useValue: {supportsDualCovers: () => false}},
|
||||
{provide: AudiobookService, useValue: {getAudiobookInfo: () => undefined}},
|
||||
],
|
||||
});
|
||||
|
||||
const fixture = TestBed.createComponent(MetadataTabsComponent);
|
||||
fixture.componentInstance.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 = [];
|
||||
fixture.detectChanges();
|
||||
|
||||
return fixture;
|
||||
}
|
||||
|
||||
it('selects the series tab from book metadata before series contents load', () => {
|
||||
const fixture = createFixture(true);
|
||||
const component = fixture.componentInstance;
|
||||
|
||||
expect(component.defaultTabValue).toBe('series');
|
||||
});
|
||||
});
|
||||
|
||||
// TODO(seam): This tab surface coordinates nested review, notes, reading-session, and
|
||||
// audiobook child components, so it needs an integration harness around real tab changes.
|
||||
|
||||
+2
-1
@@ -83,6 +83,7 @@ export interface DetachBookFileEvent {
|
||||
export class MetadataTabsComponent {
|
||||
@Input() book!: Book;
|
||||
@Input() bookInSeries: Book[] = [];
|
||||
@Input() hasSeries = false;
|
||||
@Input() recommendedBooks: BookRecommendation[] = [];
|
||||
|
||||
protected urlHelper = inject(UrlHelperService);
|
||||
@@ -102,7 +103,7 @@ export class MetadataTabsComponent {
|
||||
@Output() detachBookFile = new EventEmitter<DetachBookFileEvent>();
|
||||
|
||||
get defaultTabValue(): string {
|
||||
return this.bookInSeries && this.bookInSeries.length > 1 ? 'series' : 'similar';
|
||||
return this.hasSeries ? 'series' : 'similar';
|
||||
}
|
||||
|
||||
read(bookId: number, reader?: 'epub-streaming', bookType?: BookType): void {
|
||||
|
||||
+2
-1
@@ -958,7 +958,8 @@
|
||||
<app-metadata-tabs
|
||||
[book]="book"
|
||||
[bookInSeries]="bookInSeries"
|
||||
[recommendedBooks]="recommendedBooks"
|
||||
[hasSeries]="!!book.metadata?.seriesName"
|
||||
[recommendedBooks]="filteredRecommendedBooks()"
|
||||
(readBook)="onReadBook($event)"
|
||||
(downloadBook)="onDownloadBook($event)"
|
||||
(downloadFile)="onDownloadFile($event)"
|
||||
|
||||
+17
-3
@@ -256,7 +256,7 @@ describe('MetadataViewerComponent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('filters series recommendations and builds the read, download, and other menus from the current book', () => {
|
||||
it('filters series recommendations and builds the read, download, and other menus from the current book', async () => {
|
||||
const component = createComponent();
|
||||
const seriesBooks = [
|
||||
{id: 8, metadata: {seriesNumber: 2}},
|
||||
@@ -310,8 +310,10 @@ describe('MetadataViewerComponent', () => {
|
||||
|
||||
component.book = richBook;
|
||||
|
||||
expect(component.bookInSeries.map(book => book.id)).toEqual([4, 8]);
|
||||
expect(component.recommendedBooks.map(book => book.book.id)).toEqual([17]);
|
||||
await vi.waitFor(() => {
|
||||
expect(component.bookInSeries.map(book => book.id)).toEqual([4, 8]);
|
||||
});
|
||||
expect(component.filteredRecommendedBooks().map(book => book.book.id)).toEqual([17]);
|
||||
|
||||
const readItems = component.readMenuItems();
|
||||
expect(readItems.map(item => item.separator ? 'separator' : item.label)).toEqual([
|
||||
@@ -374,6 +376,18 @@ describe('MetadataViewerComponent', () => {
|
||||
expect(confirm).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('falls back to an empty series list when the series lookup fails', async () => {
|
||||
const component = createComponent();
|
||||
getBooksInSeries.mockReturnValueOnce(throwError(() => new Error('series failed')));
|
||||
|
||||
component.book = createBook({}, {bookId: 21, seriesName: 'Series One'});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(getBooksInSeries).toHaveBeenCalledWith(21);
|
||||
});
|
||||
expect(component.bookInSeries).toEqual([]);
|
||||
});
|
||||
|
||||
it('chooses confirmation copy for file deletion branches and runs the accept callbacks', () => {
|
||||
const component = createComponent();
|
||||
const book = createBook();
|
||||
|
||||
+38
-35
@@ -1,4 +1,4 @@
|
||||
import {AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, Input, OnChanges, OnInit, signal, SimpleChanges, ViewChild} from '@angular/core';
|
||||
import {AfterViewChecked, Component, computed, DestroyRef, ElementRef, inject, Input, OnInit, signal, ViewChild} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {DecimalPipe, NgClass} from '@angular/common';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
@@ -14,11 +14,12 @@ import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {EmailService} from '../../../../settings/email-v2/email.service';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
import {takeUntilDestroyed, toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||
import {ProgressBar} from 'primeng/progressbar';
|
||||
import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type.enum';
|
||||
import {Router} from '@angular/router';
|
||||
import {take, tap} from 'rxjs/operators';
|
||||
import {catchError, map, switchMap, take} from 'rxjs/operators';
|
||||
import {of} from 'rxjs';
|
||||
import {Menu} from 'primeng/menu';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||
import {DatePicker} from 'primeng/datepicker';
|
||||
@@ -48,8 +49,34 @@ import DOMPurify from 'dompurify';
|
||||
styleUrl: './metadata-viewer.component.scss',
|
||||
imports: [Button, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, MetadataTabsComponent, TranslocoDirective, TranslocoPipe, Dialog, Checkbox, CoverPlaceholderComponent]
|
||||
})
|
||||
export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChecked {
|
||||
export class MetadataViewerComponent implements OnInit, AfterViewChecked {
|
||||
private bookService = inject(BookService);
|
||||
private currentBook = signal<Book | null>(null);
|
||||
private readonly seriesLookupBookId = computed(() => {
|
||||
const metadata = this.currentBook()?.metadata;
|
||||
return metadata?.seriesName ? metadata.bookId : null;
|
||||
});
|
||||
private readonly bookInSeriesSignal = toSignal(
|
||||
toObservable(this.seriesLookupBookId).pipe(
|
||||
switchMap(bookId =>
|
||||
bookId == null
|
||||
? of([])
|
||||
: this.bookService.getBooksInSeries(bookId).pipe(
|
||||
catchError(() => of([]))
|
||||
)
|
||||
),
|
||||
map(series => [...series].sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0)))
|
||||
),
|
||||
{initialValue: []}
|
||||
);
|
||||
private readonly originalRecommendedBooks = signal<BookRecommendation[]>([]);
|
||||
readonly filteredRecommendedBooks = computed(() => {
|
||||
const bookInSeriesIds = new Set(this.bookInSeriesSignal().map(book => book.id));
|
||||
|
||||
return this.originalRecommendedBooks().filter(
|
||||
rec => !bookInSeriesIds.has(rec.book.id)
|
||||
);
|
||||
});
|
||||
|
||||
@Input()
|
||||
set book(value: Book | null) {
|
||||
@@ -60,7 +87,6 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
||||
}
|
||||
|
||||
this.isAutoFetching = false;
|
||||
this.loadBooksInSeriesAndFilterRecommended(value.metadata.bookId);
|
||||
this.selectedReadStatus = value.readStatus ?? ReadStatus.UNREAD;
|
||||
}
|
||||
|
||||
@@ -68,15 +94,16 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
||||
return this.currentBook();
|
||||
}
|
||||
|
||||
@Input() recommendedBooks: BookRecommendation[] = [];
|
||||
private originalRecommendedBooks: BookRecommendation[] = [];
|
||||
@Input()
|
||||
set recommendedBooks(value: BookRecommendation[]) {
|
||||
this.originalRecommendedBooks.set(value);
|
||||
}
|
||||
|
||||
private readonly t = inject(TranslocoService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private bookDialogHelperService = inject(BookDialogHelperService)
|
||||
private emailService = inject(EmailService);
|
||||
private messageService = inject(MessageService);
|
||||
private bookService = inject(BookService);
|
||||
private bookFileService = inject(BookFileService);
|
||||
private taskHelperService = inject(TaskHelperService);
|
||||
private authorService = inject(AuthorService);
|
||||
@@ -399,7 +426,9 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
||||
|
||||
return items;
|
||||
});
|
||||
bookInSeries: Book[] = [];
|
||||
get bookInSeries(): Book[] {
|
||||
return this.bookInSeriesSignal();
|
||||
}
|
||||
@ViewChild(Image) private coverImage?: Image;
|
||||
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
|
||||
isExpanded = false;
|
||||
@@ -460,32 +489,6 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['recommendedBooks']) {
|
||||
this.originalRecommendedBooks = [...this.recommendedBooks];
|
||||
this.filterRecommendations();
|
||||
}
|
||||
}
|
||||
|
||||
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
|
||||
this.bookService.getBooksInSeries(bookId).pipe(
|
||||
tap(series => {
|
||||
series.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
|
||||
this.bookInSeries = series;
|
||||
this.originalRecommendedBooks = [...this.recommendedBooks];
|
||||
}),
|
||||
takeUntilDestroyed(this.destroyRef)
|
||||
).subscribe(() => this.filterRecommendations());
|
||||
}
|
||||
|
||||
private filterRecommendations(): void {
|
||||
if (!this.originalRecommendedBooks) return;
|
||||
const bookInSeriesIds = new Set(this.bookInSeries.map(book => book.id));
|
||||
this.recommendedBooks = this.originalRecommendedBooks.filter(
|
||||
rec => !bookInSeriesIds.has(rec.book.id)
|
||||
);
|
||||
}
|
||||
|
||||
ngAfterViewChecked(): void {
|
||||
if (!this.isExpanded && this.descriptionContentRef) {
|
||||
const el = this.descriptionContentRef.nativeElement;
|
||||
|
||||
Reference in New Issue
Block a user