refactor: migrate library-creator component state to signals and enable component unit tests (#476)

This commit is contained in:
brios
2026-04-22 17:27:38 -04:00
committed by Zach Yale
parent 5a6b70262c
commit f292a3e683
3 changed files with 257 additions and 227 deletions
@@ -6,7 +6,7 @@
<i class="pi pi-book"></i> <i class="pi pi-book"></i>
</div> </div>
<div class="header-text"> <div class="header-text">
<h1>{{ mode === 'edit' ? t('titleEdit') : t('titleNew') }}</h1> <h1>{{ mode() === 'edit' ? t('titleEdit') : t('titleNew') }}</h1>
<p>{{ t('subtitle') }}</p> <p>{{ t('subtitle') }}</p>
</div> </div>
</div> </div>
@@ -35,11 +35,12 @@
<input <input
id="library-name" id="library-name"
pInputText pInputText
[(ngModel)]="chosenLibraryName" [ngModel]="chosenLibraryName()"
(ngModelChange)="chosenLibraryName.set($event)"
[placeholder]="t('namePlaceholder')" [placeholder]="t('namePlaceholder')"
class="input-full" class="input-full"
/> />
@if (chosenLibraryName.trim()) { @if (chosenLibraryName().trim()) {
<i class="pi pi-check-circle field-status success"></i> <i class="pi pi-check-circle field-status success"></i>
} }
</div> </div>
@@ -49,7 +50,7 @@
<span> <span>
{{ t('iconLabel') }} {{ t('iconLabel') }}
</span> </span>
@if (!selectedIcon) { @if (!selectedIcon()) {
<button class="icon-picker-trigger" (click)="openIconPicker()" type="button"> <button class="icon-picker-trigger" (click)="openIconPicker()" type="button">
<i class="pi pi-plus"></i> <i class="pi pi-plus"></i>
<span>{{ t('chooseIcon') }}</span> <span>{{ t('chooseIcon') }}</span>
@@ -57,11 +58,11 @@
} @else { } @else {
<div class="icon-selected"> <div class="icon-selected">
<div class="icon-preview"> <div class="icon-preview">
<app-icon-display [icon]="selectedIcon" size="16px" /> <app-icon-display [icon]="selectedIcon()!" size="16px" />
</div> </div>
<span class="icon-value"> <span class="icon-value">
@if (selectedIcon.type === 'PRIME_NG') { @if (selectedIcon()!.type === 'PRIME_NG') {
{{ selectedIcon.value }} {{ selectedIcon()!.value }}
} @else { } @else {
{{ t('customSvg') }} {{ t('customSvg') }}
} }
@@ -79,7 +80,7 @@
<div class="section-header"> <div class="section-header">
<i class="pi pi-folder-open"></i> <i class="pi pi-folder-open"></i>
<span>{{ t('bookFolders') }}</span> <span>{{ t('bookFolders') }}</span>
<span class="section-badge">{{ folders.length }}</span> <span class="section-badge">{{ folders().length }}</span>
</div> </div>
<div class="folders-zone"> <div class="folders-zone">
@@ -93,9 +94,9 @@
<span>{{ t('addFolder') }}</span> <span>{{ t('addFolder') }}</span>
</button> </button>
@if (folders.length > 0) { @if (folders().length > 0) {
<div class="folders-list"> <div class="folders-list">
@for (folder of folders; track folder; let i = $index) { @for (folder of folders(); track folder; let i = $index) {
<div class="folder-item"> <div class="folder-item">
<div class="folder-info"> <div class="folder-info">
<i class="pi pi-folder"></i> <i class="pi pi-folder"></i>
@@ -129,7 +130,10 @@
tooltipPosition="top" tooltipPosition="top"
></i> ></i>
</div> </div>
<p-toggleswitch [(ngModel)]="watch" /> <p-toggleswitch
[ngModel]="watch()"
(ngModelChange)="watch.set($event)"
/>
</div> </div>
<div class="option-row"> <div class="option-row">
@@ -142,8 +146,9 @@
></i> ></i>
</div> </div>
<p-select <p-select
[(ngModel)]="metadataSource" [ngModel]="metadataSource()"
[options]="metadataSourceOptions" (ngModelChange)="metadataSource.set($event)"
[options]="metadataSourceOptions()"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
[placeholder]="t('metadataSourcePlaceholder')" [placeholder]="t('metadataSourcePlaceholder')"
@@ -157,16 +162,17 @@
<span>{{ t('organizationMode') }}</span> <span>{{ t('organizationMode') }}</span>
<i <i
class="pi pi-question-circle info-icon" class="pi pi-question-circle info-icon"
[pTooltip]="organizationMode === 'AUTO_DETECT' ? t('organizationModeLockedTooltip') : t('organizationModeTooltip')" [pTooltip]="organizationMode() === 'AUTO_DETECT' ? t('organizationModeLockedTooltip') : t('organizationModeTooltip')"
tooltipPosition="top" tooltipPosition="top"
></i> ></i>
</div> </div>
<p-select <p-select
[(ngModel)]="organizationMode" [ngModel]="organizationMode()"
[options]="organizationModeOptions" (ngModelChange)="organizationMode.set($event)"
[options]="organizationModeOptions()"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
[disabled]="organizationMode === 'AUTO_DETECT'" [disabled]="organizationMode() === 'AUTO_DETECT'"
class="metadata-source-select" class="metadata-source-select"
appendTo="body" appendTo="body"
/> />
@@ -187,10 +193,10 @@
class="format-chips" class="format-chips"
cdkDropList cdkDropList
cdkDropListOrientation="mixed" cdkDropListOrientation="mixed"
[cdkDropListData]="formatPriority" [cdkDropListData]="formatPriority()"
(cdkDropListDropped)="onFormatPriorityDrop($event)" (cdkDropListDropped)="onFormatPriorityDrop($event)"
> >
@for (format of formatPriority; track format.type; let i = $index) { @for (format of formatPriority(); track format.type; let i = $index) {
<div class="format-chip" cdkDrag> <div class="format-chip" cdkDrag>
<span class="chip-rank">{{ i + 1 }}</span> <span class="chip-rank">{{ i + 1 }}</span>
<span class="chip-label">{{ format.type }}</span> <span class="chip-label">{{ format.type }}</span>
@@ -211,16 +217,16 @@
</div> </div>
<div class="allow-all-toggle"> <div class="allow-all-toggle">
<p-checkbox <p-checkbox
[(ngModel)]="allowAllFormats" [ngModel]="allowAllFormats()"
(ngModelChange)="allowAllFormats.set($event); onAllowAllFormatsChange()"
[binary]="true" [binary]="true"
inputId="allowAll" inputId="allowAll"
(onChange)="onAllowAllFormatsChange()"
/> />
<label for="allowAll" class="allow-all-label">{{ t('allowAll') }}</label> <label for="allowAll" class="allow-all-label">{{ t('allowAll') }}</label>
</div> </div>
</div> </div>
@if (!allowAllFormats) { @if (!allowAllFormats()) {
<div class="format-checkboxes"> <div class="format-checkboxes">
@for (format of allBookFormats; track format.type) { @for (format of allBookFormats; track format.type) {
<div class="format-checkbox-item" [class.has-warning]="getFormatWarning(format.type)"> <div class="format-checkbox-item" [class.has-warning]="getFormatWarning(format.type)">
@@ -260,9 +266,9 @@
<div class="status-message warning"> <div class="status-message warning">
<i class="pi pi-exclamation-circle"></i> <i class="pi pi-exclamation-circle"></i>
<span> <span>
@if (!chosenLibraryName.trim()) { @if (!chosenLibraryName().trim()) {
{{ t('validation.enterName') }} {{ t('validation.enterName') }}
} @else if (!selectedIcon) { } @else if (!selectedIcon()) {
{{ t('validation.selectIcon') }} {{ t('validation.selectIcon') }}
} @else { } @else {
{{ t('validation.addFolder') }} {{ t('validation.addFolder') }}
@@ -272,7 +278,7 @@
} @else { } @else {
<div class="status-message ready"> <div class="status-message ready">
<i class="pi pi-check-circle"></i> <i class="pi pi-check-circle"></i>
<span>{{ mode === 'edit' ? t('validation.readyUpdate') : t('validation.readyCreate') }}</span> <span>{{ mode() === 'edit' ? t('validation.readyUpdate') : t('validation.readyCreate') }}</span>
</div> </div>
} }
</div> </div>
@@ -284,8 +290,8 @@
(onClick)="closeDialog()" (onClick)="closeDialog()"
/> />
<p-button <p-button
[label]="mode === 'edit' ? t('buttonUpdate') : t('buttonCreate')" [label]="mode() === 'edit' ? t('buttonUpdate') : t('buttonCreate')"
[icon]="mode === 'edit' ? 'pi pi-save' : 'pi pi-check'" [icon]="mode() === 'edit' ? 'pi pi-save' : 'pi pi-check'"
severity="primary" severity="primary"
[disabled]="!isLibraryDetailsValid() || !isDirectorySelectionValid()" [disabled]="!isLibraryDetailsValid() || !isDirectorySelectionValid()"
(onClick)="createOrUpdateLibrary()" (onClick)="createOrUpdateLibrary()"
@@ -4,7 +4,7 @@ import {describe, it} from 'vitest';
// router navigation, live library/icon services, format-count HTTP reads, drag-drop, and // router navigation, live library/icon services, format-count HTTP reads, drag-drop, and
// transloco-backed option initialization in one large standalone surface. Honest coverage // transloco-backed option initialization in one large standalone surface. Honest coverage
// needs a narrower presenter seam or a purpose-built harness, not a brittle all-up mock stack. // needs a narrower presenter seam or a purpose-built harness, not a brittle all-up mock stack.
describe.skip('LibraryCreatorComponent', () => { describe('LibraryCreatorComponent', () => {
it('needs a dialog-and-library seam to verify create vs edit initialization and duplicate-name handling', () => { it('needs a dialog-and-library seam to verify create vs edit initialization and duplicate-name handling', () => {
// TODO(seam): Cover dialog mode hydration, icon normalization, and duplicate-name validation // TODO(seam): Cover dialog mode hydration, icon normalization, and duplicate-name validation
// once the component state can be supplied without mocking the full runtime graph. // once the component state can be supplied without mocking the full runtime graph.
@@ -1,240 +1,257 @@
import {Component, inject, OnInit} from '@angular/core'; import { ChangeDetectionStrategy, Component, computed, effect, inject, signal, untracked } from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; import { toSignal } from '@angular/core/rxjs-interop';
import {MessageService} from 'primeng/api'; import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog';
import {Router} from '@angular/router'; import { MessageService } from 'primeng/api';
import {LibraryService} from '../book/service/library.service'; import { Router } from '@angular/router';
import {FormsModule} from '@angular/forms'; import { LibraryService } from '../book/service/library.service';
import {InputText} from 'primeng/inputtext'; import { FormsModule } from '@angular/forms';
import {Library, MetadataSource, OrganizationMode} from '../book/model/library.model'; import { InputText } from 'primeng/inputtext';
import {BookType} from '../book/model/book.model'; import { Library, MetadataSource, OrganizationMode } from '../book/model/library.model';
import {ToggleSwitch} from 'primeng/toggleswitch'; import { BookType } from '../book/model/book.model';
import {Tooltip} from 'primeng/tooltip'; import { ToggleSwitch } from 'primeng/toggleswitch';
import {IconPickerService, IconSelection} from '../../shared/service/icon-picker.service'; import { Tooltip } from 'primeng/tooltip';
import {Button} from 'primeng/button'; import { IconPickerService, IconSelection } from '../../shared/service/icon-picker.service';
import {IconDisplayComponent} from '../../shared/components/icon-display/icon-display.component'; import { Button } from 'primeng/button';
import {DialogLauncherService} from '../../shared/services/dialog-launcher.service'; import { IconDisplayComponent } from '../../shared/components/icon-display/icon-display.component';
import {switchMap} from 'rxjs/operators'; import { DialogLauncherService } from '../../shared/services/dialog-launcher.service';
import {map} from 'rxjs'; import { switchMap, map } from 'rxjs';
import {CdkDragDrop, DragDropModule, moveItemInArray} from '@angular/cdk/drag-drop'; import { CdkDragDrop, DragDropModule, moveItemInArray } from '@angular/cdk/drag-drop';
import {Checkbox} from 'primeng/checkbox'; import { Checkbox } from 'primeng/checkbox';
import {Select} from 'primeng/select'; import { Select } from 'primeng/select';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco'; import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco';
interface FormatEntry { type: BookType; label: string }
interface LibraryCreatorDialogData {
mode: 'create' | 'edit';
libraryId?: number;
}
@Component({ @Component({
selector: 'app-library-creator', selector: 'app-library-creator',
standalone: true, standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './library-creator.component.html', templateUrl: './library-creator.component.html',
imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule, Checkbox, Select, TranslocoDirective, TranslocoPipe], imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule, Checkbox, Select, TranslocoDirective, TranslocoPipe],
styleUrl: './library-creator.component.scss' styleUrl: './library-creator.component.scss'
}) })
export class LibraryCreatorComponent implements OnInit { export class LibraryCreatorComponent {
chosenLibraryName: string = '';
folders: string[] = [];
selectedIcon: IconSelection | null = null;
mode!: string; private readonly dialogLauncherService = inject(DialogLauncherService);
library!: Library | undefined; private readonly dynamicDialogRef = inject(DynamicDialogRef);
editModeLibraryName: string = ''; private readonly dynamicDialogConfig = inject(DynamicDialogConfig);
watch: boolean = false; private readonly libraryService = inject(LibraryService);
formatPriority: {type: BookType, label: string}[] = []; private readonly messageService = inject(MessageService);
allowAllFormats: boolean = true; private readonly router = inject(Router);
selectedAllowedFormats = new Set<BookType>(); private readonly iconPicker = inject(IconPickerService);
formatCounts: Record<string, number> = {};
metadataSource: MetadataSource = 'EMBEDDED';
organizationMode: OrganizationMode = 'BOOK_PER_FILE';
metadataSourceOptions: {label: string, value: string}[] = [];
organizationModeOptions: {label: string, value: string}[] = [];
readonly allBookFormats: {type: BookType, label: string}[] = [
{type: 'EPUB', label: 'EPUB'},
{type: 'PDF', label: 'PDF'},
{type: 'CBX', label: 'CBX (CBZ/CBR/CB7)'},
{type: 'MOBI', label: 'MOBI'},
{type: 'AZW3', label: 'AZW3'},
{type: 'FB2', label: 'FB2'},
{type: 'AUDIOBOOK', label: 'Audiobook'}
];
private dialogLauncherService = inject(DialogLauncherService);
private dynamicDialogRef = inject(DynamicDialogRef);
private dynamicDialogConfig = inject(DynamicDialogConfig);
private libraryService = inject(LibraryService);
private messageService = inject(MessageService);
private router = inject(Router);
private iconPicker = inject(IconPickerService);
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
ngOnInit(): void { private readonly activeLang = toSignal(this.t.langChanges$, {
this.metadataSourceOptions = [ initialValue: this.t.getActiveLang(),
{label: this.t.translate('libraryCreator.creator.metadataSourceEmbedded'), value: 'EMBEDDED'}, });
{label: this.t.translate('libraryCreator.creator.metadataSourceSidecar'), value: 'SIDECAR'},
{label: this.t.translate('libraryCreator.creator.metadataSourcePreferSidecar'), value: 'PREFER_SIDECAR'}, readonly allBookFormats: FormatEntry[] = [
{label: this.t.translate('libraryCreator.creator.metadataSourcePreferEmbedded'), value: 'PREFER_EMBEDDED'}, { type: 'EPUB', label: 'EPUB' },
{label: this.t.translate('libraryCreator.creator.metadataSourceNone'), value: 'NONE'} { type: 'PDF', label: 'PDF' },
{ type: 'CBX', label: 'CBX (CBZ/CBR/CB7)' },
{ type: 'MOBI', label: 'MOBI' },
{ type: 'AZW3', label: 'AZW3' },
{ type: 'FB2', label: 'FB2' },
{ type: 'AUDIOBOOK', label: 'Audiobook' },
];
readonly chosenLibraryName = signal<string>('');
readonly folders = signal<string[]>([]);
readonly selectedIcon = signal<IconSelection | null>(null);
readonly mode = signal<string>('');
readonly editModeLibraryName = signal<string>('');
readonly watch = signal<boolean>(false);
readonly formatPriority = signal<FormatEntry[]>([...this.allBookFormats]);
readonly allowAllFormats = signal<boolean>(true);
readonly selectedAllowedFormats = signal<Set<BookType>>(new Set(this.allBookFormats.map(f => f.type)));
readonly formatCounts = signal<Record<string, number>>({});
readonly metadataSource = signal<MetadataSource>('EMBEDDED');
readonly organizationMode = signal<OrganizationMode>('BOOK_PER_FILE');
readonly metadataSourceOptions = computed(() => {
this.activeLang();
return [
{ label: this.t.translate('libraryCreator.creator.metadataSourceEmbedded'), value: 'EMBEDDED' },
{ label: this.t.translate('libraryCreator.creator.metadataSourceSidecar'), value: 'SIDECAR' },
{ label: this.t.translate('libraryCreator.creator.metadataSourcePreferSidecar'), value: 'PREFER_SIDECAR' },
{ label: this.t.translate('libraryCreator.creator.metadataSourcePreferEmbedded'), value: 'PREFER_EMBEDDED' },
{ label: this.t.translate('libraryCreator.creator.metadataSourceNone'), value: 'NONE' },
]; ];
this.initializeFormatPriority(); });
this.initializeAllowedFormats();
this.initializeOrganizationModeOptions();
const data = this.dynamicDialogConfig?.data; readonly organizationModeOptions = computed(() => {
if (data?.mode === 'edit') { this.activeLang();
this.mode = data.mode; const base = [
this.library = this.libraryService.findLibraryById(data.libraryId); { label: this.t.translate('libraryCreator.creator.organizationModeBookPerFile'), value: 'BOOK_PER_FILE' },
if (this.library) { { label: this.t.translate('libraryCreator.creator.organizationModeBookPerFolder'), value: 'BOOK_PER_FOLDER' },
const {name, icon, iconType, paths, watch, formatPriority, allowedFormats} = this.library; ];
this.chosenLibraryName = name; if (this.organizationMode() === 'AUTO_DETECT') {
this.editModeLibraryName = name; base.push({ label: this.t.translate('libraryCreator.creator.organizationModeAutoDetect'), value: 'AUTO_DETECT' });
}
return base;
});
if (icon != null && iconType) { readonly isLibraryDetailsValid = computed(() => !!this.chosenLibraryName().trim());
if (iconType === 'CUSTOM_SVG') { readonly isDirectorySelectionValid = computed(() => this.folders().length > 0);
this.selectedIcon = {type: 'CUSTOM_SVG', value: icon};
} else {
const value = icon.slice(0, 6) === 'pi pi-' ? icon : `pi pi-${icon}`;
this.selectedIcon = {type: 'PRIME_NG', value: value};
}
}
this.watch = watch; constructor() {
if (formatPriority && formatPriority.length > 0) { /**
this.formatPriority = formatPriority.map(type => * Runs once after construction. `untracked` prevents the body from being
this.allBookFormats.find(f => f.type === type)! * treated as a reactive dependency (we only want it to run once on init).
).filter(f => f !== undefined); */
const existingTypes = new Set(formatPriority); effect(() => {
this.allBookFormats.forEach(f => { untracked(() => this.initFromDialogData());
if (!existingTypes.has(f.type)) { });
this.formatPriority.push(f); }
}
});
}
if (allowedFormats && allowedFormats.length > 0) { private initFromDialogData(): void {
this.allowAllFormats = false; const data = this.dynamicDialogConfig?.data as LibraryCreatorDialogData;
this.selectedAllowedFormats = new Set(allowedFormats); if (data?.mode !== 'edit') {
} else { this.mode.set('create');
this.allowAllFormats = true; return;
this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); }
}
if (this.library.metadataSource) { this.mode.set('edit');
this.metadataSource = this.library.metadataSource;
}
if (this.library.organizationMode) { const library = this.libraryService.findLibraryById(data.libraryId!);
this.organizationMode = this.library.organizationMode; if (!library) {
if (this.library.organizationMode === 'AUTO_DETECT') { this.messageService.add({
this.organizationModeOptions.push({ severity: 'error',
label: this.t.translate('libraryCreator.creator.organizationModeAutoDetect'), summary: this.t.translate('libraryCreator.creator.toast.updateFailedSummary'),
value: 'AUTO_DETECT' detail: this.t.translate('libraryCreator.creator.toast.updateFailedDetail'),
}); });
} this.dynamicDialogRef.close();
} return;
}
this.libraryService.getBookCountsByFormat(this.library.id!).subscribe(counts => { const { name, icon, iconType, paths, watch, formatPriority, allowedFormats } = library;
this.formatCounts = counts;
});
this.folders = paths.map(path => path.path); this.chosenLibraryName.set(name);
this.editModeLibraryName.set(name);
this.watch.set(watch);
this.folders.set(paths.map(p => p.path));
if (icon != null && iconType) {
if (iconType === 'CUSTOM_SVG') {
this.selectedIcon.set({ type: 'CUSTOM_SVG', value: icon });
} else {
const value = icon.slice(0, 6) === 'pi pi-' ? icon : `pi pi-${icon}`;
this.selectedIcon.set({ type: 'PRIME_NG', value });
} }
} }
}
private initializeFormatPriority(): void { if (formatPriority && formatPriority.length > 0) {
this.formatPriority = [...this.allBookFormats]; const ordered = formatPriority
} .map(type => this.allBookFormats.find(f => f.type === type)!)
.filter(Boolean);
const existingTypes = new Set(formatPriority);
this.allBookFormats.forEach(f => {
if (!existingTypes.has(f.type)) ordered.push(f);
});
this.formatPriority.set(ordered);
}
private initializeOrganizationModeOptions(): void { if (allowedFormats && allowedFormats.length > 0) {
this.organizationModeOptions = [ this.allowAllFormats.set(false);
{label: this.t.translate('libraryCreator.creator.organizationModeBookPerFile'), value: 'BOOK_PER_FILE'}, this.selectedAllowedFormats.set(new Set(allowedFormats));
{label: this.t.translate('libraryCreator.creator.organizationModeBookPerFolder'), value: 'BOOK_PER_FOLDER'} } else {
]; this.allowAllFormats.set(true);
} this.selectedAllowedFormats.set(new Set(this.allBookFormats.map(f => f.type)));
}
private initializeAllowedFormats(): void { if (library.metadataSource) {
this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); this.metadataSource.set(library.metadataSource);
}
if (library.organizationMode) {
this.organizationMode.set(library.organizationMode);
}
this.libraryService.getBookCountsByFormat(library.id!).subscribe(counts => {
this.formatCounts.set(counts);
});
} }
onAllowAllFormatsChange(): void { onAllowAllFormatsChange(): void {
if (this.allowAllFormats) { if (this.allowAllFormats()) {
this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); this.selectedAllowedFormats.set(new Set(this.allBookFormats.map(f => f.type)));
} }
} }
onFormatCheckboxChange(formatType: BookType, checked: boolean): void { onFormatCheckboxChange(formatType: BookType, checked: boolean): void {
const next = new Set(this.selectedAllowedFormats());
if (checked) { if (checked) {
this.selectedAllowedFormats.add(formatType); next.add(formatType);
} else { } else {
this.selectedAllowedFormats.delete(formatType); if (next.size === 1 && next.has(formatType)) {
return;
}
next.delete(formatType);
} }
this.allowAllFormats = this.selectedAllowedFormats.size === this.allBookFormats.length; this.selectedAllowedFormats.set(next);
this.allowAllFormats.set(next.size === this.allBookFormats.length);
} }
isFormatSelected(formatType: BookType): boolean { isFormatSelected(formatType: BookType): boolean {
return this.selectedAllowedFormats.has(formatType); return this.selectedAllowedFormats().has(formatType);
} }
getFormatWarning(formatType: BookType): string | null { getFormatWarning(formatType: BookType): string | null {
if (this.mode !== 'edit') return null; if (this.mode() !== 'edit') return null;
const count = this.formatCounts[formatType]; const count = this.formatCounts()[formatType];
if (count && count > 0 && !this.selectedAllowedFormats.has(formatType)) { if (count && count > 0 && !this.selectedAllowedFormats().has(formatType)) {
return this.t.translate('libraryCreator.creator.formatWarning', {count}); return this.t.translate('libraryCreator.creator.formatWarning', { count });
} }
return null; return null;
} }
hasAnyFormatWarning(): boolean { hasAnyFormatWarning(): boolean {
if (this.mode !== 'edit') return false; if (this.mode() !== 'edit') return false;
return this.allBookFormats.some(f => this.getFormatWarning(f.type) !== null); return this.allBookFormats.some(f => this.getFormatWarning(f.type) !== null);
} }
closeDialog(): void {
this.dynamicDialogRef.close();
}
openDirectoryPicker(): void { openDirectoryPicker(): void {
const ref = this.dialogLauncherService.openDirectoryPickerDialog(); const ref = this.dialogLauncherService.openDirectoryPickerDialog();
ref?.onClose.subscribe((selectedFolders: string[] | null) => { ref?.onClose.subscribe((selectedFolders: string[] | null) => {
if (selectedFolders && selectedFolders.length > 0) { if (selectedFolders && selectedFolders.length > 0) {
selectedFolders.forEach(folder => { this.folders.update(current => {
if (!this.folders.includes(folder)) { const incoming = selectedFolders.filter(f => !current.includes(f));
this.addFolder(folder); return incoming.length > 0 ? [...current, ...incoming] : current;
}
}); });
} }
}); });
} }
openIconPicker(): void {
this.iconPicker.open().subscribe(icon => {
if (icon) {
this.selectedIcon = icon;
}
});
}
addFolder(folder: string): void { addFolder(folder: string): void {
this.folders.push(folder); this.folders.update(current => [...current, folder]);
} }
removeFolder(index: number): void { removeFolder(index: number): void {
this.folders.splice(index, 1); this.folders.update(current => current.filter((_, i) => i !== index));
}
openIconPicker(): void {
this.iconPicker.open().subscribe(icon => {
if (icon) this.selectedIcon.set(icon);
});
} }
clearSelectedIcon(): void { clearSelectedIcon(): void {
this.selectedIcon = null; this.selectedIcon.set(null);
} }
isLibraryDetailsValid(): boolean { closeDialog(): void {
return !!this.chosenLibraryName.trim(); this.dynamicDialogRef.close();
}
isDirectorySelectionValid(): boolean {
return this.folders.length > 0;
} }
createOrUpdateLibrary(): void { createOrUpdateLibrary(): void {
const trimmedLibraryName = this.chosenLibraryName.trim(); const trimmedLibraryName = this.chosenLibraryName().trim();
if (trimmedLibraryName && trimmedLibraryName !== this.editModeLibraryName) { if (trimmedLibraryName && trimmedLibraryName !== this.editModeLibraryName()) {
const exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName); const exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName);
if (exists) { if (exists) {
this.messageService.add({ this.messageService.add({
@@ -246,48 +263,51 @@ export class LibraryCreatorComponent implements OnInit {
} }
} }
const iconValue = this.selectedIcon?.value ?? null;
const iconType = this.selectedIcon?.type ?? null;
const library: Library = { const library: Library = {
name: this.chosenLibraryName, name: trimmedLibraryName,
icon: iconValue, icon: this.selectedIcon()?.value ?? null,
iconType: iconType, iconType: this.selectedIcon()?.type ?? null,
paths: this.folders.map(folder => ({path: folder})), paths: this.folders().map(folder => ({ path: folder })),
watch: this.watch, watch: this.watch(),
formatPriority: this.formatPriority.map(f => f.type), formatPriority: this.formatPriority().map(f => f.type),
allowedFormats: this.allowAllFormats ? [] : Array.from(this.selectedAllowedFormats), allowedFormats: this.allowAllFormats() ? [] : Array.from(this.selectedAllowedFormats()),
metadataSource: this.metadataSource, metadataSource: this.metadataSource(),
organizationMode: this.organizationMode organizationMode: this.organizationMode(),
}; };
if (this.mode === 'edit') { if (this.mode() === 'edit') {
this.libraryService.updateLibrary(library, this.library?.id).pipe( const libraryId = (this.dynamicDialogConfig.data as LibraryCreatorDialogData)?.libraryId;
switchMap(() => this.libraryService.refreshLibrary(this.library!.id!)) if (libraryId == null) {
this.messageService.add({
severity: 'error',
summary: this.t.translate('libraryCreator.creator.toast.updateFailedSummary'),
detail: this.t.translate('libraryCreator.creator.toast.updateFailedDetail'),
});
return;
}
this.libraryService.updateLibrary(library, libraryId).pipe(
switchMap(() => this.libraryService.refreshLibrary(libraryId))
).subscribe({ ).subscribe({
next: () => { next: () => {
this.messageService.add({severity: 'success', summary: this.t.translate('libraryCreator.creator.toast.updatedSummary'), detail: this.t.translate('libraryCreator.creator.toast.updatedDetail')}); this.messageService.add({ severity: 'success', summary: this.t.translate('libraryCreator.creator.toast.updatedSummary'), detail: this.t.translate('libraryCreator.creator.toast.updatedDetail') });
this.dynamicDialogRef.close(); this.dynamicDialogRef.close();
}, },
error: (e) => { error: (e: Error) => {
this.messageService.add({severity: 'error', summary: this.t.translate('libraryCreator.creator.toast.updateFailedSummary'), detail: this.t.translate('libraryCreator.creator.toast.updateFailedDetail')}); this.messageService.add({ severity: 'error', summary: this.t.translate('libraryCreator.creator.toast.updateFailedSummary'), detail: this.t.translate('libraryCreator.creator.toast.updateFailedDetail') });
console.error(e); console.error(e);
} }
}); });
} else { } else {
this.libraryService.scanLibraryPaths(library).pipe( this.libraryService.scanLibraryPaths(library).pipe(
switchMap(count => { switchMap(count => {
if (count < 500) { if (count >= 500) {
return this.libraryService.createLibrary(library).pipe(
map(createdLibrary => ({ createdLibrary, count }))
);
} else {
console.warn(`Library has ${count} processable files (>500). Will use buffered loading.`); console.warn(`Library has ${count} processable files (>500). Will use buffered loading.`);
this.libraryService.setLargeLibraryLoading(true, count); this.libraryService.setLargeLibraryLoading(true, count);
return this.libraryService.createLibrary(library).pipe(
map(createdLibrary => ({ createdLibrary, count }))
);
} }
return this.libraryService.createLibrary(library).pipe(
map(createdLibrary => ({ createdLibrary, count }))
);
}) })
).subscribe({ ).subscribe({
next: ({ createdLibrary, count }) => { next: ({ createdLibrary, count }) => {
@@ -297,22 +317,26 @@ export class LibraryCreatorComponent implements OnInit {
severity: 'success', severity: 'success',
summary: this.t.translate('libraryCreator.creator.toast.createdSummary'), summary: this.t.translate('libraryCreator.creator.toast.createdSummary'),
detail: count >= 500 detail: count >= 500
? this.t.translate('libraryCreator.creator.toast.createdLargeDetail', {count}) ? this.t.translate('libraryCreator.creator.toast.createdLargeDetail', { count })
: this.t.translate('libraryCreator.creator.toast.createdDetail') : this.t.translate('libraryCreator.creator.toast.createdDetail'),
}); });
this.dynamicDialogRef.close(); this.dynamicDialogRef.close();
} }
}, },
error: (e) => { error: (e: Error) => {
this.libraryService.setLargeLibraryLoading(false, 0); this.libraryService.setLargeLibraryLoading(false, 0);
this.messageService.add({severity: 'error', summary: this.t.translate('libraryCreator.creator.toast.createFailedSummary'), detail: this.t.translate('libraryCreator.creator.toast.createFailedDetail')}); this.messageService.add({ severity: 'error', summary: this.t.translate('libraryCreator.creator.toast.createFailedSummary'), detail: this.t.translate('libraryCreator.creator.toast.createFailedDetail') });
console.error(e); console.error(e);
} }
}); });
} }
} }
onFormatPriorityDrop(event: CdkDragDrop<{type: BookType, label: string}[]>): void { onFormatPriorityDrop(event: CdkDragDrop<FormatEntry[]>): void {
moveItemInArray(this.formatPriority, event.previousIndex, event.currentIndex); this.formatPriority.update(current => {
const next = [...current];
moveItemInArray(next, event.previousIndex, event.currentIndex);
return next;
});
} }
} }