fix(loading): update loading checks to use signal() for reactive state management (#727)

This commit is contained in:
brios
2026-04-22 17:27:43 -04:00
committed by Zach Yale
parent 7a88b12430
commit 284e7bec49
59 changed files with 577 additions and 345 deletions
+3 -3
View File
@@ -1,5 +1,5 @@
<ng-container *transloco="let t; prefix: 'app'">
@if (loading) {
@if (loading()) {
<div class="splash-screen">
<div class="splash-content">
<svg class="logo" viewBox="0 0 100 126" fill="none" xmlns="http://www.w3.org/2000/svg">
@@ -17,7 +17,7 @@
</linearGradient>
</defs>
</svg>
@if (offline) {
@if (offline()) {
<h1>{{ t('offline') }}</h1>
<p>{{ t('offlineLoadingDescription') }}</p>
<p>{{ t('offlineDescription') }}</p>
@@ -28,7 +28,7 @@
}
</div>
</div>
} @else if (offline) {
} @else if (offline()) {
<div class="splash-screen">
<div class="splash-content">
<svg class="logo" viewBox="0 0 100 126" fill="none" xmlns="http://www.w3.org/2000/svg">
+2 -2
View File
@@ -136,7 +136,7 @@ describe("AppComponent", () => {
it("boots the websocket wiring when auth initialization is ready", () => {
configureComponent();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(libraryHealthService.initWebsocket).toHaveBeenCalledOnce();
expect(libraryHealthService.fetchHealth).toHaveBeenCalledOnce();
expect(rxStompService.watch).toHaveBeenCalledWith("/user/queue/book-add");
@@ -148,7 +148,7 @@ describe("AppComponent", () => {
it("boots the websocket wiring but don't fetch library health when not authenticated", () => {
configureComponent({ ready: true, authenticated: false });
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(libraryHealthService.initWebsocket).toHaveBeenCalledOnce();
expect(libraryHealthService.fetchHealth).not.toHaveBeenCalled();
});
+6 -6
View File
@@ -1,4 +1,4 @@
import {Component, effect, inject, OnDestroy, OnInit} from '@angular/core';
import {Component, effect, inject, OnDestroy, OnInit, signal} from '@angular/core';
import {RxStompService} from './shared/websocket/rx-stomp.service';
import {BookService} from './features/book/service/book.service';
import {NotificationEventService} from './shared/websocket/notification-event.service';
@@ -29,8 +29,8 @@ import {AuthService} from './shared/service/auth.service';
})
export class AppComponent implements OnInit, OnDestroy {
loading = true;
offline = false;
loading = signal(true);
offline = signal(false);
private subscriptions: Subscription[] = [];
private subscriptionsInitialized = false;
@@ -48,7 +48,7 @@ export class AppComponent implements OnInit, OnDestroy {
private authService = inject(AuthService);
private readonly syncAuthInitializationEffect = effect(() => {
const ready = this.authInit.initialized();
this.loading = !ready;
this.loading.set(!ready);
if (ready && !this.subscriptionsInitialized) {
this.setupWebSocketSubscriptions();
@@ -71,12 +71,12 @@ export class AppComponent implements OnInit, OnDestroy {
}
private onOnline = () => {
this.offline = false;
this.offline.set(false);
};
private onOffline = () => {
this.checkServerReachable().then(reachable => {
this.offline = !reachable;
this.offline.set(!reachable);
});
};
@@ -16,7 +16,7 @@
</div>
}
@if (isUploading) {
@if (isUploading()) {
<p-progressSpinner class="upload-spinner" strokeWidth="4" fill="transparent" animationDuration=".8s"></p-progressSpinner>
}
@@ -123,9 +123,9 @@
<p-divider layout="vertical"/>
<p-button
type="submit"
[label]="isSaving ? t('saving') : t('saveBtn')"
[icon]="isSaving ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[disabled]="isSaving">
[label]="isSaving() ? t('saving') : t('saveBtn')"
[icon]="isSaving() ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[disabled]="isSaving()">
</p-button>
</div>
</div>
@@ -145,7 +145,7 @@ describe('AuthorEditorComponent', () => {
component.onSave();
expect(component.isSaving).toBe(true);
expect(component.isSaving()).toBe(true);
expect(updateAuthor).toHaveBeenCalledWith(9, {
name: undefined,
description: 'Updated description',
@@ -159,7 +159,7 @@ describe('AuthorEditorComponent', () => {
save$.next(updatedAuthor);
save$.complete();
expect(component.isSaving).toBe(false);
expect(component.isSaving()).toBe(false);
expect(emitSpy).toHaveBeenCalledWith(updatedAuthor);
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successSummary');
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.successDetail');
@@ -179,7 +179,7 @@ describe('AuthorEditorComponent', () => {
component.onSave();
expect(component.isSaving).toBe(false);
expect(component.isSaving()).toBe(false);
expect(emitSpy).not.toHaveBeenCalled();
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorSummary');
expect(translate).toHaveBeenCalledWith('authorBrowser.editor.toast.errorDetail');
@@ -224,12 +224,12 @@ describe('AuthorEditorComponent', () => {
const emitSpy = vi.spyOn(component.authorUpdated, 'emit');
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(999);
component.isUploading = true;
component.isUploading.set(true);
component.hasPhoto = false;
component.onUpload();
expect(component.isUploading).toBe(false);
expect(component.isUploading()).toBe(false);
expect(component.hasPhoto).toBe(true);
expect(component.photoTimestamp).toBe(999);
expect(emitSpy).toHaveBeenCalledWith(component.author);
@@ -243,11 +243,11 @@ describe('AuthorEditorComponent', () => {
it('clears upload progress and shows an error toast when upload fails', () => {
const component = createComponent();
component.isUploading = true;
component.isUploading.set(true);
component.onUploadError();
expect(component.isUploading).toBe(false);
expect(component.isUploading()).toBe(false);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'authorBrowser.editor.toast.errorSummary',
@@ -1,4 +1,4 @@
import {Component, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import {Component, EventEmitter, inject, Input, OnChanges, OnInit, Output, signal, SimpleChanges} from '@angular/core';
import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Button} from 'primeng/button';
@@ -46,8 +46,8 @@ export class AuthorEditorComponent implements OnInit, OnChanges {
private t = inject(TranslocoService);
form!: FormGroup;
isSaving = false;
isUploading = false;
isSaving = signal(false);
isUploading = signal(false);
hasPhoto = true;
photoTimestamp = Date.now();
@@ -152,11 +152,11 @@ export class AuthorEditorComponent implements OnInit, OnChanges {
}
onBeforeUpload(): void {
this.isUploading = true;
this.isUploading.set(true);
}
onUpload(): void {
this.isUploading = false;
this.isUploading.set(false);
this.photoTimestamp = Date.now();
this.hasPhoto = true;
this.authorUpdated.emit(this.author);
@@ -168,7 +168,7 @@ export class AuthorEditorComponent implements OnInit, OnChanges {
}
onUploadError(): void {
this.isUploading = false;
this.isUploading.set(false);
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
@@ -177,8 +177,8 @@ export class AuthorEditorComponent implements OnInit, OnChanges {
}
private saveMetadata(): void {
if (this.isSaving) return;
this.isSaving = true;
if (this.isSaving()) return;
this.isSaving.set(true);
const formValue = this.form.getRawValue();
const request = {
@@ -193,7 +193,7 @@ export class AuthorEditorComponent implements OnInit, OnChanges {
this.authorService.updateAuthor(this.authorId, request).subscribe({
next: (updated) => {
this.isSaving = false;
this.isSaving.set(false);
this.authorUpdated.emit(updated);
this.messageService.add({
severity: 'success',
@@ -202,7 +202,7 @@ export class AuthorEditorComponent implements OnInit, OnChanges {
});
},
error: () => {
this.isSaving = false;
this.isSaving.set(false);
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
@@ -83,8 +83,8 @@
[text]="true"
severity="info"
(onClick)="fetchMetadataByIsbn()"
[disabled]="!isbn.trim() || isFetchingMetadata"
[loading]="isFetchingMetadata"
[disabled]="!isbn.trim() || isFetchingMetadata()"
[loading]="isFetchingMetadata()"
[pTooltip]="t('fetchMetadataTooltip')"
tooltipPosition="top"/>
</div>
@@ -250,8 +250,8 @@
icon="pi pi-plus"
severity="success"
(onClick)="createBook()"
[disabled]="!canCreate() || isLoading"
[loading]="isLoading"/>
[disabled]="!canCreate() || isLoading()"
[loading]="isLoading()"/>
</div>
</div>
</div>
@@ -181,7 +181,7 @@ describe('AddPhysicalBookDialogComponent', () => {
component.fetchMetadataByIsbn();
expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719');
expect(component.isFetchingMetadata).toBe(true);
expect(component.isFetchingMetadata()).toBe(true);
lookupResult$.next(createMetadata({
title: 'Dune',
@@ -205,7 +205,7 @@ describe('AddPhysicalBookDialogComponent', () => {
expect(component.pageCount).toBe(412);
expect(component.categories).toEqual(['Science Fiction']);
expect(component.coverUrl).toBe('https://covers.example/dune.jpg');
expect(component.isFetchingMetadata).toBe(false);
expect(component.isFetchingMetadata()).toBe(false);
});
it('does not start isbn lookup for blank or in-flight requests and clears the flag on error', () => {
@@ -216,17 +216,17 @@ describe('AddPhysicalBookDialogComponent', () => {
expect(lookupByIsbn).not.toHaveBeenCalled();
component.isbn = '9780441172719';
component.isFetchingMetadata = true;
component.isFetchingMetadata.set(true);
component.fetchMetadataByIsbn();
expect(lookupByIsbn).not.toHaveBeenCalled();
component.isFetchingMetadata = false;
component.isFetchingMetadata.set(false);
lookupByIsbn.mockReturnValueOnce(throwError(() => new Error('lookup failed')));
component.fetchMetadataByIsbn();
expect(lookupByIsbn).toHaveBeenCalledWith('9780441172719');
expect(component.isFetchingMetadata).toBe(false);
expect(component.isFetchingMetadata()).toBe(false);
});
it('gates creation on required fields and does not submit when already loading', () => {
@@ -240,7 +240,7 @@ describe('AddPhysicalBookDialogComponent', () => {
component.title = 'Physical Copy';
expect(component.canCreate()).toBe(true);
component.isLoading = true;
component.isLoading.set(true);
component.createBook();
expect(createPhysicalBook).not.toHaveBeenCalled();
@@ -270,7 +270,7 @@ describe('AddPhysicalBookDialogComponent', () => {
component.createBook();
expect(component.isLoading).toBe(true);
expect(component.isLoading()).toBe(true);
expect(createPhysicalBook).toHaveBeenCalledWith({
libraryId: 2,
title: 'The Left Hand of Darkness',
@@ -288,7 +288,7 @@ describe('AddPhysicalBookDialogComponent', () => {
createResult$.next(createdBook);
createResult$.complete();
expect(component.isLoading).toBe(false);
expect(component.isLoading()).toBe(false);
expect(dialogRef.close).toHaveBeenCalledWith(createdBook);
});
@@ -314,7 +314,7 @@ describe('AddPhysicalBookDialogComponent', () => {
categories: undefined,
thumbnailUrl: undefined,
});
expect(component.isLoading).toBe(false);
expect(component.isLoading()).toBe(false);
expect(dialogRef.close).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,4 @@
import {Component, computed, effect, inject} from '@angular/core';
import {Component, computed, effect, inject, signal} from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
@@ -57,8 +57,8 @@ export class AddPhysicalBookDialogComponent {
filteredCategories: string[] = [];
coverUrl: string | null = null;
isLoading: boolean = false;
isFetchingMetadata: boolean = false;
isLoading = signal(false);
isFetchingMetadata = signal(false);
private readonly initializeSelectedLibraryEffect = effect(() => {
const libraries = this.libraries;
if (libraries.length === 0) {
@@ -117,9 +117,9 @@ export class AddPhysicalBookDialogComponent {
fetchMetadataByIsbn(): void {
const isbnValue = this.isbn.trim();
if (!isbnValue || this.isFetchingMetadata) return;
if (!isbnValue || this.isFetchingMetadata()) return;
this.isFetchingMetadata = true;
this.isFetchingMetadata.set(true);
this.bookMetadataService.lookupByIsbn(isbnValue).subscribe({
next: (metadata) => {
if (metadata.title) this.title = metadata.title;
@@ -131,10 +131,10 @@ export class AddPhysicalBookDialogComponent {
if (metadata.pageCount) this.pageCount = metadata.pageCount;
if (metadata.categories?.length) this.categories = [...metadata.categories];
this.coverUrl = metadata.thumbnailUrl || null;
this.isFetchingMetadata = false;
this.isFetchingMetadata.set(false);
},
error: () => {
this.isFetchingMetadata = false;
this.isFetchingMetadata.set(false);
}
});
}
@@ -148,9 +148,9 @@ export class AddPhysicalBookDialogComponent {
}
createBook(): void {
if (!this.canCreate() || this.isLoading) return;
if (!this.canCreate() || this.isLoading()) return;
this.isLoading = true;
this.isLoading.set(true);
const request: CreatePhysicalBookRequest = {
libraryId: this.selectedLibraryId!,
@@ -168,11 +168,11 @@ export class AddPhysicalBookDialogComponent {
this.bookService.createPhysicalBook(request).subscribe({
next: (book) => {
this.isLoading = false;
this.isLoading.set(false);
this.dynamicDialogRef.close(book);
},
error: () => {
this.isLoading = false;
this.isLoading.set(false);
}
});
}
@@ -1,6 +1,6 @@
<div class="book-notes-container">
<div class="notes-content">
@if (loading) {
@if (loading()) {
<div class="loading-state">
<p-progressSpinner/>
<span class="loading-text">Loading notes...</span>
@@ -85,7 +85,7 @@ describe('BookNotesComponent', () => {
component.loadNotes();
expect(bookNoteService.getNotesForBook).not.toHaveBeenCalled();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('loads notes and orders them by most recent update first', () => {
@@ -98,7 +98,7 @@ describe('BookNotesComponent', () => {
expect(bookNoteService.getNotesForBook).toHaveBeenCalledWith(42);
expect(component.notes.map(note => note.id)).toEqual([2, 3, 1]);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('shows an error toast when loading notes fails', () => {
@@ -106,7 +106,7 @@ describe('BookNotesComponent', () => {
component.loadNotes();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'common.error',
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, signal, SimpleChanges} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Button} from 'primeng/button';
@@ -38,7 +38,7 @@ export class BookNotesComponent implements OnInit, OnChanges {
private readonly t = inject(TranslocoService);
notes: BookNote[] = [];
loading = false;
loading = signal(false);
showCreateDialog = false;
showEditDialog = false;
selectedNote: BookNote | null = null;
@@ -70,7 +70,7 @@ export class BookNotesComponent implements OnInit, OnChanges {
loadNotes(): void {
if (!this.bookId) return;
this.loading = true;
this.loading.set(true);
this.bookNoteService.getNotesForBook(this.bookId)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
@@ -78,11 +78,11 @@ export class BookNotesComponent implements OnInit, OnChanges {
this.notes = notes.sort((a, b) =>
new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
);
this.loading = false;
this.loading.set(false);
},
error: (error) => {
console.error('Failed to load notes:', error);
this.loading = false;
this.loading.set(false);
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -1,7 +1,7 @@
<ng-container *transloco="let t; prefix: 'book.reviews'">
<div class="book-reviews-container">
<div class="reviews-content">
@if (loading) {
@if (loading()) {
<div class="loading-state">
<p-progressSpinner/>
<span class="loading-text">{{ t('labels.loadingReviews') }}</span>
@@ -156,9 +156,9 @@
[icon]="reviewsLocked ? 'pi pi-lock' : 'pi pi-lock-open'"
size="small"
[severity]="reviewsLocked ? 'danger' : 'success'"
[disabled]="!reviewDownloadEnabled || loading"
[disabled]="!reviewDownloadEnabled || loading()"
(click)="toggleReviewsLock()"
[pTooltip]="loading ? t('tooltip.pleaseWait') : (!reviewDownloadEnabled ? t('tooltip.enableDownloads') : (reviewsLocked ? t('tooltip.unlockReviews') : t('tooltip.lockReviews')))"
[pTooltip]="loading() ? t('tooltip.pleaseWait') : (!reviewDownloadEnabled ? t('tooltip.enableDownloads') : (reviewsLocked ? t('tooltip.unlockReviews') : t('tooltip.lockReviews')))"
tooltipPosition="left"
class="action-btn"/>
@@ -167,10 +167,10 @@
icon="pi pi-refresh"
size="small"
severity="primary"
[loading]="loading"
[disabled]="reviewsLocked || !reviewDownloadEnabled || loading"
[loading]="loading()"
[disabled]="reviewsLocked || !reviewDownloadEnabled || loading()"
(click)="fetchNewReviews()"
[pTooltip]="loading ? t('tooltip.pleaseWait') : (!reviewDownloadEnabled ? t('tooltip.enableDownloads') : (reviewsLocked ? t('tooltip.reviewsLocked') : t('tooltip.fetchNewReviews')))"
[pTooltip]="loading() ? t('tooltip.pleaseWait') : (!reviewDownloadEnabled ? t('tooltip.enableDownloads') : (reviewsLocked ? t('tooltip.reviewsLocked') : t('tooltip.fetchNewReviews')))"
tooltipPosition="left"
class="action-btn"/>
}
@@ -181,9 +181,9 @@
icon="pi pi-trash"
size="small"
severity="danger"
[disabled]="reviewsLocked || loading"
[disabled]="reviewsLocked || loading()"
(click)="deleteAllReviews()"
[pTooltip]="loading ? t('tooltip.pleaseWait') : (reviewsLocked ? t('tooltip.reviewsLocked') : t('tooltip.deleteAllReviews'))"
[pTooltip]="loading() ? t('tooltip.pleaseWait') : (reviewsLocked ? t('tooltip.reviewsLocked') : t('tooltip.deleteAllReviews'))"
tooltipPosition="left"
class="action-btn"/>
}
@@ -194,9 +194,9 @@
[icon]="allSpoilersRevealed ? 'pi pi-eye-slash' : 'pi pi-eye'"
size="small"
[severity]="allSpoilersRevealed ? 'warn' : 'info'"
[disabled]="loading"
[disabled]="loading()"
(click)="toggleSpoilerVisibility()"
[pTooltip]="loading ? t('tooltip.pleaseWait') : (allSpoilersRevealed ? t('tooltip.hideAllSpoilers') : t('tooltip.revealAllSpoilers'))"
[pTooltip]="loading() ? t('tooltip.pleaseWait') : (allSpoilersRevealed ? t('tooltip.hideAllSpoilers') : t('tooltip.revealAllSpoilers'))"
tooltipPosition="left"
class="action-btn"/>
@@ -205,9 +205,9 @@
icon="pi pi-sort-amount-down"
size="small"
severity="contrast"
[disabled]="loading"
[disabled]="loading()"
(click)="toggleSortOrder()"
[pTooltip]="loading ? t('tooltip.pleaseWait') : (sortAscending ? t('tooltip.sortNewest') : t('tooltip.sortOldest'))"
[pTooltip]="loading() ? t('tooltip.pleaseWait') : (sortAscending ? t('tooltip.sortNewest') : t('tooltip.sortOldest'))"
tooltipPosition="left"
class="action-btn"/>
}
@@ -1,6 +1,7 @@
import {SimpleChange} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {of, throwError} from 'rxjs';
import {of, throwError, delay} from 'rxjs';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {ConfirmationService, MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
@@ -151,7 +152,7 @@ describe('BookReviewsComponent', () => {
expect(reviewService.getByBookId).toHaveBeenCalledWith(42);
expect(component.reviews?.map(review => review.id)).toEqual([3, 2, 1]);
expect(component.reviewsLocked).toBe(true);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('refreshes reviews, clears revealed spoilers, and shows a success toast', () => {
@@ -167,7 +168,7 @@ describe('BookReviewsComponent', () => {
expect(component.reviews?.map(review => review.id)).toEqual([5, 4]);
expect(component.revealedSpoilers.size).toBe(0);
expect(component.allSpoilersRevealed).toBe(false);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'book.reviews.toast.reviewsUpdatedSummary',
@@ -184,7 +185,7 @@ describe('BookReviewsComponent', () => {
component.fetchNewReviews();
expect(errorSpy).toHaveBeenCalledWith('Failed to fetch new reviews:', error);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'book.reviews.toast.fetchFailedSummary',
@@ -339,4 +340,94 @@ describe('BookReviewsComponent', () => {
expect(component.getProviderSeverity('goodreads')).toBe('success');
expect(component.formatDate('2026-03-28T12:00:00.000Z')).toBe('March 28, 2026');
});
it('ignores stale responses if the bookId changes while a request is in-flight', async () => {
const book1Reviews = [createReview(1)];
const book2Reviews = [createReview(2)];
// First request is slow
reviewService.getByBookId.mockReturnValueOnce(of(book1Reviews).pipe(delay(50)));
// Second request is fast
reviewService.getByBookId.mockReturnValueOnce(of(book2Reviews));
// Select book 1
component.bookId = 1;
component.ngOnChanges({
bookId: new SimpleChange(undefined, 1, true),
});
// Immediately select book 2 while book 1 is still loading
component.bookId = 2;
component.ngOnChanges({
bookId: new SimpleChange(1, 2, false),
});
// Wait for both to complete
await new Promise(resolve => setTimeout(resolve, 100));
// Should only have book 2's reviews
expect(component.reviews?.map(r => r.id)).toEqual([2]);
expect(component.loading()).toBe(false);
});
it('does not prematurely clear loading if a refresh finishes while a new book load is in-flight', async () => {
// 1. fetchNewReviews(42) starts
reviewService.refreshReviews.mockReturnValueOnce(of([]).pipe(delay(50)));
component.fetchNewReviews();
expect(component.loading()).toBe(true);
// 2. Switch to book 43 -> loadReviews(43) starts
// Use a longer delay for the new book load
reviewService.getByBookId.mockReturnValueOnce(of([]).pipe(delay(100)));
component.bookId = 43;
component.ngOnChanges({
bookId: new SimpleChange(42, 43, false),
});
// 3. Wait for fetchNewReviews(42) to finish (after 50ms)
await new Promise(resolve => setTimeout(resolve, 75));
// 4. loading should still be true because loadReviews(43) is in flight
expect(component.loading()).toBe(true);
// 5. Wait for loadReviews(43) to finish (after 100ms total)
await new Promise(resolve => setTimeout(resolve, 50));
expect(component.loading()).toBe(false);
});
it('ignores stale responses in a 1 -> 2 -> 1 navigation sequence (ABA problem)', async () => {
const book1InitialReviews = [createReview(1, {body: 'First Request'})];
const book1LatestReviews = [createReview(1, {body: 'Second Request'})];
const book2Reviews = [createReview(2)];
// 1. First request for Book 1 is very slow
reviewService.getByBookId.mockReturnValueOnce(of(book1InitialReviews).pipe(delay(100)));
// 2. Request for Book 2 is fast
reviewService.getByBookId.mockReturnValueOnce(of(book2Reviews));
// 3. Second request for Book 1 is slow
reviewService.getByBookId.mockReturnValueOnce(of(book1LatestReviews).pipe(delay(50)));
// Navigate: Book 1
component.bookId = 1;
component.ngOnChanges({bookId: new SimpleChange(undefined, 1, true)});
// Navigate: Book 2
component.bookId = 2;
component.ngOnChanges({bookId: new SimpleChange(1, 2, false)});
// Navigate: Book 1 again
component.bookId = 1;
component.ngOnChanges({bookId: new SimpleChange(2, 1, false)});
// Wait for all requests to finish
await new Promise(resolve => setTimeout(resolve, 150));
// Should have the reviews from the SECOND request for Book 1, not the first
expect(component.reviews?.[0].body).toBe('Second Request');
expect(component.loading()).toBe(false);
});
});
@@ -1,6 +1,8 @@
import {Component, DestroyRef, effect, inject, Input, OnChanges, OnInit, signal, SimpleChanges} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {finalize} from 'rxjs';
import {BookReview, BookReviewService} from './book-review-service';
import {ProgressSpinner} from 'primeng/progressspinner';
import {Rating} from 'primeng/rating';
@@ -37,8 +39,13 @@ export class BookReviewsComponent implements OnInit, OnChanges {
private destroyRef = inject(DestroyRef);
private readonly t = inject(TranslocoService);
private bookIdState = signal<number | null>(null);
private loadingBookId: number | null = null;
private loadingRequestSeq = 0;
private activeLoadingRequestSeq: number | null = null;
loading = false;
loading = signal(false);
hasPermission = false;
revealedSpoilers = new Set<number>();
sortAscending = false;
@@ -72,22 +79,36 @@ export class BookReviewsComponent implements OnInit, OnChanges {
}
private loadReviews(): void {
if (this.loading || !this.bookId) {
const requestedBookId = this.bookId;
if (!requestedBookId || this.loadingBookId === requestedBookId) {
return;
}
this.loading = true;
this.reviewService.getByBookId(this.bookId)
.pipe(takeUntilDestroyed(this.destroyRef))
const requestSeq = ++this.loadingRequestSeq;
this.loadingBookId = requestedBookId;
this.activeLoadingRequestSeq = requestSeq;
this.loading.set(true);
this.reviewService.getByBookId(requestedBookId)
.pipe(
takeUntilDestroyed(this.destroyRef),
finalize(() => {
if (this.activeLoadingRequestSeq === requestSeq) {
this.loadingBookId = null;
this.activeLoadingRequestSeq = null;
this.loading.set(false);
}
})
)
.subscribe({
next: (reviews) => {
if (this.bookId !== requestedBookId || this.activeLoadingRequestSeq !== requestSeq) return;
this.reviews = this.sortReviewsByDate(reviews || []);
this.loading = false;
},
error: (error) => {
console.error('Failed to load reviews for bookId', this.bookId, ':', error);
if (this.bookId !== requestedBookId || this.activeLoadingRequestSeq !== requestSeq) return;
console.error('Failed to load reviews for bookId', requestedBookId, ':', error);
this.reviews = [];
this.loading = false;
this.messageService.add({
severity: 'error',
@@ -99,18 +120,33 @@ export class BookReviewsComponent implements OnInit, OnChanges {
});
}
fetchNewReviews(): void {
if (!this.bookId || this.loading || this.reviewsLocked) return;
this.loading = true;
fetchNewReviews(): void {
const requestedBookId = this.bookId;
if (!requestedBookId || this.loadingBookId === requestedBookId || this.loading() || this.reviewsLocked) return;
const requestSeq = ++this.loadingRequestSeq;
this.loadingBookId = requestedBookId;
this.activeLoadingRequestSeq = requestSeq;
this.loading.set(true);
this.revealedSpoilers.clear();
this.reviewService.refreshReviews(this.bookId)
.pipe(takeUntilDestroyed(this.destroyRef))
this.reviewService.refreshReviews(requestedBookId)
.pipe(
takeUntilDestroyed(this.destroyRef),
finalize(() => {
if (this.activeLoadingRequestSeq === requestSeq) {
this.loadingBookId = null;
this.activeLoadingRequestSeq = null;
this.loading.set(false);
}
})
)
.subscribe({
next: (reviews) => {
if (this.bookId !== requestedBookId || this.activeLoadingRequestSeq !== requestSeq) return;
this.reviews = this.sortReviewsByDate(reviews || []);
this.loading = false;
this.updateSpoilerState();
this.messageService.add({
severity: 'success',
@@ -120,8 +156,9 @@ export class BookReviewsComponent implements OnInit, OnChanges {
});
},
error: (error) => {
if (this.bookId !== requestedBookId || this.activeLoadingRequestSeq !== requestSeq) return;
console.error('Failed to fetch new reviews:', error);
this.loading = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('book.reviews.toast.fetchFailedSummary'),
@@ -132,6 +169,8 @@ export class BookReviewsComponent implements OnInit, OnChanges {
});
}
deleteAllReviews(): void {
if (!this.reviews || this.reviews.length === 0 || this.reviewsLocked) return;
@@ -28,7 +28,7 @@
</div>
</div>
<div class="card-body">
@if (loading) {
@if (loading()) {
<div class="loading-overlay">
<div class="loading-content">
@@ -269,7 +269,7 @@
}
</div>
@if (!loading) {
@if (!loading()) {
<p-divider></p-divider>
<div class="footer">
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, OnInit, QueryList, ViewChildren} from '@angular/core';
import {Component, DestroyRef, inject, OnInit, QueryList, signal, ViewChildren} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {startWith, take, tap} from 'rxjs/operators';
import {PageTitleService} from "../../../../shared/service/page-title.service";
@@ -86,7 +86,7 @@ export class BookdropFileReviewComponent implements OnInit {
bookdropFileUis: BookdropFileUI[] = [];
fileUiCache: Record<number, BookdropFileUI> = {};
copiedFlags: Record<number, boolean> = {};
loading = true;
loading = signal(true);
saving = false;
includeCoversOnCopy = true;
@@ -102,7 +102,7 @@ export class BookdropFileReviewComponent implements OnInit {
this.activatedRoute.queryParams
.pipe(startWith({}), tap(() => {
this.loading = true;
this.loading.set(true);
this.loadPage(0);
}))
.subscribe();
@@ -198,12 +198,12 @@ export class BookdropFileReviewComponent implements OnInit {
});
this.totalRecords = response.page.totalElements;
this.currentPage = page;
this.loading = false;
this.loading.set(false);
this.syncCurrentPageSelection();
},
error: err => {
console.error('Error loading files:', err);
this.loading = false;
this.loading.set(false);
}
});
}
@@ -1,5 +1,5 @@
<div class="reading-sessions-container" *transloco="let t; prefix: 'metadata.readingSessions'">
@if (loading && sessions.length === 0) {
@if (loading() && sessions.length === 0) {
<div class="loading-state">
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s"></p-progressSpinner>
<p class="loading-text">{{ t('loading') }}</p>
@@ -14,7 +14,7 @@
[value]="sessions"
[paginator]="true"
[rows]="rows"
[loading]="loading"
[loading]="loading()"
[showCurrentPageReport]="true"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} sessions"
class="p-datatable-sm">
@@ -59,7 +59,7 @@ describe('BookReadingSessionsComponent', () => {
expect(getSessionsByBookId).toHaveBeenCalledWith(7, 0, 100);
expect(component.sessions).toEqual([session]);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(component.pageReportTemplate).toBe('translated:metadata.readingSessions.pageReport');
});
@@ -75,7 +75,7 @@ describe('BookReadingSessionsComponent', () => {
component.bookId = 7;
component.loadSessions();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(component.sessions).toEqual([]);
component.bookId = 9;
@@ -85,7 +85,7 @@ describe('BookReadingSessionsComponent', () => {
expect(getSessionsByBookId).toHaveBeenNthCalledWith(2, 9, 0, 100);
expect(component.sessions).toEqual([createSession({id: 2, bookId: 9})]);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('ignores the initial ngOnChanges first-change event', () => {
@@ -1,5 +1,8 @@
import {Component, inject, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core';
import {Component, DestroyRef, inject, Input, OnInit, OnChanges, signal, SimpleChanges} from '@angular/core';
import {ReadingSessionApiService, ReadingSessionResponse} from '../../../../../shared/service/reading-session-api.service';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {finalize, Subject, takeUntil} from 'rxjs';
import {TableModule} from 'primeng/table';
import {ProgressSpinner} from 'primeng/progressspinner';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@@ -16,11 +19,14 @@ export class BookReadingSessionsComponent implements OnInit, OnChanges {
@Input() bookId!: number;
private readonly readingSessionService = inject(ReadingSessionApiService);
private readonly destroyRef = inject(DestroyRef);
private readonly cancelLoad$ = new Subject<void>();
private readonly t = inject(TranslocoService);
sessions: ReadingSessionResponse[] = [];
rows = 5;
loading = false;
loading = signal(false);
get pageReportTemplate(): string {
return this.t.translate('metadata.readingSessions.pageReport');
@@ -37,19 +43,25 @@ export class BookReadingSessionsComponent implements OnInit, OnChanges {
}
loadSessions() {
this.loading = true;
this.cancelLoad$.next();
this.loading.set(true);
this.readingSessionService.getSessionsByBookId(this.bookId, 0, 100)
.pipe(
takeUntil(this.cancelLoad$),
takeUntilDestroyed(this.destroyRef),
finalize(() => this.loading.set(false))
)
.subscribe({
next: (response) => {
this.sessions = response.content;
this.loading = false;
},
error: () => {
this.loading = false;
this.sessions = [];
}
});
}
formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
@@ -3,7 +3,7 @@
<app-metadata-picker
[fetchedMetadata]="selectedFetchedMetadata"
[book]="book"
[detailLoading]="detailLoading"
[detailLoading]="detailLoading()"
(goBack)="onGoBack()">
</app-metadata-picker>
</div>
@@ -76,7 +76,7 @@
<p-button
[label]="t('searchBtn')"
type="submit"
[disabled]="!isSearchEnabled || loading"
[disabled]="!isSearchEnabled || loading()"
icon="pi pi-search"
class="'custom-search-button'">
</p-button>
@@ -84,7 +84,7 @@
</div>
</form>
@if (loading || searchTriggered) {
@if (loading() || searchTriggered()) {
<div class="provider-status">
<div class="status-header">
<div class="results-info">
@@ -94,7 +94,7 @@
</h3>
<span class="results-count">{{ t('booksFound', { count: filteredMetadata().length }) }}</span>
</div>
@if (loading) {
@if (loading()) {
<span class="fetching-badge">
<i class="pi pi-spin pi-spinner"></i>
{{ t('fetching') }}
@@ -129,7 +129,7 @@
</div>
}
@if (!searchTriggered && allFetchedMetadata().length === 0) {
@if (!searchTriggered() && allFetchedMetadata().length === 0) {
<div class="empty-state">
<div class="empty-icon">
<i class="pi pi-search"></i>
@@ -139,7 +139,7 @@
</div>
}
@if (searchTriggered && allFetchedMetadata().length === 0 && !loading) {
@if (searchTriggered() && allFetchedMetadata().length === 0 && !loading()) {
<div class="empty-state">
<div class="empty-icon no-results">
<i class="pi pi-inbox"></i>
@@ -36,8 +36,8 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
providers: string[] = [];
bookId!: number;
loading: boolean = false;
searchTriggered = false;
loading = signal(false);
searchTriggered = signal(false);
private currentBook: Book | null = null;
private currentSettings: AppSettings | null = null;
@@ -55,7 +55,7 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
@Input() isActiveTab: boolean = false;
readonly selectedFetchedMetadata = signal<BookMetadata | null>(null);
detailLoading = false;
detailLoading = signal(false);
private formBuilder = inject(FormBuilder);
private bookMetadataService = inject(BookMetadataService);
@@ -190,8 +190,8 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
private resetFormFromBook(book: Book): void {
this.cancelRequest$.next();
this.loading = false;
this.detailLoading = false;
this.loading.set(false);
this.detailLoading.set(false);
this.selectedFetchedMetadata.set(null);
this.allFetchedMetadata.set([]);
@@ -239,7 +239,7 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
}
onSubmit(): void {
this.searchTriggered = true;
this.searchTriggered.set(true);
if (this.form.valid) {
const providerKeys = this.form.get('provider')?.value;
if (!providerKeys) return;
@@ -252,7 +252,7 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
isbn: this.form.get('isbn')?.value
};
this.loading = true;
this.loading.set(true);
this.allFetchedMetadata.set([]);
const initialCounts = new Map<string, number>();
@@ -304,11 +304,11 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
},
error: (error) => {
console.error('Error fetching metadata:', error);
this.loading = false;
this.loading.set(false);
this.providerLoading.set(new Map());
},
complete: () => {
this.loading = false;
this.loading.set(false);
activeProviders.forEach((provider: string) => {
if (!this.providerCompletionStatus().get(provider)) {
this.providerLoading.update(map => new Map(map).set(provider, false));
@@ -391,7 +391,7 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
const enrichment = this.getDetailEnrichmentInfo(fetchedMetadata);
if (enrichment) {
this.detailLoading = true;
this.detailLoading.set(true);
this.bookMetadataService.fetchMetadataDetail(enrichment.provider, enrichment.id)
.pipe(takeUntil(this.cancelRequest$))
.subscribe({
@@ -401,11 +401,11 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
if (currentId === enrichment.id) {
this.selectedFetchedMetadata.set(enriched);
}
this.detailLoading = false;
this.detailLoading.set(false);
},
error: (err) => {
console.error('Error fetching detailed metadata:', err);
this.detailLoading = false;
this.detailLoading.set(false);
}
});
}
@@ -445,7 +445,7 @@ export class MetadataSearcherComponent implements OnDestroy, OnChanges {
}
onGoBack() {
this.detailLoading = false;
this.detailLoading.set(false);
this.selectedFetchedMetadata.set(null);
}
@@ -16,7 +16,7 @@
</div>
</div>
@if (loading) {
@if (loading()) {
<div class="loading-state">
<i class="pi pi-spin pi-spinner"></i>
<span>{{ t('loading') }}</span>
@@ -26,7 +26,7 @@
<p-button
[label]="t('exportBtn')"
icon="pi pi-upload"
[loading]="exporting"
[loading]="exporting()"
(onClick)="exportToSidecar()"
severity="primary"
size="small"
@@ -36,7 +36,7 @@
<p-button
[label]="t('importBtn')"
icon="pi pi-download"
[loading]="importing"
[loading]="importing()"
[disabled]="syncStatus === 'MISSING'"
(onClick)="importFromSidecar()"
severity="secondary"
@@ -65,7 +65,7 @@ describe('SidecarViewerComponent', () => {
component.currentBookId = 7;
component.sidecarContent = createMetadata();
component.syncStatus = 'IN_SYNC';
component.loading = true;
component.loading.set(true);
component.error = 'failed';
component.book = null;
@@ -73,7 +73,7 @@ describe('SidecarViewerComponent', () => {
expect(component.currentBookId).toBeNull();
expect(component.sidecarContent).toBeNull();
expect(component.syncStatus).toBe('NOT_APPLICABLE');
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(component.error).toBeNull();
});
@@ -90,7 +90,7 @@ describe('SidecarViewerComponent', () => {
expect(component.currentBookId).toBe(7);
expect(component.syncStatus).toBe('IN_SYNC');
expect(component.sidecarContent).toEqual(metadata);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('skips content loading when the sidecar is missing or not applicable', () => {
@@ -102,14 +102,14 @@ describe('SidecarViewerComponent', () => {
expect(getSidecarContent).not.toHaveBeenCalled();
expect(component.syncStatus).toBe('MISSING');
expect(component.sidecarContent).toBeNull();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
getSyncStatus.mockReturnValue(of({status: 'NOT_APPLICABLE'}));
component.book = createBook(4);
expect(getSidecarContent).not.toHaveBeenCalled();
expect(component.syncStatus).toBe('NOT_APPLICABLE');
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('falls back to NOT_APPLICABLE when sync status lookup fails', () => {
@@ -121,7 +121,7 @@ describe('SidecarViewerComponent', () => {
expect(component.syncStatus).toBe('NOT_APPLICABLE');
expect(component.sidecarContent).toBeNull();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(consoleError).toHaveBeenCalledOnce();
});
@@ -134,7 +134,7 @@ describe('SidecarViewerComponent', () => {
component.book = createBook(6);
expect(component.sidecarContent).toBeNull();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(consoleError).not.toHaveBeenCalled();
getSidecarContent.mockReturnValue(throwError(() => ({status: 500})));
@@ -159,7 +159,7 @@ describe('SidecarViewerComponent', () => {
detail: 'translated:metadata.sidecar.toast.exportSuccessDetail',
});
expect(reload).toHaveBeenCalledWith(9);
expect(component.exporting).toBe(false);
expect(component.exporting()).toBe(false);
});
it('shows an error toast when export fails and ignores export without a selected book', () => {
@@ -179,7 +179,7 @@ describe('SidecarViewerComponent', () => {
summary: 'translated:metadata.sidecar.toast.exportFailedSummary',
detail: 'translated:metadata.sidecar.toast.exportFailedDetail',
});
expect(component.exporting).toBe(false);
expect(component.exporting()).toBe(false);
expect(consoleError).toHaveBeenCalledOnce();
});
@@ -199,7 +199,7 @@ describe('SidecarViewerComponent', () => {
detail: 'translated:metadata.sidecar.toast.importSuccessDetail',
});
expect(reload).toHaveBeenCalledWith(12);
expect(component.importing).toBe(false);
expect(component.importing()).toBe(false);
component.importFromSidecar();
@@ -208,7 +208,7 @@ describe('SidecarViewerComponent', () => {
summary: 'translated:metadata.sidecar.toast.importFailedSummary',
detail: 'translated:metadata.sidecar.toast.importFailedDetail',
});
expect(component.importing).toBe(false);
expect(component.importing()).toBe(false);
expect(consoleError).toHaveBeenCalledOnce();
});
@@ -1,4 +1,4 @@
import {Component, inject, Input, OnDestroy} from '@angular/core';
import {Component, inject, Input, OnDestroy, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {Book} from '../../../../book/model/book.model';
@@ -24,7 +24,7 @@ export class SidecarViewerComponent implements OnDestroy {
this.currentBookId = null;
this.sidecarContent = null;
this.syncStatus = 'NOT_APPLICABLE';
this.loading = false;
this.loading.set(false);
this.error = null;
return;
}
@@ -40,14 +40,14 @@ export class SidecarViewerComponent implements OnDestroy {
sidecarContent: SidecarMetadata | null = null;
syncStatus: SidecarSyncStatus = 'NOT_APPLICABLE';
loading = false;
exporting = false;
importing = false;
loading = signal(false);
exporting = signal(false);
importing = signal(false);
currentBookId: number | null = null;
error: string | null = null;
loadSidecarData(bookId: number): void {
this.loading = true;
this.loading.set(true);
this.error = null;
this.sidecarService.getSyncStatus(bookId).pipe(
@@ -60,13 +60,13 @@ export class SidecarViewerComponent implements OnDestroy {
this.loadSidecarContent(bookId);
} else {
this.sidecarContent = null;
this.loading = false;
this.loading.set(false);
}
},
error: (err) => {
this.syncStatus = 'NOT_APPLICABLE';
this.sidecarContent = null;
this.loading = false;
this.loading.set(false);
console.error('Failed to get sync status:', err);
}
});
@@ -78,11 +78,11 @@ export class SidecarViewerComponent implements OnDestroy {
).subscribe({
next: (content) => {
this.sidecarContent = content;
this.loading = false;
this.loading.set(false);
},
error: (err) => {
this.sidecarContent = null;
this.loading = false;
this.loading.set(false);
if (err.status !== 404) {
console.error('Failed to load sidecar content:', err);
}
@@ -93,7 +93,7 @@ export class SidecarViewerComponent implements OnDestroy {
exportToSidecar(): void {
if (!this.currentBookId) return;
this.exporting = true;
this.exporting.set(true);
this.sidecarService.exportToSidecar(this.currentBookId).pipe(
takeUntil(this.destroy$)
).subscribe({
@@ -104,7 +104,7 @@ export class SidecarViewerComponent implements OnDestroy {
detail: this.t.translate('metadata.sidecar.toast.exportSuccessDetail')
});
this.loadSidecarData(this.currentBookId!);
this.exporting = false;
this.exporting.set(false);
},
error: (err) => {
this.messageService.add({
@@ -112,7 +112,7 @@ export class SidecarViewerComponent implements OnDestroy {
summary: this.t.translate('metadata.sidecar.toast.exportFailedSummary'),
detail: this.t.translate('metadata.sidecar.toast.exportFailedDetail')
});
this.exporting = false;
this.exporting.set(false);
console.error('Export failed:', err);
}
});
@@ -121,7 +121,7 @@ export class SidecarViewerComponent implements OnDestroy {
importFromSidecar(): void {
if (!this.currentBookId) return;
this.importing = true;
this.importing.set(true);
this.sidecarService.importFromSidecar(this.currentBookId).pipe(
takeUntil(this.destroy$)
).subscribe({
@@ -132,7 +132,7 @@ export class SidecarViewerComponent implements OnDestroy {
detail: this.t.translate('metadata.sidecar.toast.importSuccessDetail')
});
this.loadSidecarData(this.currentBookId!);
this.importing = false;
this.importing.set(false);
},
error: (err) => {
this.messageService.add({
@@ -140,7 +140,7 @@ export class SidecarViewerComponent implements OnDestroy {
summary: this.t.translate('metadata.sidecar.toast.importFailedSummary'),
detail: this.t.translate('metadata.sidecar.toast.importFailedDetail')
});
this.importing = false;
this.importing.set(false);
console.error('Import failed:', err);
}
});
@@ -61,7 +61,7 @@
type="submit"
[label]="t('searchBtn')"
icon="pi pi-search"
[loading]="loading"
[loading]="loading()"
[disabled]="searchForm.invalid">
</p-button>
<p-button
@@ -81,7 +81,7 @@
<!-- Results Area -->
<div class="results-section">
@if (!hasSearched) {
@if (!hasSearched()) {
<!-- Initial State -->
<div class="empty-state">
<div class="empty-state-icon">
@@ -90,7 +90,7 @@
<h3>{{ t('searchForCovers') }}</h3>
<p>{{ t('searchForCoversDescription') }}</p>
</div>
} @else if (loading) {
} @else if (loading()) {
<!-- Loading State -->
<div class="loading-state">
<p-progressSpinner strokeWidth="3" animationDuration="1s"></p-progressSpinner>
@@ -1,4 +1,4 @@
import {Component, inject, Input, OnInit} from '@angular/core';
import {Component, inject, Input, OnInit, signal} from '@angular/core';
import {MessageService} from 'primeng/api';
import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
import {BookCoverService, CoverFetchRequest, CoverImage} from '../../../../shared/services/book-cover.service';
@@ -32,8 +32,8 @@ export class CoverSearchComponent implements OnInit {
@Input() bookId!: number;
searchForm: FormGroup;
coverImages: CoverImage[] = [];
loading = false;
hasSearched = false;
loading = signal(false);
hasSearched = signal(false);
coverType: 'ebook' | 'audiobook' = 'ebook';
private fb = inject(FormBuilder);
@@ -79,7 +79,7 @@ export class CoverSearchComponent implements OnInit {
onSearch() {
if (this.searchForm.valid) {
this.loading = true;
this.loading.set(true);
this.coverImages = [];
const request: CoverFetchRequest = {
bookId: this.bookId,
@@ -90,8 +90,8 @@ export class CoverSearchComponent implements OnInit {
this.bookCoverService.fetchBookCovers(request)
.pipe(finalize(() => {
this.loading = false;
this.hasSearched = true;
this.loading.set(false);
this.hasSearched.set(true);
}))
.subscribe({
next: (image) => {
@@ -139,6 +139,6 @@ export class CoverSearchComponent implements OnInit {
onClear() {
this.searchForm.reset();
this.coverImages = [];
this.hasSearched = false;
this.hasSearched.set(false);
}
}
@@ -70,7 +70,7 @@
<p-table
#dataTable
[value]="getMetadataItems(tab.type)"
[loading]="loading"
[loading]="loading()"
[globalFilterFields]="['value']"
[paginator]="true"
[rows]="50"
@@ -195,7 +195,7 @@
<small class="help-text" [innerHTML]="t('multiMergeHowItWorks', { type: getTypeLabel(currentMergeType, true) })"></small>
}
</div>
@if (mergingInProgress) {
@if (mergingInProgress()) {
<div class="processing-note">
<i class="pi pi-info-circle"></i>
<span>{{ t('processingNote') }}</span>
@@ -209,14 +209,14 @@
[label]="'common.cancel' | transloco"
icon="pi pi-times"
(onClick)="showMergeDialog = false"
[disabled]="mergingInProgress"
[disabled]="mergingInProgress()"
severity="secondary"
outlined></p-button>
<p-button
[label]="mergingInProgress ? t('processing') : ('common.confirm' | transloco)"
[icon]="mergingInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[loading]="mergingInProgress"
[disabled]="mergingInProgress"
[label]="mergingInProgress() ? t('processing') : ('common.confirm' | transloco)"
[icon]="mergingInProgress() ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[loading]="mergingInProgress()"
[disabled]="mergingInProgress()"
(onClick)="confirmMerge()"
severity="success"></p-button>
</div>
@@ -252,7 +252,7 @@
<small class="help-text" [innerHTML]="t('multiRenameHowItWorks', { singular: getTypeLabel(currentMergeType, false), type: getTypeLabel(currentMergeType, true) })"></small>
}
</div>
@if (mergingInProgress) {
@if (mergingInProgress()) {
<div class="processing-note">
<i class="pi pi-info-circle"></i>
<span>{{ t('renameProcessingNote') }}</span>
@@ -266,14 +266,14 @@
[label]="'common.cancel' | transloco"
icon="pi pi-times"
(onClick)="showRenameDialog = false"
[disabled]="mergingInProgress"
[disabled]="mergingInProgress()"
severity="secondary"
outlined></p-button>
<p-button
[label]="mergingInProgress ? t('processing') : ('common.confirm' | transloco)"
[icon]="mergingInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[loading]="mergingInProgress"
[disabled]="mergingInProgress"
[label]="mergingInProgress() ? t('processing') : ('common.confirm' | transloco)"
[icon]="mergingInProgress() ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[loading]="mergingInProgress()"
[disabled]="mergingInProgress()"
(onClick)="confirmRename()"
severity="success"></p-button>
</div>
@@ -315,7 +315,7 @@
<li>{{ t('totalBooksAffected') }} <strong>{{ currentDeleteItem ? currentDeleteItem.count : getTotalAffectedBooks(getSelectedItems(currentMergeType)) }}</strong></li>
</ul>
</div>
@if (deletingInProgress) {
@if (deletingInProgress()) {
<div class="processing-note">
<i class="pi pi-info-circle"></i>
<span>{{ t('renameProcessingNote') }}</span>
@@ -329,14 +329,14 @@
[label]="'common.cancel' | transloco"
icon="pi pi-times"
(onClick)="showDeleteDialog = false"
[disabled]="deletingInProgress"
[disabled]="deletingInProgress()"
severity="secondary"
outlined></p-button>
<p-button
[label]="deletingInProgress ? t('deleting') : ('common.delete' | transloco)"
[icon]="deletingInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-trash'"
[loading]="deletingInProgress"
[disabled]="deletingInProgress"
[label]="deletingInProgress() ? t('deleting') : ('common.delete' | transloco)"
[icon]="deletingInProgress() ? 'pi pi-spin pi-spinner' : 'pi pi-trash'"
[loading]="deletingInProgress()"
[disabled]="deletingInProgress()"
(onClick)="confirmDelete()"
severity="danger"></p-button>
</div>
@@ -89,7 +89,7 @@ describe('MetadataManagerComponent', () => {
const component = createComponent();
TestBed.flushEffects();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(component.authors[0]).toEqual({value: 'Alice', count: 2, bookIds: [1, 2], selected: false});
expect(component.categories[0]).toEqual({value: 'Fantasy', count: 2, bookIds: [1, 2], selected: false});
expect(component.series).toEqual([{value: 'Series A', count: 2, bookIds: [1, 2], selected: false}]);
@@ -110,13 +110,13 @@ describe('MetadataManagerComponent', () => {
const component = createComponent();
TestBed.flushEffects();
expect(component.loading).toBe(true);
expect(component.loading()).toBe(true);
expect(component.authors).toEqual([]);
isBooksLoading.set(false);
TestBed.flushEffects();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(component.authors).toEqual([{value: 'Alice', count: 1, bookIds: [1], selected: false}]);
});
@@ -1,4 +1,4 @@
import {Component, effect, inject, OnDestroy, OnInit} from '@angular/core';
import {Component, effect, inject, OnDestroy, OnInit, signal} from '@angular/core';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {TableModule} from 'primeng/table';
import {Button} from 'primeng/button';
@@ -75,7 +75,7 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
private routeSub!: Subscription;
private readonly syncMetadataEffect = effect(() => {
const isLoading = this.bookService.isBooksLoading();
this.loading = isLoading;
this.loading.set(isLoading);
if (isLoading) {
return;
@@ -100,9 +100,9 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
selectAllPublishers = false;
selectAllLanguages = false;
loading = false;
mergingInProgress = false;
deletingInProgress = false;
loading = signal(false);
mergingInProgress = signal(false);
deletingInProgress = signal(false);
showMergeDialog = false;
showRenameDialog = false;
showDeleteDialog = false;
@@ -322,8 +322,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
? `"${targetValues[0]}"`
: `${targetValues.length} values`;
this.loading = true;
this.mergingInProgress = true;
this.loading.set(true);
this.mergingInProgress.set(true);
this.bookMetadataManageService.consolidateMetadata(this.currentMergeType, targetValues, [oldValue]).subscribe({
next: () => {
this.messageService.add({
@@ -339,8 +339,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
this.showRenameDialog = false;
this.currentRenameItem = null;
this.renameTarget = '';
this.mergingInProgress = false;
this.loading = false;
this.mergingInProgress.set(false);
this.loading.set(false);
},
error: (error) => {
this.messageService.add({
@@ -352,8 +352,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
? this.t.translate('metadata.manager.toast.renameFailedDetail')
: this.t.translate('metadata.manager.toast.splitFailedDetail'))
});
this.loading = false;
this.mergingInProgress = false;
this.loading.set(false);
this.mergingInProgress.set(false);
}
});
}
@@ -397,8 +397,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
const affectedBooks = this.getTotalAffectedBooks(selected);
const operation = targetValues.length === 1 ? 'merge' : 'merge/split';
this.loading = true;
this.mergingInProgress = true;
this.loading.set(true);
this.mergingInProgress.set(true);
this.bookMetadataManageService.consolidateMetadata(this.currentMergeType, targetValues, valuesToMerge).subscribe({
next: () => {
this.messageService.add({
@@ -414,8 +414,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
this.showMergeDialog = false;
this.mergeTarget = '';
this.clearSelection(this.currentMergeType);
this.mergingInProgress = false;
this.loading = false;
this.mergingInProgress.set(false);
this.loading.set(false);
},
error: (error) => {
this.messageService.add({
@@ -427,8 +427,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
? this.t.translate('metadata.manager.toast.mergeFailedDetail')
: this.t.translate('metadata.manager.toast.mergeSplitFailedDetail'))
});
this.loading = false;
this.mergingInProgress = false;
this.loading.set(false);
this.mergingInProgress.set(false);
}
});
}
@@ -456,8 +456,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
? this.currentDeleteItem.count
: this.getTotalAffectedBooks(this.getSelectedItems(this.currentMergeType));
this.loading = true;
this.deletingInProgress = true;
this.loading.set(true);
this.deletingInProgress.set(true);
this.bookMetadataManageService.deleteMetadata(this.currentMergeType, valuesToDelete).subscribe({
next: () => {
this.messageService.add({
@@ -469,8 +469,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
this.showDeleteDialog = false;
this.currentDeleteItem = null;
this.clearSelection(this.currentMergeType);
this.deletingInProgress = false;
this.loading = false;
this.deletingInProgress.set(false);
this.loading.set(false);
},
error: (error) => {
this.messageService.add({
@@ -478,8 +478,8 @@ export class MetadataManagerComponent implements OnInit, OnDestroy {
summary: this.t.translate('metadata.manager.toast.deleteFailedSummary'),
detail: error?.error?.message || this.t.translate('metadata.manager.toast.deleteFailedDetail')
});
this.loading = false;
this.deletingInProgress = false;
this.loading.set(false);
this.deletingInProgress.set(false);
}
});
}
@@ -17,7 +17,7 @@
</p-button>
</div>
@if (!loading) {
@if (!loading()) {
<div class="dialog-content">
@if (currentProposal?.metadataJson; as proposed) {
<app-metadata-picker
@@ -87,7 +87,7 @@ describe('MetadataReviewDialogComponent', () => {
expect(getTaskWithProposals).toHaveBeenCalledWith('task-1');
expect(component.currentProposal).toEqual(createProposal({proposalId: 5}));
expect(component.currentBook()).toEqual({id: 11, title: 'Book 11'});
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('closes when loading the task proposals fails', () => {
@@ -31,7 +31,7 @@ export class MetadataReviewDialogComponent implements OnInit {
private bookService = inject(BookService);
private progressService = inject(MetadataProgressService);
loading = true;
loading = signal(true);
readonly proposals = signal<FetchedProposal[]>([]);
readonly currentIndex = signal(0);
readonly currentBook = computed<Book | null>(() => {
@@ -52,7 +52,7 @@ export class MetadataReviewDialogComponent implements OnInit {
const bookIds = new Set(proposals.map(proposal => proposal.bookId));
const matchedBooks = this.bookService.books().filter(book => bookIds.has(book.id));
this.loading = matchedBooks.length !== bookIds.size;
this.loading.set(matchedBooks.length !== bookIds.size);
});
}
@@ -99,7 +99,7 @@
<!-- Scrollable Content Area -->
<div class="entries-scroll-area">
<!-- Loading State -->
@if (loading) {
@if (loading()) {
<div class="settings-card">
<div class="state-container">
<i class="pi pi-spin pi-spinner"></i>
@@ -108,7 +108,7 @@
}
<!-- Empty State: No annotations at all -->
@if (!loading && totalEntries === 0 && !searchQuery.trim() && selectedBookId === null && showHighlights && showNotes && showBookmarks) {
@if (!loading() && totalEntries === 0 && !searchQuery.trim() && selectedBookId === null && showHighlights && showNotes && showBookmarks) {
<div class="settings-card">
<div class="state-container">
<div class="state-icon">
@@ -121,7 +121,7 @@
}
<!-- Empty State: No results match filters -->
@if (!loading && totalEntries === 0 && (searchQuery.trim() || selectedBookId !== null || !showHighlights || !showNotes || !showBookmarks)) {
@if (!loading() && totalEntries === 0 && (searchQuery.trim() || selectedBookId !== null || !showHighlights || !showNotes || !showBookmarks)) {
<div class="settings-card">
<div class="state-container">
<div class="state-icon warn">
@@ -133,7 +133,7 @@
}
<!-- Book Groups -->
@if (!loading && filteredGroups.length > 0) {
@if (!loading() && filteredGroups.length > 0) {
@for (group of filteredGroups; track group.bookId) {
<div class="settings-card book-group-card">
<!-- Book Header -->
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, DestroyRef, inject, OnInit, signal} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {of, Subject} from 'rxjs';
import {debounceTime, switchMap} from 'rxjs/operators';
@@ -62,7 +62,7 @@ export class NotebookComponent implements OnInit {
filteredGroups: BookGroup[] = [];
totalEntries = 0;
loading = true;
loading = signal(true);
exporting = false;
searchQuery = '';
@@ -89,7 +89,7 @@ export class NotebookComponent implements OnInit {
if (types.length === 0) {
return of(EMPTY_PAGE);
}
this.loading = true;
this.loading.set(true);
return this.notebookService.getNotebookEntries(
this.page, this.pageSize, types, this.selectedBookId, this.searchQuery, this.sortDirection
);
@@ -98,7 +98,7 @@ export class NotebookComponent implements OnInit {
).subscribe(result => {
this.totalEntries = result.page.totalElements;
this.groupEntries(result.content);
this.loading = false;
this.loading.set(false);
});
this.searchSubject.pipe(
@@ -68,7 +68,7 @@
[rows]="rows"
[first]="currentPage * rows"
[totalRecords]="totalRecords"
[loading]="loading"
[loading]="loading()"
[showCurrentPageReport]="true"
[currentPageReportTemplate]="t('pageReport')"
(onLazyLoad)="onLazyLoad($event)"
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, DestroyRef, inject, OnInit, signal} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {ActivatedRoute, Router} from '@angular/router';
import {TableLazyLoadEvent, TableModule} from 'primeng/table';
@@ -55,7 +55,7 @@ export class AuditLogsComponent implements OnInit {
logs: AuditLog[] = [];
totalRecords = 0;
rows = 25;
loading = false;
loading = signal(false);
selectedAction: string | null = null;
selectedUsername: string | null = null;
dateRange: Date[] | null = null;
@@ -127,7 +127,7 @@ export class AuditLogsComponent implements OnInit {
loadLogs(showLoading = true): void {
if (showLoading) {
this.loading = true;
this.loading.set(true);
}
const action = this.selectedAction || undefined;
const username = this.selectedUsername || undefined;
@@ -139,10 +139,10 @@ export class AuditLogsComponent implements OnInit {
next: (response) => {
this.logs = response.content;
this.totalRecords = response.page.totalElements;
this.loading = false;
this.loading.set(false);
},
error: () => {
this.loading = false;
this.loading.set(false);
}
});
}
@@ -23,7 +23,12 @@
</div>
<div class="section-body">
@if (emailProviders.length === 0) {
@if (loading()) {
<div class="loading-state">
<p-progressSpinner/>
<p class="loading-text">{{ 'common.loading' | transloco }}</p>
</div>
} @else if (emailProviders.length === 0) {
<div class="empty-state">
<i class="pi pi-envelope"></i>
<p class="empty-title">{{ t('emptyTitle') }}</p>
@@ -1,5 +1,6 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, DestroyRef, inject, OnInit, signal} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {finalize} from 'rxjs';
import {Button} from 'primeng/button';
import {Checkbox} from 'primeng/checkbox';
import {MessageService} from 'primeng/api';
@@ -13,6 +14,7 @@ import {EmailProvider} from '../email-provider.model';
import {UserService} from '../../user-management/user.service';
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {ProgressSpinner} from 'primeng/progressspinner';
@Component({
selector: 'app-email-v2-provider',
@@ -25,7 +27,8 @@ import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/tran
Tooltip,
FormsModule,
TranslocoDirective,
TranslocoPipe
TranslocoPipe,
ProgressSpinner
],
templateUrl: './email-v2-provider.component.html',
styleUrl: './email-v2-provider.component.scss'
@@ -40,6 +43,9 @@ export class EmailV2ProviderComponent implements OnInit {
private userService = inject(UserService);
private t = inject(TranslocoService);
private destroyRef = inject(DestroyRef);
loading = signal(false);
private loadingRequestSeq = 0;
private activeLoadingRequestSeq: number | null = null;
defaultProviderId: unknown;
currentUserId: number | null = null;
isAdmin: boolean = false;
@@ -56,10 +62,21 @@ export class EmailV2ProviderComponent implements OnInit {
}
loadEmailProviders(): void {
const requestSeq = ++this.loadingRequestSeq;
this.activeLoadingRequestSeq = requestSeq;
this.loading.set(true);
this.emailProvidersService.getEmailProviders().pipe(
takeUntilDestroyed(this.destroyRef)
takeUntilDestroyed(this.destroyRef),
finalize(() => {
if (this.activeLoadingRequestSeq === requestSeq) {
this.loading.set(false);
}
})
).subscribe({
next: (emailProviders: EmailProvider[]) => {
if (this.activeLoadingRequestSeq !== requestSeq) return;
this.emailProviders = emailProviders.map((provider) => ({
...provider,
isEditing: false,
@@ -68,6 +85,9 @@ export class EmailV2ProviderComponent implements OnInit {
this.defaultProviderId = defaultProvider ? defaultProvider.id : null;
},
error: () => {
if (this.activeLoadingRequestSeq !== requestSeq) return;
this.emailProviders = [];
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -154,7 +174,7 @@ export class EmailV2ProviderComponent implements OnInit {
detail: this.t.translate('settingsEmail.provider.defaultSetDetail', {name: provider.name}),
});
},
error: (err) => {
error: (err: unknown) => {
console.error('Failed to set default provider', err);
this.messageService.add({
severity: 'error',
@@ -23,7 +23,12 @@
</div>
<div class="section-body">
@if (recipientEmails.length === 0) {
@if (loading()) {
<div class="loading-state">
<p-progressSpinner/>
<p class="loading-text">{{ 'common.loading' | transloco }}</p>
</div>
} @else if (recipientEmails.length === 0) {
<div class="empty-state">
<i class="pi pi-users"></i>
<p class="empty-title">{{ t('emptyTitle') }}</p>
@@ -1,5 +1,6 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, DestroyRef, inject, OnInit, signal} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {finalize} from 'rxjs';
import {Button} from 'primeng/button';
import {MessageService} from 'primeng/api';
import {RadioButton} from 'primeng/radiobutton';
@@ -11,6 +12,7 @@ import {EmailV2RecipientService} from './email-v2-recipient.service';
import {EmailRecipient} from '../email-recipient.model';
import {DialogLauncherService} from '../../../../shared/services/dialog-launcher.service';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {ProgressSpinner} from 'primeng/progressspinner';
@Component({
selector: 'app-email-v2-recipient',
@@ -22,7 +24,8 @@ import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/tran
Tooltip,
FormsModule,
TranslocoDirective,
TranslocoPipe
TranslocoPipe,
ProgressSpinner
],
templateUrl: './email-v2-recipient.component.html',
styleUrl: './email-v2-recipient.component.scss'
@@ -36,6 +39,9 @@ export class EmailV2RecipientComponent implements OnInit {
private messageService = inject(MessageService);
private t = inject(TranslocoService);
private destroyRef = inject(DestroyRef);
loading = signal(false);
private loadingRequestSeq = 0;
private activeLoadingRequestSeq: number | null = null;
defaultRecipientId: unknown;
ngOnInit(): void {
@@ -43,10 +49,21 @@ export class EmailV2RecipientComponent implements OnInit {
}
loadRecipientEmails(): void {
const requestSeq = ++this.loadingRequestSeq;
this.activeLoadingRequestSeq = requestSeq;
this.loading.set(true);
this.emailRecipientService.getRecipients().pipe(
takeUntilDestroyed(this.destroyRef)
takeUntilDestroyed(this.destroyRef),
finalize(() => {
if (this.activeLoadingRequestSeq === requestSeq) {
this.loading.set(false);
}
})
).subscribe({
next: (recipients: EmailRecipient[]) => {
if (this.activeLoadingRequestSeq !== requestSeq) return;
this.recipientEmails = recipients.map((recipient) => ({
...recipient,
isEditing: false,
@@ -55,6 +72,9 @@ export class EmailV2RecipientComponent implements OnInit {
this.defaultRecipientId = defaultRecipient ? defaultRecipient.id : null;
},
error: () => {
if (this.activeLoadingRequestSeq !== requestSeq) return;
this.recipientEmails = [];
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -40,9 +40,9 @@
<span class="setting-description">Current size occupied by Cache Storage</span>
</div>
<div class="setting-control action-buttons">
<span class="setting-value">{{ cacheStorageUsageMb | number: '1.2-2' }} MB</span>
<span class="setting-value">{{ cacheStorageUsageMb() | number: '1.2-2' }} MB</span>
<p-button type="button" label="Refresh" icon="pi pi-refresh" severity="secondary" [outlined]="true"
[disabled]="isLoadingCacheStorageUsage" [loading]="isLoadingCacheStorageUsage" (onClick)="loadCacheStorageUsage()">
[disabled]="isLoadingCacheStorageUsage()" [loading]="isLoadingCacheStorageUsage()" (onClick)="loadCacheStorageUsage()">
</p-button>
</div>
</div>
@@ -54,7 +54,7 @@
</div>
<div class="setting-control">
<p-button type="button" label="Clear Cache" icon="pi pi-trash" severity="danger" [outlined]="true"
[disabled]="isClearingCacheStorage" [loading]="isClearingCacheStorage" (onClick)="clearCacheStorage()">
[disabled]="isClearingCacheStorage()" [loading]="isClearingCacheStorage()" (onClick)="clearCacheStorage()">
</p-button>
</div>
</div>
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from "@angular/core";
import {Component, inject, OnInit, signal} from "@angular/core";
import {FormsModule} from "@angular/forms";
import {DecimalPipe} from "@angular/common";
import {Checkbox} from "primeng/checkbox";
@@ -28,9 +28,9 @@ export class LocalSettingsComponent implements OnInit {
protected settings: LocalSettings = this.localSettingsService.get();
protected isLoadingCacheStorageUsage = false;
protected isClearingCacheStorage = false;
protected cacheStorageUsageMb = 0;
protected isLoadingCacheStorageUsage = signal(false);
protected isClearingCacheStorage = signal(false);
protected cacheStorageUsageMb = signal(0);
async ngOnInit(): Promise<void> {
await this.loadCacheStorageUsage();
@@ -57,7 +57,7 @@ export class LocalSettingsComponent implements OnInit {
severity: "secondary",
},
accept: async () => {
this.isClearingCacheStorage = true;
this.isClearingCacheStorage.set(true);
try {
await this.cacheStorageService.clear();
await this.loadCacheStorageUsage();
@@ -73,22 +73,22 @@ export class LocalSettingsComponent implements OnInit {
detail: "Unable to clear Cache Storage. Please try again.",
});
} finally {
this.isClearingCacheStorage = false;
this.isClearingCacheStorage.set(false);
}
},
});
}
async loadCacheStorageUsage(): Promise<void> {
this.isLoadingCacheStorageUsage = true;
this.isLoadingCacheStorageUsage.set(true);
try {
const totalBytes = await this.cacheStorageService.getCacheSizeInBytes();
this.cacheStorageUsageMb = totalBytes / (1024 * 1024);
this.cacheStorageUsageMb.set(totalBytes / (1024 * 1024));
} catch (error) {
console.error("Error loading Cache Storage usage:", error);
this.cacheStorageUsageMb = 0;
this.cacheStorageUsageMb.set(0);
} finally {
this.isLoadingCacheStorageUsage = false;
this.isLoadingCacheStorageUsage.set(false);
}
}
}
@@ -2,7 +2,7 @@
@if (userService.currentUser(); as currentUser) {
@if (currentUser) {
<div class="settings-container">
<p-tabs [(value)]="activeTab" lazy scrollable>
<p-tabs [(value)]="activeTab" scrollable>
<p-tablist>
<p-tab [value]="SettingsTab.ReaderSettings">
<i class="pi pi-book"></i> {{ t('reader') }}
@@ -59,84 +59,93 @@
</p-tab>
</p-tablist>
<p-tabpanels>
<!-- [GROUP: Lazy Tabs] -->
<p-tabpanel [value]="SettingsTab.ReaderSettings">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.ReaderSettings)) {
<app-reader-preferences></app-reader-preferences>
</ng-template>
}
</p-tabpanel>
<p-tabpanel [value]="SettingsTab.ViewPreferences">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.ViewPreferences)) {
<app-view-preferences-parent></app-view-preferences-parent>
</ng-template>
}
</p-tabpanel>
@if (currentUser.permissions.admin || currentUser.permissions.canManageMetadataConfig) {
<p-tabpanel [value]="SettingsTab.MetadataSettings">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.MetadataSettings)) {
<app-metadata-settings-component></app-metadata-settings-component>
</ng-template>
}
</p-tabpanel>
<p-tabpanel [value]="SettingsTab.LibraryMetadataSettings">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.LibraryMetadataSettings)) {
<app-library-metadata-settings-component></app-library-metadata-settings-component>
</ng-template>
}
</p-tabpanel>
}
@if (currentUser.permissions.admin || currentUser.permissions.canManageGlobalPreferences) {
<p-tabpanel [value]="SettingsTab.ApplicationSettings">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.ApplicationSettings)) {
<app-global-preferences></app-global-preferences>
</ng-template>
}
</p-tabpanel>
}
<!-- [GROUP: Eager Tabs (Always Rendered to ensure initialization)] -->
@if (currentUser.permissions.admin) {
<p-tabpanel [value]="SettingsTab.UserManagement">
<ng-template #content>
<app-user-management></app-user-management>
</ng-template>
<app-user-management></app-user-management>
</p-tabpanel>
}
<p-tabpanel [value]="SettingsTab.EmailSettingsV2">
<ng-template #content>
<app-email-v2></app-email-v2>
</ng-template>
<app-email-v2></app-email-v2>
</p-tabpanel>
<!-- [GROUP: Lazy Tabs Continued] -->
@if (currentUser.permissions.admin || currentUser.permissions.canManageMetadataConfig) {
<p-tabpanel [value]="SettingsTab.NamingPattern">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.NamingPattern)) {
<app-file-naming-pattern></app-file-naming-pattern>
</ng-template>
}
</p-tabpanel>
}
@if (currentUser.permissions.admin) {
<p-tabpanel [value]="SettingsTab.AuthenticationSettings">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.AuthenticationSettings)) {
<app-authentication-settings></app-authentication-settings>
</ng-template>
}
</p-tabpanel>
}
@if (currentUser.permissions.admin || currentUser.permissions.canAccessTaskManager) {
<p-tabpanel [value]="SettingsTab.Tasks">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.Tasks)) {
<app-task-management></app-task-management>
</ng-template>
}
</p-tabpanel>
}
@if (currentUser.permissions.admin) {
<p-tabpanel [value]="SettingsTab.AuditLogs">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.AuditLogs)) {
<app-audit-logs></app-audit-logs>
</ng-template>
}
</p-tabpanel>
}
<p-tabpanel [value]="SettingsTab.OpdsV2">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.OpdsV2)) {
<app-opds-settings></app-opds-settings>
</ng-template>
}
</p-tabpanel>
<p-tabpanel [value]="SettingsTab.DeviceSettings">
<ng-template #content>
@if (visitedTabs().has(SettingsTab.DeviceSettings)) {
<app-device-settings-component></app-device-settings-component>
</ng-template>
}
</p-tabpanel>
</p-tabpanels>
</p-tabs>
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, DestroyRef, effect, inject, OnInit, signal} from '@angular/core';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {UserService} from './user-management/user.service';
import {GlobalPreferencesComponent} from './global-preferences/global-preferences.component';
@@ -71,14 +71,19 @@ export class SettingsComponent implements OnInit {
SettingsTab = SettingsTab;
private validTabs = Object.values(SettingsTab);
private _activeTab: SettingsTab = SettingsTab.ReaderSettings;
private _activeTab = signal<SettingsTab>(SettingsTab.ReaderSettings);
visitedTabs = signal<Set<SettingsTab>>(new Set([
SettingsTab.UserManagement,
SettingsTab.EmailSettingsV2
]));
get activeTab(): SettingsTab {
return this._activeTab;
return this._activeTab();
}
set activeTab(value: SettingsTab) {
this._activeTab = value;
this._activeTab.set(value);
this.router.navigate([], {
relativeTo: this.route,
@@ -87,22 +92,44 @@ export class SettingsComponent implements OnInit {
});
}
constructor() {
const pageTitle = inject(PageTitleService);
pageTitle.setPageTitle('Settings');
effect(() => {
const active = this._activeTab();
this.visitedTabs.update(set => {
if (set.has(active)) return set;
const newSet = new Set(set);
newSet.add(active);
return newSet;
});
});
}
ngOnInit(): void {
this.pageTitle.setPageTitle('Settings');
// Initialize from snapshot synchronously to ensure p-tabs (lazy) picks up the correct value on first render
const initialTab = this.route.snapshot.queryParams['tab'];
if (this.validTabs.includes(initialTab)) {
this._activeTab.set(initialTab as SettingsTab);
}
this.route.queryParams.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(params => {
const tabParam = params['tab'];
if (this.validTabs.includes(tabParam)) {
this._activeTab = tabParam as SettingsTab;
this._activeTab.set(tabParam as SettingsTab);
} else {
this._activeTab = SettingsTab.ReaderSettings;
const defaultTab = SettingsTab.ReaderSettings;
this._activeTab.set(defaultTab);
this.router.navigate([], {
relativeTo: this.route,
queryParams: {tab: this._activeTab},
queryParams: {tab: defaultTab},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
});
}
}
@@ -21,14 +21,14 @@
</div>
<div class="section-body">
@if (loading && taskInfos.length === 0) {
@if (loading() && taskInfos.length === 0) {
<div class="loading-state">
<i class="pi pi-spin pi-spinner"></i>
<span>{{ t('loading') }}</span>
</div>
}
@if (!loading && taskInfos.length === 0) {
@if (!loading() && taskInfos.length === 0) {
<div class="empty-state">
<i class="pi pi-check-circle"></i>
<p class="empty-title">{{ t('emptyTitle') }}</p>
@@ -152,7 +152,7 @@ describe('TaskManagementComponent', () => {
id: 'task-1',
status: TaskStatus.PENDING,
});
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('reports load failures through the message service', () => {
@@ -1,4 +1,4 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {Component, DestroyRef, inject, OnInit, signal} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Button} from 'primeng/button';
import {ProgressBar} from 'primeng/progressbar';
@@ -54,7 +54,7 @@ export class TaskManagementComponent implements OnInit {
// State
taskInfos: TaskInfo[] = [];
taskHistories = new Map<string, TaskHistory>();
loading = false;
loading = signal(false);
executingTasks = new Set<string>();
// Metadata Replace Options
@@ -98,13 +98,13 @@ export class TaskManagementComponent implements OnInit {
// ============================================================================
loadTasks(): void {
this.loading = true;
this.loading.set(true);
forkJoin({
available: this.taskService.getAvailableTasks(),
latest: this.taskService.getLatestTasksForEachType()
})
.pipe(finalize(() => this.loading = false))
.pipe(finalize(() => this.loading.set(false)))
.subscribe({
next: ({available, latest}) => {
this.taskInfos = this.sortTasksByDisplayOrder(available);
@@ -118,7 +118,7 @@
[label]="t('clearBtn')"
severity="danger"
[outlined]="true"
[disabled]="!filesPresent() || isUploading"
[disabled]="!filesPresent() || isUploading()"
[pTooltip]="t('clearTooltip')"
tooltipPosition="top"/>
</div>
@@ -127,11 +127,11 @@
</ng-template>
<ng-template #content let-files let-removeFileCallback="removeFileCallback">
@if (files?.length > 0) {
@if (isUploading || uploadCompleted) {
@if (isUploading() || uploadCompleted()) {
<div class="upload-progress-summary">
<div class="progress-row">
<span class="progress-status">
@if (isUploading) {
@if (isUploading()) {
<i class="pi pi-spin pi-spinner"></i>
{{ t('uploading') }}
} @else {
@@ -1,4 +1,4 @@
import {ChangeDetectorRef, Component, inject, ViewChild, effect} from '@angular/core';
import {ChangeDetectorRef, Component, inject, ViewChild, effect, signal} from '@angular/core';
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
import {Button} from 'primeng/button';
import {FormsModule} from '@angular/forms';
@@ -47,8 +47,8 @@ export class BookUploaderComponent {
@ViewChild(FileUpload) fileUpload!: FileUpload;
files: UploadingFile[] = [];
isUploading: boolean = false;
uploadCompleted: boolean = false;
isUploading = signal(false);
uploadCompleted = signal(false);
_selectedLibrary: Library | null = null;
selectedPath: LibraryPath | null = null;
@@ -112,10 +112,14 @@ export class BookUploaderComponent {
onClear(clearCallback: () => void): void {
clearCallback();
this.files = [];
this.uploadCompleted.set(false);
}
onFilesSelect(event: FileSelectEvent): void {
this.uploadCompleted.set(false);
if (this.value === 'library' && (!this.selectedLibrary || !this.selectedPath)) {
this.messageService.add({
severity: 'error',
summary: this.t.translate('shared.bookUploader.toast.noDestinationSummary'),
@@ -185,8 +189,8 @@ export class BookUploaderComponent {
const filesToUpload = this.files.filter(f => f.status === 'Pending');
if (filesToUpload.length === 0) return;
this.isUploading = true;
this.uploadCompleted = false;
this.isUploading.set(true);
this.uploadCompleted.set(false);
const destination = this.value;
const libraryId = this.selectedLibrary?.id?.toString();
const pathId = this.selectedPath?.id?.toString();
@@ -197,9 +201,9 @@ export class BookUploaderComponent {
private uploadBatch(files: UploadingFile[], startIndex: number, batchSize: number, destination: string, libraryId?: string, pathId?: string): void {
const batch = files.slice(startIndex, startIndex + batchSize);
if (batch.length === 0) {
this.isUploading = false;
this.uploadCompleted = true;
this.cdr.detectChanges();
this.isUploading.set(false);
this.uploadCompleted.set(true);
if (destination === 'bookdrop') {
this.ref.close('uploaded_to_bookdrop');
}
@@ -266,9 +270,9 @@ export class BookUploaderComponent {
isChooseDisabled(): boolean {
if (this.value === 'bookdrop') {
return this.isUploading;
return this.isUploading();
}
return !this.selectedLibrary || !this.selectedPath || this.isUploading;
return !this.selectedLibrary || !this.selectedPath || this.isUploading();
}
isUploadDisabled(): boolean {
@@ -324,7 +328,7 @@ export class BookUploaderComponent {
}
hasUploadCompleted(): boolean {
return this.uploadCompleted;
return this.uploadCompleted();
}
closeDialog(): void {
@@ -95,7 +95,7 @@
</div>
<div class="directories-container">
@if (isLoading) {
@if (isLoading()) {
<div class="loading-state">
<p-progressSpinner
class="custom-spinner"
@@ -133,7 +133,7 @@
</span>
</div>
<div class="directories-grid" [class.fade-in]="!isLoading && filteredPaths.length > 0">
<div class="directories-grid" [class.fade-in]="!isLoading() && filteredPaths.length > 0">
@for (folder of filteredPaths; track folder) {
<div
class="directory-item"
@@ -46,13 +46,13 @@ describe('DirectoryPickerComponent', () => {
component.ngOnInit();
expect(utilityService.getFolders).toHaveBeenCalledWith('/');
expect(component.isLoading).toBe(true);
expect(component.isLoading()).toBe(true);
vi.advanceTimersByTime(100);
expect(component.paths).toEqual(['/books', '/comics']);
expect(component.filteredPaths).toEqual(['/books', '/comics']);
expect(component.isLoading).toBe(false);
expect(component.isLoading()).toBe(false);
expect(component.breadcrumbItems).toEqual([]);
});
@@ -127,7 +127,7 @@ describe('DirectoryPickerComponent', () => {
component.getFolders('/broken');
expect(component.isLoading).toBe(false);
expect(component.isLoading()).toBe(false);
expect(console.error).toHaveBeenCalled();
});
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core';
import {Component, inject, OnInit, signal} from '@angular/core';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {UtilityService} from './utility.service';
import {TableModule} from 'primeng/table';
@@ -42,7 +42,7 @@ export class DirectoryPickerComponent implements OnInit {
selectedFolders: string[] = [];
selectedFoldersMap: Record<string, boolean> = {};
searchQuery: string = '';
isLoading: boolean = false;
isLoading = signal(false);
breadcrumbItems: MenuItem[] = [];
home: MenuItem = {icon: 'pi pi-home', command: () => this.navigateToRoot()};
@@ -55,14 +55,14 @@ export class DirectoryPickerComponent implements OnInit {
}
getFolders(path: string): void {
this.isLoading = true;
this.isLoading.set(true);
this.filteredPaths = [];
this.utilityService.getFolders(path).subscribe({
next: (folders: string[]) => {
setTimeout(() => {
this.paths = folders;
this.filteredPaths = folders;
this.isLoading = false;
this.isLoading.set(false);
this.updateBreadcrumb(path);
folders.forEach(folder => {
this.selectedFoldersMap[folder] = this.selectedFolders.includes(folder);
@@ -71,7 +71,7 @@ export class DirectoryPickerComponent implements OnInit {
},
error: (error) => {
console.error('Error fetching folders:', error);
this.isLoading = false;
this.isLoading.set(false);
}
});
}
@@ -153,9 +153,9 @@
<p-button
fluid
type="submit"
[label]="loading ? t('creatingAccountBtn') : t('createAccountBtn')"
[icon]="loading ? 'pi pi-spin pi-spinner' : 'pi pi-user-plus'"
[disabled]="loading || setupForm.invalid"
[label]="loading() ? t('creatingAccountBtn') : t('createAccountBtn')"
[icon]="loading() ? 'pi pi-spin pi-spinner' : 'pi pi-user-plus'"
[disabled]="loading() || setupForm.invalid"
class="setup-button"
/>
@@ -63,7 +63,7 @@ describe('SetupComponent', () => {
component.onSubmit();
expect(setupService.createAdmin).not.toHaveBeenCalled();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('submits the admin payload without confirmPassword', () => {
@@ -71,7 +71,7 @@ describe('SetupComponent', () => {
component.onSubmit();
expect(component.loading).toBe(true);
expect(component.loading()).toBe(true);
expect(component.error).toBe(null);
expect(setupService.createAdmin).toHaveBeenCalledWith({
name: 'Admin User',
@@ -87,7 +87,7 @@ describe('SetupComponent', () => {
component.onSubmit();
expect(component.success).toBe(true);
expect(component.loading).toBe(true);
expect(component.loading()).toBe(true);
expect(router.navigate).not.toHaveBeenCalled();
vi.advanceTimersByTime(1500);
@@ -104,7 +104,7 @@ describe('SetupComponent', () => {
component.onSubmit();
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
expect(component.error).toBe('Setup failed');
expect(component.success).toBe(false);
});
@@ -1,4 +1,4 @@
import {Component, inject} from '@angular/core';
import {Component, inject, signal} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {SetupService} from './setup.service';
@@ -26,7 +26,7 @@ export class SetupComponent {
private setupService = inject(SetupService);
private router = inject(Router);
setupForm: FormGroup;
loading = false;
loading = signal(false);
error: string | null = null;
success = false;
private readonly t = inject(TranslocoService);
@@ -44,7 +44,7 @@ export class SetupComponent {
onSubmit(): void {
if (this.setupForm.invalid) return;
this.loading = true;
this.loading.set(true);
this.error = null;
// Remove confirm password from the payload, as it does not need to be sent to backend
const { confirmPassword, ...payload } = this.setupForm.value;
@@ -55,7 +55,7 @@ export class SetupComponent {
setTimeout(() => this.router.navigate(['/login']), 1500);
},
error: (err) => {
this.loading = false;
this.loading.set(false);
this.error =
err?.error?.message || this.t.translate('shared.setup.toast.createFailedDefault');
},
@@ -19,19 +19,19 @@
</div>
<div class="dialog-content">
@if (loading) {
@if (loading()) {
<div class="loading-state">
{{ t('loading') }}
</div>
}
@if (!loading && changelog.length === 0) {
@if (!loading() && changelog.length === 0) {
<div class="empty-state">
{{ t('empty') }}
</div>
}
@if (!loading && changelog.length > 0) {
@if (!loading() && changelog.length > 0) {
<div class="changelog-list">
@for (release of changelog; track release) {
<div class="release-item">
@@ -47,7 +47,7 @@ describe('VersionChangelogDialogComponent', () => {
expect(versionService.getChangelog).toHaveBeenCalled();
expect(component.changelog).toHaveLength(1);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('clears the loading state when the changelog request fails', () => {
@@ -58,7 +58,7 @@ describe('VersionChangelogDialogComponent', () => {
component.ngOnInit();
expect(component.changelog).toEqual([]);
expect(component.loading).toBe(false);
expect(component.loading()).toBe(false);
});
it('converts markdown to sanitized HTML and normalizes headings to h3', () => {
@@ -1,4 +1,4 @@
import { Component, inject, OnInit } from '@angular/core';
import { Component, inject, OnInit, signal } from '@angular/core';
import { ReleaseNote, VersionService } from '../../../service/version.service';
import showdown from 'showdown';
@@ -25,7 +25,7 @@ export class VersionChangelogDialogComponent implements OnInit {
dialogRef = inject(DynamicDialogRef);
changelog: ReleaseNote[] = [];
loading = true;
loading = signal(true);
private converter = new showdown.Converter({ tables: true, emoji: true });
@@ -33,10 +33,10 @@ export class VersionChangelogDialogComponent implements OnInit {
this.versionService.getChangelog().subscribe({
next: (data) => {
this.changelog = data;
this.loading = false;
this.loading.set(false);
},
error: () => {
this.loading = false;
this.loading.set(false);
}
});
}