refactor(ui): move large library processing screen to notifications (#1428)
Co-authored-by: Alex <25013571+alexhb1@users.noreply.github.com>
This commit is contained in:
@@ -13,18 +13,19 @@ import { AppConfigService } from "./shared/service/app-config.service";
|
||||
import { MetadataProgressService } from "./shared/service/metadata-progress.service";
|
||||
import { BookdropFileService } from "./features/bookdrop/service/bookdrop-file.service";
|
||||
import { TaskService } from "./features/settings/task-management/task.service";
|
||||
import { LibraryService } from "./features/book/service/library.service";
|
||||
import { LibraryHealthService } from "./features/book/service/library-health.service";
|
||||
import { LibraryLoadingService } from "./features/library-creator/library-loading.service";
|
||||
import { AuthService } from "./shared/service/auth.service";
|
||||
import { ConfirmationService } from "primeng/api";
|
||||
import { MessageService } from "primeng/api";
|
||||
import { CommandPaletteService } from "./features/command-palette/command-palette.service";
|
||||
import { LibraryImportProgressService } from "./shared/service/library-import-progress.service";
|
||||
|
||||
interface StompMessage {
|
||||
body: string;
|
||||
}
|
||||
|
||||
const DEFAULT_AUTH = { ready: true, authenticated: true };
|
||||
|
||||
describe("AppComponent", () => {
|
||||
let fixture: ComponentFixture<AppComponent>;
|
||||
let component: AppComponent;
|
||||
@@ -46,15 +47,8 @@ describe("AppComponent", () => {
|
||||
let bookdropFileService: { handleIncomingFile: ReturnType<typeof vi.fn> };
|
||||
let taskService: { handleTaskProgress: ReturnType<typeof vi.fn> };
|
||||
let libraryHealthService: { initWebsocket: ReturnType<typeof vi.fn>, fetchHealth: ReturnType<typeof vi.fn> };
|
||||
let libraryLoadingService: {
|
||||
showBookLoadingProgress: ReturnType<typeof vi.fn>;
|
||||
hide: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let authService: { forceLogout: ReturnType<typeof vi.fn>, isAuthenticated: ReturnType<typeof signal> };
|
||||
let libraryService: {
|
||||
largeLibraryLoading: ReturnType<typeof signal>;
|
||||
setLargeLibraryLoading: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let libraryImportProgressService: { recordBookAdded: ReturnType<typeof vi.fn> };
|
||||
let commandPaletteService: {
|
||||
toggle: ReturnType<typeof vi.fn>;
|
||||
open: ReturnType<typeof vi.fn>;
|
||||
@@ -73,8 +67,7 @@ describe("AppComponent", () => {
|
||||
}
|
||||
|
||||
function configureComponent(
|
||||
auth = { ready: true, authenticated: true },
|
||||
largeLibraryLoading = { isLoading: false, expectedCount: 0 },
|
||||
auth = DEFAULT_AUTH
|
||||
): void {
|
||||
topics = new Map();
|
||||
rxStompService = {
|
||||
@@ -94,15 +87,8 @@ describe("AppComponent", () => {
|
||||
bookdropFileService = { handleIncomingFile: vi.fn() };
|
||||
taskService = { handleTaskProgress: vi.fn() };
|
||||
libraryHealthService = { initWebsocket: vi.fn(), fetchHealth: vi.fn() };
|
||||
libraryLoadingService = {
|
||||
showBookLoadingProgress: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
};
|
||||
authService = { forceLogout: vi.fn(), isAuthenticated: signal(auth.authenticated) };
|
||||
libraryService = {
|
||||
largeLibraryLoading: signal(largeLibraryLoading),
|
||||
setLargeLibraryLoading: vi.fn(),
|
||||
};
|
||||
libraryImportProgressService = { recordBookAdded: vi.fn() };
|
||||
commandPaletteService = {
|
||||
toggle: vi.fn(),
|
||||
open: vi.fn(),
|
||||
@@ -131,10 +117,9 @@ describe("AppComponent", () => {
|
||||
{ provide: MetadataProgressService, useValue: metadataProgressService },
|
||||
{ provide: BookdropFileService, useValue: bookdropFileService },
|
||||
{ provide: TaskService, useValue: taskService },
|
||||
{ provide: LibraryService, useValue: libraryService },
|
||||
{ provide: LibraryHealthService, useValue: libraryHealthService },
|
||||
{ provide: LibraryLoadingService, useValue: libraryLoadingService },
|
||||
{ provide: AuthService, useValue: authService },
|
||||
{ provide: LibraryImportProgressService, useValue: libraryImportProgressService },
|
||||
{ provide: CommandPaletteService, useValue: commandPaletteService },
|
||||
ConfirmationService,
|
||||
MessageService],
|
||||
@@ -175,27 +160,15 @@ describe("AppComponent", () => {
|
||||
expect(libraryHealthService.fetchHealth).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("routes websocket book notifications through the large library loading branch", () => {
|
||||
configureComponent({ ready: true, authenticated: true }, { isLoading: true, expectedCount: 2 });
|
||||
it("routes websocket book notifications to bookService", () => {
|
||||
configureComponent();
|
||||
|
||||
topics
|
||||
.get("/user/queue/book-add")
|
||||
?.next({ body: JSON.stringify({ metadata: { title: "First" } }) });
|
||||
topics
|
||||
.get("/user/queue/book-add")
|
||||
?.next({ body: JSON.stringify({ metadata: { title: "Second" } }) });
|
||||
|
||||
expect(bookService.handleNewlyCreatedBook).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
libraryLoadingService.showBookLoadingProgress,
|
||||
).toHaveBeenNthCalledWith(1, "First", 1, 2);
|
||||
expect(
|
||||
libraryLoadingService.showBookLoadingProgress,
|
||||
).toHaveBeenNthCalledWith(2, "Second", 2, 2);
|
||||
expect(libraryService.setLargeLibraryLoading).toHaveBeenCalledWith(
|
||||
false,
|
||||
0,
|
||||
);
|
||||
expect(bookService.handleNewlyCreatedBook).toHaveBeenCalledWith({ metadata: { title: "First" } });
|
||||
expect(libraryImportProgressService.recordBookAdded).toHaveBeenCalledWith("First");
|
||||
});
|
||||
|
||||
it("forwards websocket updates to the matching root services", () => {
|
||||
@@ -261,12 +234,11 @@ describe("AppComponent", () => {
|
||||
expect(authService.forceLogout).toHaveBeenCalledWith("session_revoked");
|
||||
});
|
||||
|
||||
it("unsubscribes and hides the loading overlay when destroyed", () => {
|
||||
it("unsubscribes when destroyed", () => {
|
||||
configureComponent();
|
||||
|
||||
component.ngOnDestroy();
|
||||
|
||||
expect(libraryLoadingService.hide).toHaveBeenCalledOnce();
|
||||
topics
|
||||
.get("/user/queue/book-update")
|
||||
?.next({ body: JSON.stringify({ id: 99 }) });
|
||||
|
||||
@@ -6,7 +6,7 @@ import {parseLogNotification} from './shared/websocket/model/log-notification.mo
|
||||
import {ConfirmDialog} from 'primeng/confirmdialog';
|
||||
import {Toast} from 'primeng/toast';
|
||||
import {RouterOutlet} from '@angular/router';
|
||||
import {TranslocoDirective, TranslocoPipe} from '@jsverse/transloco';
|
||||
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
|
||||
import {AuthInitializationService} from './core/security/auth-initialization-service';
|
||||
import {AppConfigService} from './shared/service/app-config.service';
|
||||
import {MetadataBatchProgressNotification} from './shared/model/metadata-batch-progress.model';
|
||||
@@ -14,13 +14,11 @@ import {MetadataProgressService} from './shared/service/metadata-progress.servic
|
||||
import {BookdropFileNotification, BookdropFileService} from './features/bookdrop/service/bookdrop-file.service';
|
||||
import {Subscription} from 'rxjs';
|
||||
import {TaskProgressPayload, TaskService} from './features/settings/task-management/task.service';
|
||||
import {LibraryService} from './features/book/service/library.service';
|
||||
import {LibraryHealthService} from './features/book/service/library-health.service';
|
||||
import {LibraryLoadingService} from './features/library-creator/library-loading.service';
|
||||
import {scan} from 'rxjs/operators';
|
||||
import {AuthService} from './shared/service/auth.service';
|
||||
import {CommandPaletteComponent} from './features/command-palette/command-palette.component';
|
||||
import {CommandPaletteService} from './features/command-palette/command-palette.service';
|
||||
import {LibraryImportProgressService} from './shared/service/library-import-progress.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -44,11 +42,11 @@ export class AppComponent implements OnInit, OnDestroy {
|
||||
private metadataProgressService = inject(MetadataProgressService);
|
||||
private bookdropFileService = inject(BookdropFileService);
|
||||
private taskService = inject(TaskService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private libraryHealthService = inject(LibraryHealthService);
|
||||
private libraryLoadingService = inject(LibraryLoadingService);
|
||||
private authService = inject(AuthService);
|
||||
private commandPaletteService = inject(CommandPaletteService);
|
||||
private readonly libraryImportProgressService = inject(LibraryImportProgressService);
|
||||
private readonly translocoService = inject(TranslocoService);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
private readonly syncAuthInitializationEffect = effect(() => {
|
||||
const ready = this.authInit.initialized();
|
||||
@@ -107,25 +105,11 @@ export class AppComponent implements OnInit, OnDestroy {
|
||||
|
||||
private setupWebSocketSubscriptions(): void {
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-add').pipe(
|
||||
scan((acc, msg) => {
|
||||
const loadingState = this.libraryService.largeLibraryLoading();
|
||||
const book = JSON.parse(msg.body);
|
||||
if (loadingState.isLoading) {
|
||||
const newCount = acc.count + 1;
|
||||
this.libraryLoadingService.showBookLoadingProgress(book.metadata?.title || 'Unknown Book', newCount, loadingState.expectedCount);
|
||||
this.bookService.handleNewlyCreatedBook(book);
|
||||
if (newCount >= loadingState.expectedCount) {
|
||||
this.libraryService.setLargeLibraryLoading(false, 0);
|
||||
return {count: 0};
|
||||
}
|
||||
return {count: newCount};
|
||||
} else {
|
||||
this.bookService.handleNewlyCreatedBook(book);
|
||||
return {count: 0};
|
||||
}
|
||||
}, {count: 0})
|
||||
).subscribe()
|
||||
this.rxStompService.watch('/user/queue/book-add').subscribe(msg => {
|
||||
const book = JSON.parse(msg.body);
|
||||
this.libraryImportProgressService.recordBookAdded(book.metadata?.title || this.translocoService.translate('book.unknownTitle'));
|
||||
this.bookService.handleNewlyCreatedBook(book);
|
||||
})
|
||||
);
|
||||
this.subscriptions.push(
|
||||
this.rxStompService.watch('/user/queue/book-update').subscribe(msg =>
|
||||
@@ -186,6 +170,5 @@ export class AppComponent implements OnInit, OnDestroy {
|
||||
window.removeEventListener('online', this.onOnline);
|
||||
window.removeEventListener('offline', this.onOffline);
|
||||
this.subscriptions.forEach(sub => sub.unsubscribe());
|
||||
this.libraryLoadingService.hide();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ describe('LibraryService', () => {
|
||||
expect(queryClientHarness.queryClient.removeQueries).toHaveBeenCalledWith({queryKey: libraryFormatCountsQueryKey(4), exact: true});
|
||||
});
|
||||
|
||||
it('hydrates format counts through ensureQueryData and tracks large-library loading state', async () => {
|
||||
it('hydrates format counts through ensureQueryData', async () => {
|
||||
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
|
||||
|
||||
const resultPromise = new Promise<Record<string, number>>((resolve, reject) => {
|
||||
@@ -109,9 +109,6 @@ describe('LibraryService', () => {
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({EPUB: 7, PDF: 2});
|
||||
|
||||
service.setLargeLibraryLoading(true, 2500);
|
||||
expect(service.largeLibraryLoading()).toEqual({isLoading: true, expectedCount: 2500});
|
||||
|
||||
bookService.books.mockReturnValue([
|
||||
{libraryId: 8, shelves: []},
|
||||
{libraryId: 8, shelves: []},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {computed, effect, inject, Injectable, signal} from '@angular/core';
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {from, lastValueFrom, Observable} from 'rxjs';
|
||||
import {tap} from 'rxjs/operators';
|
||||
@@ -20,11 +20,6 @@ export class LibraryService {
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
readonly largeLibraryLoading = signal<{ isLoading: boolean; expectedCount: number }>({
|
||||
isLoading: false,
|
||||
expectedCount: 0
|
||||
});
|
||||
|
||||
private librariesQuery = injectQuery(() => ({
|
||||
...this.getLibrariesQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
@@ -140,10 +135,6 @@ export class LibraryService {
|
||||
return counts;
|
||||
});
|
||||
|
||||
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
|
||||
this.largeLibraryLoading.set({ isLoading, expectedCount });
|
||||
}
|
||||
|
||||
getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> {
|
||||
return from(this.queryClient.ensureQueryData(this.getLibraryFormatCountsQueryOptions(libraryId)));
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { CdkDragDrop, DragDropModule, moveItemInArray } from '@angular/cdk/drag-
|
||||
import { Checkbox } from 'primeng/checkbox';
|
||||
import { Select } from 'primeng/select';
|
||||
import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco';
|
||||
import { LibraryImportProgressService } from '../../shared/service/library-import-progress.service';
|
||||
|
||||
interface FormatEntry { type: BookType; label: string }
|
||||
|
||||
@@ -45,6 +46,7 @@ export class LibraryCreatorComponent {
|
||||
private readonly router = inject(Router);
|
||||
private readonly iconPicker = inject(IconPickerService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly libraryImportProgressService = inject(LibraryImportProgressService);
|
||||
|
||||
private readonly activeLang = toSignal(this.t.langChanges$, {
|
||||
initialValue: this.t.getActiveLang(),
|
||||
@@ -302,8 +304,7 @@ export class LibraryCreatorComponent {
|
||||
this.libraryService.scanLibraryPaths(library).pipe(
|
||||
switchMap(count => {
|
||||
if (count >= 500) {
|
||||
console.warn(`Library has ${count} processable files (>500). Will use buffered loading.`);
|
||||
this.libraryService.setLargeLibraryLoading(true, count);
|
||||
this.libraryImportProgressService.start(library.name, count);
|
||||
}
|
||||
return this.libraryService.createLibrary(library).pipe(
|
||||
map(createdLibrary => ({ createdLibrary, count }))
|
||||
@@ -312,6 +313,9 @@ export class LibraryCreatorComponent {
|
||||
).subscribe({
|
||||
next: ({ createdLibrary, count }) => {
|
||||
if (createdLibrary) {
|
||||
if (count >= 500 && createdLibrary.id !== undefined) {
|
||||
this.libraryImportProgressService.attachLibrary(createdLibrary.id);
|
||||
}
|
||||
this.router.navigate(['/library', createdLibrary.id, 'books']);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
@@ -324,7 +328,7 @@ export class LibraryCreatorComponent {
|
||||
}
|
||||
},
|
||||
error: (e: Error) => {
|
||||
this.libraryService.setLargeLibraryLoading(false, 0);
|
||||
this.libraryImportProgressService.fail();
|
||||
this.messageService.add({ severity: 'error', summary: this.t.translate('libraryCreator.creator.toast.createFailedSummary'), detail: this.t.translate('libraryCreator.creator.toast.createFailedDetail') });
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import {describe, it} from 'vitest';
|
||||
|
||||
// NOTE(frontend-seam): Replace this skipped spec once the component-factory lifecycle
|
||||
// is wrapped behind a testable seam. The current service hard-codes Angular's
|
||||
// `createComponent()` ESM export plus direct `document.body` mutation, and Vitest in
|
||||
// this browser-mode setup cannot reliably intercept that export to prove attach/detach
|
||||
// behavior without changing runtime code.
|
||||
describe.skip('LibraryLoadingService', () => {
|
||||
it('needs a component-factory seam to verify dynamic creation and teardown', () => {
|
||||
// TODO(seam): Cover component creation, progress updates, and body overflow cleanup
|
||||
// after introducing a testable wrapper around createComponent/document.body behavior.
|
||||
});
|
||||
});
|
||||
@@ -1,44 +0,0 @@
|
||||
import {Injectable, ComponentRef, ApplicationRef, createComponent, EmbeddedViewRef, EnvironmentInjector, inject} from '@angular/core';
|
||||
import { LibraryLoadingComponent } from './library-loading/library-loading.component';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class LibraryLoadingService {
|
||||
private appRef = inject(ApplicationRef);
|
||||
private injector = inject(EnvironmentInjector);
|
||||
private componentRef: ComponentRef<LibraryLoadingComponent> | null = null;
|
||||
|
||||
showBookLoadingProgress(bookTitle: string, current: number, total: number): void {
|
||||
if (this.componentRef) {
|
||||
this.updateProgress(bookTitle, current, total);
|
||||
return;
|
||||
}
|
||||
|
||||
this.componentRef = createComponent(LibraryLoadingComponent, {
|
||||
environmentInjector: this.injector
|
||||
});
|
||||
|
||||
this.componentRef.instance.updateProgress(bookTitle, current, total);
|
||||
|
||||
this.appRef.attachView(this.componentRef.hostView);
|
||||
const domElem = (this.componentRef.hostView as EmbeddedViewRef<unknown>).rootNodes[0] as HTMLElement;
|
||||
document.body.appendChild(domElem);
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
updateProgress(bookTitle: string, current: number, total: number): void {
|
||||
if (this.componentRef) {
|
||||
this.componentRef.instance.updateProgress(bookTitle, current, total);
|
||||
}
|
||||
}
|
||||
|
||||
hide(): void {
|
||||
if (this.componentRef) {
|
||||
this.appRef.detachView(this.componentRef.hostView);
|
||||
this.componentRef.destroy();
|
||||
this.componentRef = null;
|
||||
document.body.style.overflow = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
<ng-container *transloco="let t; prefix: 'libraryCreator.loading'">
|
||||
<div class="fullscreen-loader">
|
||||
<div class="library-loader-content">
|
||||
<div class="library-loader-header">
|
||||
<i class="pi pi-book"></i>
|
||||
<h2>{{ t('title') }}</h2>
|
||||
</div>
|
||||
|
||||
<div class="library-loader-body">
|
||||
<div class="book-title">
|
||||
@if (!isComplete()) {
|
||||
<ng-container>
|
||||
{{ t('processing') }} <strong>{{ bookTitle() }}</strong>
|
||||
</ng-container>
|
||||
}
|
||||
@if (isComplete()) {
|
||||
<strong class="complete-message">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
{{ t('complete') }}
|
||||
</strong>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="progress-info">
|
||||
<span>{{ current() }} / {{ total() }}</span>
|
||||
<span>{{ percentage() }}%</span>
|
||||
</div>
|
||||
|
||||
<div class="progress-bar-container">
|
||||
<div class="progress-bar-fill" [style.width.%]="percentage()"></div>
|
||||
</div>
|
||||
|
||||
@if (!isComplete()) {
|
||||
<div class="loader-animation">
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
<div class="dot"></div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (isComplete()) {
|
||||
<div class="library-loader-footer">
|
||||
<button class="reload-button" (click)="onReload()">
|
||||
<i class="pi pi-bookmark"></i>
|
||||
{{ t('openLibrary') }}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
.fullscreen-loader {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgb(0 0 0 / 85%);
|
||||
backdrop-filter: blur(8px);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.library-loader-content {
|
||||
background: var(--card-background);
|
||||
padding: 2.5rem;
|
||||
border-radius: 12px;
|
||||
width: 550px;
|
||||
max-width: 90vw;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.library-loader-header {
|
||||
text-align: center;
|
||||
|
||||
i {
|
||||
font-size: 3rem;
|
||||
color: var(--primary-color);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0 0 0.5rem;
|
||||
color: var(--text-color);
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.library-loader-body {
|
||||
.book-title {
|
||||
color: var(--text-color-secondary);
|
||||
margin-bottom: 1.5rem;
|
||||
margin-top: 2.5rem;
|
||||
font-size: 0.95rem;
|
||||
overflow-wrap: anywhere;
|
||||
overflow-wrap: break-word;
|
||||
line-height: 1.4;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
|
||||
strong {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.complete-message {
|
||||
color: var(--primary-color);
|
||||
font-size: 1.1rem;
|
||||
|
||||
i {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.progress-info {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 0.5rem;
|
||||
color: var(--text-color-secondary);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.progress-bar-container {
|
||||
width: 100%;
|
||||
height: 8px;
|
||||
background: var(--card-background);
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
|
||||
.progress-bar-fill {
|
||||
height: 100%;
|
||||
background: var(--primary-color);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.loader-animation {
|
||||
margin-top: 1.5rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
background: var(--primary-color);
|
||||
border-radius: 50%;
|
||||
animation: bounce 1.4s infinite ease-in-out both;
|
||||
|
||||
&:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
&:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.library-loader-footer {
|
||||
margin-top: 3rem;
|
||||
text-align: center;
|
||||
|
||||
.reload-button {
|
||||
padding: 0.75rem 1.25rem;
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
font-weight: 700;
|
||||
|
||||
i {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-hover-color);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgb(0 0 0 / 20%);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes bounce {
|
||||
0%, 80%, 100% {
|
||||
transform: scale(0);
|
||||
}
|
||||
|
||||
40% {
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {LibraryLoadingComponent} from './library-loading.component';
|
||||
|
||||
describe('LibraryLoadingComponent', () => {
|
||||
it('computes progress percentage and completion state from the latest update', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
|
||||
component.updateProgress('Dune', 2, 3);
|
||||
|
||||
expect(component.bookTitle()).toBe('Dune');
|
||||
expect(component.current()).toBe(2);
|
||||
expect(component.total()).toBe(3);
|
||||
expect(component.percentage()).toBe(67);
|
||||
expect(component.isComplete()).toBe(false);
|
||||
});
|
||||
|
||||
it('marks the flow complete when current reaches the total', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
|
||||
component.updateProgress('Children of Dune', 5, 5);
|
||||
|
||||
expect(component.isComplete()).toBe(true);
|
||||
expect(component.percentage()).toBe(100);
|
||||
});
|
||||
|
||||
it('truncates very long titles for display', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
|
||||
component.updateProgress('A'.repeat(200), 2, 3)
|
||||
|
||||
expect(component.bookTitle()).toBe(`${'A'.repeat(50)}...`);
|
||||
});
|
||||
|
||||
it('returns zero percent when there is no total yet', () => {
|
||||
const component = new LibraryLoadingComponent();
|
||||
|
||||
expect(component.percentage()).toBe(0);
|
||||
});
|
||||
});
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
import { computed, signal, Component } from '@angular/core';
|
||||
import {TranslocoDirective} from '@jsverse/transloco';
|
||||
|
||||
const MAX_TITLE_LENGTH = 50;
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-loading',
|
||||
standalone: true,
|
||||
imports: [TranslocoDirective],
|
||||
templateUrl: './library-loading.component.html',
|
||||
styleUrl: './library-loading.component.scss'
|
||||
})
|
||||
export class LibraryLoadingComponent {
|
||||
bookTitle = signal('');
|
||||
current = signal(0);
|
||||
total = signal(0);
|
||||
isComplete = signal(false);
|
||||
|
||||
readonly percentage = computed(() => this.total() > 0 ? Math.round((this.current() / this.total()) * 100) : 0);
|
||||
|
||||
truncateTitle(title: string): string {
|
||||
if (title.length > MAX_TITLE_LENGTH) {
|
||||
return title.substring(0, MAX_TITLE_LENGTH) + "...";
|
||||
}
|
||||
|
||||
return title;
|
||||
}
|
||||
|
||||
updateProgress(bookTitle: string, current: number, total: number): void {
|
||||
this.bookTitle.set(this.truncateTitle(bookTitle));
|
||||
this.current.set(current);
|
||||
this.total.set(total);
|
||||
this.isComplete.set(current >= total);
|
||||
}
|
||||
|
||||
onReload(): void {
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
<ng-container *transloco="let t">
|
||||
@if (progressService.state$ | async; as progress) {
|
||||
@if (progress.active) {
|
||||
<div class="rounded-lg border border-[var(--primary-color)] bg-[var(--card-background)] p-4">
|
||||
<div class="mb-2 flex items-center justify-between gap-3">
|
||||
<div class="flex min-w-0 items-center gap-2 text-[var(--primary-color)]">
|
||||
<i class="pi pi-book" aria-hidden="true"></i>
|
||||
<p class="m-0 text-sm font-semibold">{{ t('libraryCreator.loading.title') }}</p>
|
||||
</div>
|
||||
<p-tag
|
||||
[value]="t(getStatusLabelKey(progress.status))"
|
||||
[severity]="getTagSeverity(progress.status)">
|
||||
</p-tag>
|
||||
</div>
|
||||
|
||||
<div class="mb-2 break-words text-base text-zinc-200">
|
||||
@if (progress.status === 'COMPLETED') {
|
||||
{{ t('libraryCreator.loading.complete') }}
|
||||
} @else if (progress.status === 'ERROR') {
|
||||
{{ t('libraryCreator.creator.toast.createFailedSummary') }}
|
||||
} @else {
|
||||
{{ t('libraryCreator.loading.processing') }} <strong>{{ progress.currentBookTitle || progress.libraryName }}</strong>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="mb-2 text-sm text-zinc-300 tabular-nums">
|
||||
<span [innerHTML]="t('shared.metadataProgress.bookProgress', { current: getCurrentCount(progress), total: progress.expectedCount })"></span>
|
||||
</div>
|
||||
|
||||
<p-progressBar
|
||||
[style]="{ height: '15px' }"
|
||||
[value]="getProgressPercent(progress)"
|
||||
[showValue]="false">
|
||||
</p-progressBar>
|
||||
|
||||
@if (progress.status !== 'IN_PROGRESS') {
|
||||
<div class="mt-4 flex flex-wrap justify-end gap-2">
|
||||
@if (progress.libraryId !== undefined) {
|
||||
<button
|
||||
pButton
|
||||
type="button"
|
||||
[label]="t('libraryCreator.loading.openLibrary')"
|
||||
icon="pi pi-book"
|
||||
severity="info"
|
||||
size="small"
|
||||
outlined
|
||||
(click)="openLibrary(progress)">
|
||||
</button>
|
||||
}
|
||||
<button
|
||||
pButton
|
||||
type="button"
|
||||
[label]="t('shared.metadataProgress.dismissBtn')"
|
||||
icon="pi pi-times"
|
||||
severity="secondary"
|
||||
size="small"
|
||||
outlined
|
||||
(click)="dismiss()">
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</ng-container>
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {ChangeDetectionStrategy, Component, inject} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {ButtonDirective} from 'primeng/button';
|
||||
import {ProgressBar} from 'primeng/progressbar';
|
||||
import {Tag} from 'primeng/tag';
|
||||
import {TranslocoDirective} from '@jsverse/transloco';
|
||||
|
||||
import {LibraryImportProgressService, LibraryImportProgressState, LibraryImportProgressStatus} from '../../service/library-import-progress.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-import-progress-widget',
|
||||
templateUrl: './library-import-progress-widget-component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
standalone: true,
|
||||
imports: [AsyncPipe, ButtonDirective, ProgressBar, Tag, TranslocoDirective]
|
||||
})
|
||||
export class LibraryImportProgressWidgetComponent {
|
||||
protected readonly progressService = inject(LibraryImportProgressService);
|
||||
private readonly router = inject(Router);
|
||||
|
||||
getProgressPercent(state: LibraryImportProgressState): number {
|
||||
if (state.expectedCount <= 0) return 0;
|
||||
if (state.status === 'COMPLETED') return 100;
|
||||
const percent = Math.round((state.processedCount / state.expectedCount) * 100);
|
||||
return Math.min(100, Math.max(0, percent));
|
||||
}
|
||||
|
||||
getCurrentCount(state: LibraryImportProgressState): number {
|
||||
return Math.min(state.processedCount, state.expectedCount);
|
||||
}
|
||||
|
||||
getStatusLabelKey(status: LibraryImportProgressStatus): string {
|
||||
return {
|
||||
IN_PROGRESS: 'shared.metadataProgress.statusInProgress',
|
||||
COMPLETED: 'shared.metadataProgress.statusCompleted',
|
||||
ERROR: 'shared.metadataProgress.statusError',
|
||||
}[status];
|
||||
}
|
||||
|
||||
getTagSeverity(status: LibraryImportProgressStatus): 'info' | 'success' | 'danger' {
|
||||
switch (status) {
|
||||
case 'COMPLETED':
|
||||
return 'success';
|
||||
case 'ERROR':
|
||||
return 'danger';
|
||||
case 'IN_PROGRESS':
|
||||
default:
|
||||
return 'info';
|
||||
}
|
||||
}
|
||||
|
||||
dismiss(): void {
|
||||
this.progressService.clear();
|
||||
}
|
||||
|
||||
openLibrary(state: LibraryImportProgressState): void {
|
||||
if (state.libraryId === undefined) return;
|
||||
this.router.navigate(['/library', state.libraryId, 'books']).then(navigated => {
|
||||
if (navigated) {
|
||||
this.dismiss();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+3
@@ -3,6 +3,9 @@
|
||||
@if (hasMetadataTasks$ | async) {
|
||||
<app-metadata-progress-widget/>
|
||||
}
|
||||
@if (hasActiveLibraryImport$ | async) {
|
||||
<app-library-import-progress-widget/>
|
||||
}
|
||||
@if (hasPendingBookdropFiles$ | async) {
|
||||
<app-bookdrop-files-widget-component/>
|
||||
}
|
||||
|
||||
+18
@@ -6,6 +6,7 @@ import {BookdropFileService} from '../../../features/bookdrop/service/bookdrop-f
|
||||
import {getTranslocoModule} from '../../../core/testing/transloco-testing';
|
||||
import {MetadataBatchStatus} from '../../model/metadata-batch-progress.model';
|
||||
import {MetadataProgressService} from '../../service/metadata-progress.service';
|
||||
import {LibraryImportProgressService} from '../../service/library-import-progress.service';
|
||||
import {UnifiedNotificationBoxComponent} from './unified-notification-popover-component';
|
||||
|
||||
describe('UnifiedNotificationBoxComponent', () => {
|
||||
@@ -13,10 +14,12 @@ describe('UnifiedNotificationBoxComponent', () => {
|
||||
let component: UnifiedNotificationBoxComponent;
|
||||
let activeTasks$: BehaviorSubject<Record<string, unknown>>;
|
||||
let hasPendingFiles$: BehaviorSubject<boolean>;
|
||||
let hasActiveImport$: BehaviorSubject<boolean>;
|
||||
|
||||
beforeEach(async () => {
|
||||
activeTasks$ = new BehaviorSubject<Record<string, unknown>>({});
|
||||
hasPendingFiles$ = new BehaviorSubject(false);
|
||||
hasActiveImport$ = new BehaviorSubject(false);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [UnifiedNotificationBoxComponent, getTranslocoModule()],
|
||||
@@ -29,6 +32,10 @@ describe('UnifiedNotificationBoxComponent', () => {
|
||||
provide: BookdropFileService,
|
||||
useValue: {hasPendingFiles$},
|
||||
},
|
||||
{
|
||||
provide: LibraryImportProgressService,
|
||||
useValue: {hasActiveImport$},
|
||||
},
|
||||
],
|
||||
}).compileComponents();
|
||||
|
||||
@@ -72,4 +79,15 @@ describe('UnifiedNotificationBoxComponent', () => {
|
||||
hasPendingFiles$.next(true);
|
||||
expect(hasPendingFiles).toBe(true);
|
||||
});
|
||||
|
||||
it('forwards the active library import signal', () => {
|
||||
let hasActiveImport: boolean | undefined;
|
||||
component.hasActiveLibraryImport$.subscribe(value => {
|
||||
hasActiveImport = value;
|
||||
});
|
||||
|
||||
expect(hasActiveImport).toBe(false);
|
||||
hasActiveImport$.next(true);
|
||||
expect(hasActiveImport).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
+5
@@ -6,12 +6,15 @@ import {AsyncPipe} from '@angular/common';
|
||||
import {BookdropFileService} from '../../../features/bookdrop/service/bookdrop-file.service';
|
||||
import {BookdropFilesWidgetComponent} from '../../../features/bookdrop/component/bookdrop-files-widget/bookdrop-files-widget.component';
|
||||
import {MetadataProgressWidgetComponent} from '../metadata-progress-widget/metadata-progress-widget-component';
|
||||
import {LibraryImportProgressService} from '../../service/library-import-progress.service';
|
||||
import {LibraryImportProgressWidgetComponent} from '../library-import-progress-widget/library-import-progress-widget-component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-unified-notification-popover-component',
|
||||
imports: [
|
||||
LiveNotificationBoxComponent,
|
||||
MetadataProgressWidgetComponent,
|
||||
LibraryImportProgressWidgetComponent,
|
||||
AsyncPipe,
|
||||
BookdropFilesWidgetComponent
|
||||
],
|
||||
@@ -22,10 +25,12 @@ import {MetadataProgressWidgetComponent} from '../metadata-progress-widget/metad
|
||||
export class UnifiedNotificationBoxComponent {
|
||||
metadataProgressService = inject(MetadataProgressService);
|
||||
bookdropFileService = inject(BookdropFileService);
|
||||
libraryImportProgressService = inject(LibraryImportProgressService);
|
||||
|
||||
hasMetadataTasks$ = this.metadataProgressService.activeTasks$.pipe(
|
||||
map(tasks => Object.keys(tasks).length > 0)
|
||||
);
|
||||
|
||||
hasPendingBookdropFiles$ = this.bookdropFileService.hasPendingFiles$;
|
||||
hasActiveLibraryImport$ = this.libraryImportProgressService.hasActiveImport$;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { BookdropFileService } from '../../../features/bookdrop/service/bookdrop
|
||||
import { AuthService } from '../../service/auth.service';
|
||||
import { MetadataBatchProgressNotification, MetadataBatchStatus } from '../../model/metadata-batch-progress.model';
|
||||
import { MetadataProgressService } from '../../service/metadata-progress.service';
|
||||
import { LibraryImportProgressService } from '../../service/library-import-progress.service';
|
||||
import { AppVersion, VersionService } from '../../service/version.service';
|
||||
import { DialogLauncherService } from '../../services/dialog-launcher.service';
|
||||
import { LayoutService } from '../layout.service';
|
||||
@@ -42,6 +43,7 @@ describe('AppSidebarComponent', () => {
|
||||
let activeTasks$: BehaviorSubject<Record<string, MetadataBatchProgressNotification>>;
|
||||
let progressUpdates$: BehaviorSubject<MetadataBatchProgressNotification>;
|
||||
let hasPendingFiles$: BehaviorSubject<boolean>;
|
||||
let hasActiveImport$: BehaviorSubject<boolean>;
|
||||
const sidebarCollapsed = signal(false);
|
||||
const isDesktop = signal(true);
|
||||
const layoutService = {
|
||||
@@ -68,6 +70,7 @@ describe('AppSidebarComponent', () => {
|
||||
review: false,
|
||||
});
|
||||
hasPendingFiles$ = new BehaviorSubject(false);
|
||||
hasActiveImport$ = new BehaviorSubject(false);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [AppSidebarComponent, getTranslocoModule()],
|
||||
@@ -97,6 +100,7 @@ describe('AppSidebarComponent', () => {
|
||||
{ provide: AuthService, useValue: { logout: vi.fn() } },
|
||||
{ provide: MetadataProgressService, useValue: { activeTasks$, progressUpdates$ } },
|
||||
{ provide: BookdropFileService, useValue: { hasPendingFiles$ } },
|
||||
{ provide: LibraryImportProgressService, useValue: { hasActiveImport$ } },
|
||||
{ provide: VersionService, useValue: { getVersion: vi.fn(() => versionInfo) } },
|
||||
{ provide: LayoutService, useValue: layoutService },
|
||||
{ provide: UserService, useValue: { currentUser } },
|
||||
@@ -247,7 +251,7 @@ describe('AppSidebarComponent', () => {
|
||||
expect(sidebar.notificationPopoverOrigin()).toBeNull();
|
||||
});
|
||||
|
||||
it('aggregates metadata tasks and pending bookdrop files into the sidebar badge count', () => {
|
||||
it('aggregates metadata tasks, library imports, and pending bookdrop files into the sidebar badge count', () => {
|
||||
const sidebar = component as unknown as {
|
||||
completedTaskCount: number;
|
||||
shouldShowNotificationBadge: boolean;
|
||||
@@ -272,8 +276,9 @@ describe('AppSidebarComponent', () => {
|
||||
},
|
||||
});
|
||||
hasPendingFiles$.next(true);
|
||||
hasActiveImport$.next(true);
|
||||
|
||||
expect(sidebar.completedTaskCount).toBe(3);
|
||||
expect(sidebar.completedTaskCount).toBe(4);
|
||||
expect(sidebar.shouldShowNotificationBadge).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ import { VersionService } from '../../service/version.service';
|
||||
import { MetadataProgressService } from '../../service/metadata-progress.service';
|
||||
import { BookdropFileService } from '../../../features/bookdrop/service/bookdrop-file.service';
|
||||
import { MetadataBatchProgressNotification, MetadataBatchStatus } from '../../model/metadata-batch-progress.model';
|
||||
import { LibraryImportProgressService } from '../../service/library-import-progress.service';
|
||||
|
||||
const DOCUMENTATION_URL = 'https://grimmory.org/docs/getting-started';
|
||||
const ABOVE_ALIGN_LEFT: ConnectedPosition[] = [
|
||||
@@ -139,6 +140,7 @@ export class AppSidebarComponent {
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly metadataProgressService = inject(MetadataProgressService);
|
||||
private readonly bookdropFileService = inject(BookdropFileService);
|
||||
private readonly libraryImportProgressService = inject(LibraryImportProgressService);
|
||||
|
||||
readonly currentUser = this.userService.currentUser;
|
||||
private readonly allAuthors = this.authorService.allAuthors;
|
||||
@@ -231,6 +233,7 @@ export class AppSidebarComponent {
|
||||
protected progressHighlight = false;
|
||||
protected completedTaskCount = 0;
|
||||
protected hasPendingBookdropFiles = false;
|
||||
protected hasActiveLibraryImport = false;
|
||||
|
||||
private readonly latestTasks: Record<string, MetadataBatchProgressNotification> = {};
|
||||
|
||||
@@ -250,6 +253,13 @@ export class AppSidebarComponent {
|
||||
this.hasPendingBookdropFiles = hasPending;
|
||||
this.updateCompletedTaskCount();
|
||||
});
|
||||
|
||||
this.libraryImportProgressService.hasActiveImport$
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe((hasActive) => {
|
||||
this.hasActiveLibraryImport = hasActive;
|
||||
this.updateCompletedTaskCount();
|
||||
});
|
||||
}
|
||||
|
||||
openSearch(): void {
|
||||
@@ -383,6 +393,7 @@ export class AppSidebarComponent {
|
||||
private updateCompletedTaskCount(): void {
|
||||
const metadataTaskCount = Object.keys(this.latestTasks).length;
|
||||
const bookdropFileTaskCount = this.hasPendingBookdropFiles ? 1 : 0;
|
||||
this.completedTaskCount = metadataTaskCount + bookdropFileTaskCount;
|
||||
const libraryImportTaskCount = this.hasActiveLibraryImport ? 1 : 0;
|
||||
this.completedTaskCount = metadataTaskCount + bookdropFileTaskCount + libraryImportTaskCount;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {afterEach, describe, expect, it} from 'vitest';
|
||||
|
||||
import {LibraryImportProgressService, LibraryImportProgressState} from './library-import-progress.service';
|
||||
|
||||
describe('LibraryImportProgressService', () => {
|
||||
afterEach(() => {
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('tracks progress from start through completion and clear', () => {
|
||||
TestBed.configureTestingModule({providers: [LibraryImportProgressService]});
|
||||
const service = TestBed.inject(LibraryImportProgressService);
|
||||
let latest: LibraryImportProgressState | undefined;
|
||||
service.state$.subscribe(state => {
|
||||
latest = state;
|
||||
});
|
||||
|
||||
service.start('Main Library', 2);
|
||||
service.attachLibrary(7);
|
||||
service.recordBookAdded('First');
|
||||
|
||||
expect(latest).toEqual({
|
||||
active: true,
|
||||
libraryId: 7,
|
||||
libraryName: 'Main Library',
|
||||
expectedCount: 2,
|
||||
processedCount: 1,
|
||||
currentBookTitle: 'First',
|
||||
status: 'IN_PROGRESS',
|
||||
});
|
||||
|
||||
service.fail();
|
||||
|
||||
expect(latest?.status).toBe('ERROR');
|
||||
|
||||
service.start('Main Library', 2);
|
||||
service.recordBookAdded('First');
|
||||
service.recordBookAdded('Second');
|
||||
|
||||
expect(latest?.status).toBe('COMPLETED');
|
||||
|
||||
service.clear();
|
||||
|
||||
expect(latest?.active).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {BehaviorSubject} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
|
||||
export type LibraryImportProgressStatus = 'IN_PROGRESS' | 'COMPLETED' | 'ERROR';
|
||||
|
||||
export interface LibraryImportProgressState {
|
||||
active: boolean;
|
||||
libraryId?: number;
|
||||
libraryName: string;
|
||||
expectedCount: number;
|
||||
processedCount: number;
|
||||
currentBookTitle?: string;
|
||||
status: LibraryImportProgressStatus;
|
||||
}
|
||||
|
||||
const EMPTY_STATE: LibraryImportProgressState = {
|
||||
active: false,
|
||||
libraryName: '',
|
||||
expectedCount: 0,
|
||||
processedCount: 0,
|
||||
status: 'COMPLETED',
|
||||
};
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LibraryImportProgressService {
|
||||
private readonly stateSubject = new BehaviorSubject<LibraryImportProgressState>(EMPTY_STATE);
|
||||
|
||||
readonly state$ = this.stateSubject.asObservable();
|
||||
readonly hasActiveImport$ = this.state$.pipe(map(state => state.active));
|
||||
|
||||
start(libraryName: string, expectedCount: number): void {
|
||||
if (expectedCount <= 0) {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
this.stateSubject.next({
|
||||
active: false,
|
||||
libraryName,
|
||||
expectedCount,
|
||||
processedCount: 0,
|
||||
status: 'IN_PROGRESS',
|
||||
});
|
||||
}
|
||||
|
||||
attachLibrary(libraryId: number): void {
|
||||
const state = this.stateSubject.value;
|
||||
if (state.expectedCount <= 0) return;
|
||||
this.stateSubject.next({...state, libraryId});
|
||||
}
|
||||
|
||||
recordBookAdded(bookTitle: string): void {
|
||||
const state = this.stateSubject.value;
|
||||
if (state.expectedCount <= 0 || state.status !== 'IN_PROGRESS') return;
|
||||
|
||||
const processedCount = Math.min(state.processedCount + 1, state.expectedCount);
|
||||
this.stateSubject.next({
|
||||
...state,
|
||||
active: true,
|
||||
processedCount,
|
||||
currentBookTitle: bookTitle,
|
||||
status: processedCount >= state.expectedCount
|
||||
? 'COMPLETED'
|
||||
: 'IN_PROGRESS',
|
||||
});
|
||||
}
|
||||
|
||||
fail(): void {
|
||||
const state = this.stateSubject.value;
|
||||
if (state.expectedCount <= 0 || state.status !== 'IN_PROGRESS') return;
|
||||
if (!state.active) {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
this.stateSubject.next({...state, status: 'ERROR'});
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.stateSubject.next(EMPTY_STATE);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user