refactor(ui): convert bookdrop progress to signals (#1626)

This commit is contained in:
Alex
2026-06-03 14:30:09 +01:00
committed by GitHub
parent 9d30913b3a
commit 9de1c9d55a
9 changed files with 106 additions and 91 deletions
@@ -4,10 +4,10 @@
<div class="widget-info">
<p class="widget-title">{{ t('title') }}</p>
<p class="widget-count">{{ pendingCount }}</p>
@if (lastUpdatedAt) {
<p class="widget-count">{{ pendingCount() }}</p>
@if (lastUpdatedAt(); as updatedAt) {
<p class="widget-date">
{{ t('lastUpdated') }} {{ lastUpdatedAt | date: 'short' }}
{{ t('lastUpdated') }} {{ updatedAt | date: 'short' }}
</p>
}
</div>
@@ -1,14 +1,68 @@
import {describe, it} from 'vitest';
import {provideZonelessChangeDetection, signal, WritableSignal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {Router} from '@angular/router';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
// NOTE(frontend-seam): Real coverage here needs seams around the live summary stream, router
// navigation timing, and widget lifecycle teardown so bookdrop notification state can be tested
// without mounting the live websocket-backed runtime.
describe.skip('BookdropFilesWidgetComponent', () => {
it('needs subscription seams to verify pending-count updates and timestamp hydration from summary notifications', () => {
// TODO(seam): Cover ngOnInit once the live summary observable is isolated behind a deterministic subject.
import {getTranslocoModule} from '../../../../core/testing/transloco-testing';
import {BookdropFileNotification, BookdropFileService} from '../../service/bookdrop-file.service';
import {BookdropFilesWidgetComponent} from './bookdrop-files-widget.component';
describe('BookdropFilesWidgetComponent', () => {
let fixture: ComponentFixture<BookdropFilesWidgetComponent>;
let component: BookdropFilesWidgetComponent;
let summary: WritableSignal<BookdropFileNotification>;
let router: {navigate: ReturnType<typeof vi.fn>};
beforeEach(async () => {
summary = signal<BookdropFileNotification>({
pendingCount: 0,
totalCount: 0,
});
router = {
navigate: vi.fn(),
};
await TestBed.configureTestingModule({
imports: [BookdropFilesWidgetComponent, getTranslocoModule()],
providers: [
provideZonelessChangeDetection(),
{provide: BookdropFileService, useValue: {summary}},
{provide: Router, useValue: router},
],
}).compileComponents();
fixture = TestBed.createComponent(BookdropFilesWidgetComponent);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('needs routing seams to verify review navigation and destroy-time subscription cleanup', () => {
// TODO(seam): Cover openReviewDialog and ngOnDestroy after extracting router and subscription lifecycle concerns.
afterEach(() => {
TestBed.resetTestingModule();
vi.restoreAllMocks();
});
it('updates the visible pending count when the summary signal changes', async () => {
summary.set({
pendingCount: 3,
totalCount: 9,
lastUpdatedAt: '2026-05-28T12:05:00Z',
});
await fixture.whenStable();
fixture.detectChanges();
expect(countText()).toBe('3');
expect(fixture.nativeElement.querySelector('.widget-date')).not.toBeNull();
});
it('navigates to bookdrop review with a reload timestamp', () => {
component.openReviewDialog();
expect(router.navigate).toHaveBeenCalledWith(['/bookdrop'], {
queryParams: {reload: expect.any(Number)},
});
});
function countText(): string {
return fixture.nativeElement.querySelector('.widget-count').textContent.trim();
}
});
@@ -1,7 +1,5 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {BookdropFileNotification, BookdropFileService} from '../../service/bookdrop-file.service';
import {ChangeDetectionStrategy, Component, computed, inject} from '@angular/core';
import {BookdropFileService} from '../../service/bookdrop-file.service';
import {DatePipe} from '@angular/common';
import {Router} from '@angular/router';
import {Button} from 'primeng/button';
@@ -12,37 +10,21 @@ import {TranslocoDirective} from '@jsverse/transloco';
standalone: true,
templateUrl: './bookdrop-files-widget.component.html',
styleUrl: './bookdrop-files-widget.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
DatePipe,
Button,
TranslocoDirective
]
})
export class BookdropFilesWidgetComponent implements OnInit, OnDestroy {
pendingCount = 0;
totalCount = 0;
lastUpdatedAt?: string;
private destroy$ = new Subject<void>();
private bookdropFileService = inject(BookdropFileService);
private router = inject(Router);
ngOnInit(): void {
this.bookdropFileService.summary$
.pipe(takeUntil(this.destroy$))
.subscribe((summary: BookdropFileNotification) => {
this.pendingCount = summary.pendingCount;
this.totalCount = summary.totalCount;
this.lastUpdatedAt = summary.lastUpdatedAt;
});
}
export class BookdropFilesWidgetComponent {
private readonly bookdropFileService = inject(BookdropFileService);
private readonly router = inject(Router);
private readonly summary = this.bookdropFileService.summary;
protected readonly pendingCount = computed(() => this.summary().pendingCount);
protected readonly lastUpdatedAt = computed(() => this.summary().lastUpdatedAt);
openReviewDialog(): void {
this.router.navigate(['/bookdrop'], {queryParams: {reload: Date.now()}});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -51,13 +51,8 @@ describe('BookdropFileService', () => {
service = TestBed.inject(BookdropFileService);
TestBed.flushEffects();
let latestSummary: BookdropFileNotification | undefined;
service.summary$.subscribe(value => {
latestSummary = value;
});
expect(getNotification).toHaveBeenCalledOnce();
expect(latestSummary).toEqual(summary);
expect(service.summary()).toEqual(summary);
});
it('does not auto-refresh when the current user lacks access', () => {
@@ -77,26 +72,24 @@ describe('BookdropFileService', () => {
it('publishes incoming file summaries and pending state', () => {
service = TestBed.inject(BookdropFileService);
let hasPendingFiles: boolean | undefined;
service.hasPendingFiles$.subscribe(value => {
hasPendingFiles = value;
});
service.handleIncomingFile(summary);
expect(hasPendingFiles).toBe(true);
expect(service.summary()).toEqual(summary);
expect(service.hasPendingFiles()).toBe(true);
service.handleIncomingFile({...summary, pendingCount: 0});
expect(hasPendingFiles).toBe(false);
expect(service.hasPendingFiles()).toBe(false);
});
it('warns when manual refresh fails', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
currentUser.set(null);
getNotification.mockReturnValueOnce(throwError(() => new Error('boom')));
service = TestBed.inject(BookdropFileService);
TestBed.flushEffects();
service.refresh();
expect(getNotification).toHaveBeenCalledOnce();
expect(warnSpy).toHaveBeenCalled();
});
});
@@ -1,6 +1,4 @@
import {effect, inject, Injectable, OnDestroy} from '@angular/core';
import {BehaviorSubject, Subscription} from 'rxjs';
import {map} from 'rxjs/operators';
import {computed, effect, inject, Injectable, signal} from '@angular/core';
import {BookdropFileApiService} from './bookdrop-file-api.service';
import {AuthService} from '../../../shared/service/auth.service';
import {UserService} from '../../settings/user-management/user.service';
@@ -14,52 +12,40 @@ export interface BookdropFileNotification {
@Injectable({
providedIn: 'root'
})
export class BookdropFileService implements OnDestroy {
private summarySubject = new BehaviorSubject<BookdropFileNotification>({
export class BookdropFileService {
private readonly summaryState = signal<BookdropFileNotification>({
pendingCount: 0,
totalCount: 0
});
summary$ = this.summarySubject.asObservable();
readonly summary = this.summaryState.asReadonly();
readonly hasPendingFiles = computed(() => this.summary().pendingCount > 0);
hasPendingFiles$ = this.summary$.pipe(
map(summary => summary.pendingCount > 0)
);
private apiService = inject(BookdropFileApiService);
private authService = inject(AuthService);
private subscriptions = new Subscription();
private userService = inject(UserService);
private hasInitialized = false;
private readonly apiService = inject(BookdropFileApiService);
private readonly authService = inject(AuthService);
private readonly userService = inject(UserService);
constructor() {
effect(() => {
const user = this.userService.currentUser();
if (this.hasInitialized || !user) {
const token = this.authService.token();
if (!user || !token || !(user.permissions.admin || user.permissions.canAccessBookdrop)) {
return;
}
this.hasInitialized = true;
if ((user.permissions.admin || user.permissions.canAccessBookdrop) && this.authService.token()) {
this.refresh();
}
this.refresh();
});
}
handleIncomingFile(summary: BookdropFileNotification): void {
this.summarySubject.next(summary);
this.summaryState.set(summary);
}
refresh(): void {
const sub = this.apiService.getNotification().subscribe({
next: summary => this.summarySubject.next(summary),
this.apiService.getNotification().subscribe({
next: summary => this.summaryState.set(summary),
error: err => console.warn('Failed to refresh bookdrop file summary:', err)
});
this.subscriptions.add(sub);
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
this.summarySubject.complete();
}
}
@@ -14,12 +14,12 @@ describe('UnifiedNotificationBoxComponent', () => {
let fixture: ComponentFixture<UnifiedNotificationBoxComponent>;
let component: UnifiedNotificationBoxComponent;
let activeTasks$: BehaviorSubject<Record<string, unknown>>;
let hasPendingFiles$: BehaviorSubject<boolean>;
let hasPendingFiles: WritableSignal<boolean>;
let hasActiveImport: WritableSignal<boolean>;
beforeEach(async () => {
activeTasks$ = new BehaviorSubject<Record<string, unknown>>({});
hasPendingFiles$ = new BehaviorSubject(false);
hasPendingFiles = signal(false);
hasActiveImport = signal(false);
await TestBed.configureTestingModule({
@@ -31,7 +31,7 @@ describe('UnifiedNotificationBoxComponent', () => {
},
{
provide: BookdropFileService,
useValue: {hasPendingFiles$},
useValue: {hasPendingFiles},
},
{
provide: LibraryImportProgressService,
@@ -71,7 +71,7 @@ describe('UnifiedNotificationBoxComponent', () => {
const popover = component as unknown as {hasPendingBookdropFiles: Signal<boolean>};
expect(popover.hasPendingBookdropFiles()).toBe(false);
hasPendingFiles$.next(true);
hasPendingFiles.set(true);
expect(popover.hasPendingBookdropFiles()).toBe(true);
});
@@ -28,6 +28,6 @@ export class UnifiedNotificationBoxComponent {
private readonly activeMetadataTasks = toSignal(this.metadataProgressService.activeTasks$, {initialValue: {}});
protected readonly hasMetadataTasks = computed(() => Object.keys(this.activeMetadataTasks()).length > 0);
protected readonly hasPendingBookdropFiles = toSignal(this.bookdropFileService.hasPendingFiles$, {initialValue: false});
protected readonly hasPendingBookdropFiles = this.bookdropFileService.hasPendingFiles;
protected readonly hasActiveLibraryImport = this.libraryImportProgressService.hasActiveImport;
}
@@ -42,7 +42,7 @@ describe('AppSidebarComponent', () => {
let versionInfo: BehaviorSubject<AppVersion>;
let activeTasks$: BehaviorSubject<Record<string, MetadataBatchProgressNotification>>;
let progressUpdates$: BehaviorSubject<MetadataBatchProgressNotification>;
let hasPendingFiles$: BehaviorSubject<boolean>;
let hasPendingFiles: WritableSignal<boolean>;
let hasActiveImport: WritableSignal<boolean>;
const sidebarCollapsed = signal(false);
const isDesktop = signal(true);
@@ -71,7 +71,7 @@ describe('AppSidebarComponent', () => {
status: MetadataBatchStatus.COMPLETED,
review: false,
});
hasPendingFiles$ = new BehaviorSubject(false);
hasPendingFiles = signal(false);
hasActiveImport = signal(false);
TestBed.configureTestingModule({
@@ -101,7 +101,7 @@ describe('AppSidebarComponent', () => {
{ provide: BookDialogHelperService, useValue: { openShelfCreatorDialog: vi.fn(() => Promise.resolve(null)) } },
{ provide: AuthService, useValue: { logout: vi.fn() } },
{ provide: MetadataProgressService, useValue: { activeTasks$, progressUpdates$ } },
{ provide: BookdropFileService, useValue: { hasPendingFiles$ } },
{ provide: BookdropFileService, useValue: { hasPendingFiles } },
{ provide: LibraryImportProgressService, useValue: { hasActiveImport } },
{ provide: VersionService, useValue: { getVersion: vi.fn(() => versionInfo) } },
{ provide: LayoutService, useValue: layoutService },
@@ -288,7 +288,7 @@ describe('AppSidebarComponent', () => {
review: true,
},
});
hasPendingFiles$.next(true);
hasPendingFiles.set(true);
hasActiveImport.set(true);
expect(sidebar.completedTaskCount()).toBe(4);
@@ -235,7 +235,7 @@ export class AppSidebarComponent {
private readonly progressHighlight = computed(() =>
this.latestProgress()?.status === MetadataBatchStatus.IN_PROGRESS
);
private readonly hasPendingBookdropFiles = toSignal(this.bookdropFileService.hasPendingFiles$, { initialValue: false });
private readonly hasPendingBookdropFiles = this.bookdropFileService.hasPendingFiles;
private readonly hasActiveLibraryImport = this.libraryImportProgressService.hasActiveImport;
protected readonly completedTaskCount = computed(() => {
const metadataTaskCount = Object.keys(this.activeMetadataTasks()).length;