diff --git a/frontend/src/app/features/library-creator/library-creator.component.html b/frontend/src/app/features/library-creator/library-creator.component.html index 496f39a86..a39af1f93 100644 --- a/frontend/src/app/features/library-creator/library-creator.component.html +++ b/frontend/src/app/features/library-creator/library-creator.component.html @@ -6,7 +6,7 @@
-

{{ mode === 'edit' ? t('titleEdit') : t('titleNew') }}

+

{{ mode() === 'edit' ? t('titleEdit') : t('titleNew') }}

{{ t('subtitle') }}

@@ -35,11 +35,12 @@ - @if (chosenLibraryName.trim()) { + @if (chosenLibraryName().trim()) { } @@ -49,7 +50,7 @@ {{ t('iconLabel') }} - @if (!selectedIcon) { + @if (!selectedIcon()) { - @if (folders.length > 0) { + @if (folders().length > 0) {
- @for (folder of folders; track folder; let i = $index) { + @for (folder of folders(); track folder; let i = $index) {
@@ -129,7 +130,10 @@ tooltipPosition="top" >
- +
@@ -142,8 +146,9 @@ >
{{ t('organizationMode') }}
@@ -187,10 +193,10 @@ class="format-chips" cdkDropList cdkDropListOrientation="mixed" - [cdkDropListData]="formatPriority" + [cdkDropListData]="formatPriority()" (cdkDropListDropped)="onFormatPriorityDrop($event)" > - @for (format of formatPriority; track format.type; let i = $index) { + @for (format of formatPriority(); track format.type; let i = $index) {
{{ i + 1 }} {{ format.type }} @@ -211,16 +217,16 @@
- @if (!allowAllFormats) { + @if (!allowAllFormats()) {
@for (format of allBookFormats; track format.type) {
@@ -260,9 +266,9 @@
- @if (!chosenLibraryName.trim()) { + @if (!chosenLibraryName().trim()) { {{ t('validation.enterName') }} - } @else if (!selectedIcon) { + } @else if (!selectedIcon()) { {{ t('validation.selectIcon') }} } @else { {{ t('validation.addFolder') }} @@ -272,7 +278,7 @@ } @else {
- {{ mode === 'edit' ? t('validation.readyUpdate') : t('validation.readyCreate') }} + {{ mode() === 'edit' ? t('validation.readyUpdate') : t('validation.readyCreate') }}
}
@@ -284,8 +290,8 @@ (onClick)="closeDialog()" /> { +describe('LibraryCreatorComponent', () => { 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 // once the component state can be supplied without mocking the full runtime graph. diff --git a/frontend/src/app/features/library-creator/library-creator.component.ts b/frontend/src/app/features/library-creator/library-creator.component.ts index 8722563cc..34a835e20 100644 --- a/frontend/src/app/features/library-creator/library-creator.component.ts +++ b/frontend/src/app/features/library-creator/library-creator.component.ts @@ -1,240 +1,257 @@ -import {Component, inject, OnInit} from '@angular/core'; -import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; -import {MessageService} from 'primeng/api'; -import {Router} from '@angular/router'; -import {LibraryService} from '../book/service/library.service'; -import {FormsModule} from '@angular/forms'; -import {InputText} from 'primeng/inputtext'; -import {Library, MetadataSource, OrganizationMode} from '../book/model/library.model'; -import {BookType} from '../book/model/book.model'; -import {ToggleSwitch} from 'primeng/toggleswitch'; -import {Tooltip} from 'primeng/tooltip'; -import {IconPickerService, IconSelection} from '../../shared/service/icon-picker.service'; -import {Button} from 'primeng/button'; -import {IconDisplayComponent} from '../../shared/components/icon-display/icon-display.component'; -import {DialogLauncherService} from '../../shared/services/dialog-launcher.service'; -import {switchMap} from 'rxjs/operators'; -import {map} from 'rxjs'; -import {CdkDragDrop, DragDropModule, moveItemInArray} from '@angular/cdk/drag-drop'; -import {Checkbox} from 'primeng/checkbox'; -import {Select} from 'primeng/select'; -import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco'; +import { ChangeDetectionStrategy, Component, computed, effect, inject, signal, untracked } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog'; +import { MessageService } from 'primeng/api'; +import { Router } from '@angular/router'; +import { LibraryService } from '../book/service/library.service'; +import { FormsModule } from '@angular/forms'; +import { InputText } from 'primeng/inputtext'; +import { Library, MetadataSource, OrganizationMode } from '../book/model/library.model'; +import { BookType } from '../book/model/book.model'; +import { ToggleSwitch } from 'primeng/toggleswitch'; +import { Tooltip } from 'primeng/tooltip'; +import { IconPickerService, IconSelection } from '../../shared/service/icon-picker.service'; +import { Button } from 'primeng/button'; +import { IconDisplayComponent } from '../../shared/components/icon-display/icon-display.component'; +import { DialogLauncherService } from '../../shared/services/dialog-launcher.service'; +import { switchMap, map } from 'rxjs'; +import { CdkDragDrop, DragDropModule, moveItemInArray } from '@angular/cdk/drag-drop'; +import { Checkbox } from 'primeng/checkbox'; +import { Select } from 'primeng/select'; +import { TranslocoDirective, TranslocoPipe, TranslocoService } from '@jsverse/transloco'; + +interface FormatEntry { type: BookType; label: string } + +interface LibraryCreatorDialogData { + mode: 'create' | 'edit'; + libraryId?: number; +} @Component({ selector: 'app-library-creator', standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './library-creator.component.html', imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule, Checkbox, Select, TranslocoDirective, TranslocoPipe], styleUrl: './library-creator.component.scss' }) -export class LibraryCreatorComponent implements OnInit { - chosenLibraryName: string = ''; - folders: string[] = []; - selectedIcon: IconSelection | null = null; +export class LibraryCreatorComponent { - mode!: string; - library!: Library | undefined; - editModeLibraryName: string = ''; - watch: boolean = false; - formatPriority: {type: BookType, label: string}[] = []; - allowAllFormats: boolean = true; - selectedAllowedFormats = new Set(); - formatCounts: Record = {}; - 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 dialogLauncherService = inject(DialogLauncherService); + private readonly dynamicDialogRef = inject(DynamicDialogRef); + private readonly dynamicDialogConfig = inject(DynamicDialogConfig); + private readonly libraryService = inject(LibraryService); + private readonly messageService = inject(MessageService); + private readonly router = inject(Router); + private readonly iconPicker = inject(IconPickerService); private readonly t = inject(TranslocoService); - ngOnInit(): void { - this.metadataSourceOptions = [ - {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'} + private readonly activeLang = toSignal(this.t.langChanges$, { + initialValue: this.t.getActiveLang(), + }); + + readonly allBookFormats: FormatEntry[] = [ + { 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' }, + ]; + + readonly chosenLibraryName = signal(''); + readonly folders = signal([]); + readonly selectedIcon = signal(null); + readonly mode = signal(''); + readonly editModeLibraryName = signal(''); + readonly watch = signal(false); + readonly formatPriority = signal([...this.allBookFormats]); + readonly allowAllFormats = signal(true); + readonly selectedAllowedFormats = signal>(new Set(this.allBookFormats.map(f => f.type))); + readonly formatCounts = signal>({}); + readonly metadataSource = signal('EMBEDDED'); + readonly organizationMode = signal('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; - if (data?.mode === 'edit') { - this.mode = data.mode; - this.library = this.libraryService.findLibraryById(data.libraryId); - if (this.library) { - const {name, icon, iconType, paths, watch, formatPriority, allowedFormats} = this.library; - this.chosenLibraryName = name; - this.editModeLibraryName = name; + readonly organizationModeOptions = computed(() => { + this.activeLang(); + const base = [ + { label: this.t.translate('libraryCreator.creator.organizationModeBookPerFile'), value: 'BOOK_PER_FILE' }, + { label: this.t.translate('libraryCreator.creator.organizationModeBookPerFolder'), value: 'BOOK_PER_FOLDER' }, + ]; + if (this.organizationMode() === 'AUTO_DETECT') { + base.push({ label: this.t.translate('libraryCreator.creator.organizationModeAutoDetect'), value: 'AUTO_DETECT' }); + } + return base; + }); - if (icon != null && iconType) { - if (iconType === 'CUSTOM_SVG') { - 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}; - } - } + readonly isLibraryDetailsValid = computed(() => !!this.chosenLibraryName().trim()); + readonly isDirectorySelectionValid = computed(() => this.folders().length > 0); - this.watch = watch; - if (formatPriority && formatPriority.length > 0) { - this.formatPriority = formatPriority.map(type => - this.allBookFormats.find(f => f.type === type)! - ).filter(f => f !== undefined); - const existingTypes = new Set(formatPriority); - this.allBookFormats.forEach(f => { - if (!existingTypes.has(f.type)) { - this.formatPriority.push(f); - } - }); - } + constructor() { + /** + * Runs once after construction. `untracked` prevents the body from being + * treated as a reactive dependency (we only want it to run once on init). + */ + effect(() => { + untracked(() => this.initFromDialogData()); + }); + } - if (allowedFormats && allowedFormats.length > 0) { - this.allowAllFormats = false; - this.selectedAllowedFormats = new Set(allowedFormats); - } else { - this.allowAllFormats = true; - this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); - } + private initFromDialogData(): void { + const data = this.dynamicDialogConfig?.data as LibraryCreatorDialogData; + if (data?.mode !== 'edit') { + this.mode.set('create'); + return; + } - if (this.library.metadataSource) { - this.metadataSource = this.library.metadataSource; - } + this.mode.set('edit'); - if (this.library.organizationMode) { - this.organizationMode = this.library.organizationMode; - if (this.library.organizationMode === 'AUTO_DETECT') { - this.organizationModeOptions.push({ - label: this.t.translate('libraryCreator.creator.organizationModeAutoDetect'), - value: 'AUTO_DETECT' - }); - } - } + const library = this.libraryService.findLibraryById(data.libraryId!); + if (!library) { + this.messageService.add({ + severity: 'error', + summary: this.t.translate('libraryCreator.creator.toast.updateFailedSummary'), + detail: this.t.translate('libraryCreator.creator.toast.updateFailedDetail'), + }); + this.dynamicDialogRef.close(); + return; + } - this.libraryService.getBookCountsByFormat(this.library.id!).subscribe(counts => { - this.formatCounts = counts; - }); + const { name, icon, iconType, paths, watch, formatPriority, allowedFormats } = library; - 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 { - this.formatPriority = [...this.allBookFormats]; - } + if (formatPriority && formatPriority.length > 0) { + 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 { - this.organizationModeOptions = [ - {label: this.t.translate('libraryCreator.creator.organizationModeBookPerFile'), value: 'BOOK_PER_FILE'}, - {label: this.t.translate('libraryCreator.creator.organizationModeBookPerFolder'), value: 'BOOK_PER_FOLDER'} - ]; - } + if (allowedFormats && allowedFormats.length > 0) { + this.allowAllFormats.set(false); + this.selectedAllowedFormats.set(new Set(allowedFormats)); + } else { + this.allowAllFormats.set(true); + this.selectedAllowedFormats.set(new Set(this.allBookFormats.map(f => f.type))); + } - private initializeAllowedFormats(): void { - this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); + if (library.metadataSource) { + 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 { - if (this.allowAllFormats) { - this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); + if (this.allowAllFormats()) { + this.selectedAllowedFormats.set(new Set(this.allBookFormats.map(f => f.type))); } } onFormatCheckboxChange(formatType: BookType, checked: boolean): void { + const next = new Set(this.selectedAllowedFormats()); if (checked) { - this.selectedAllowedFormats.add(formatType); + next.add(formatType); } 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 { - return this.selectedAllowedFormats.has(formatType); + return this.selectedAllowedFormats().has(formatType); } getFormatWarning(formatType: BookType): string | null { - if (this.mode !== 'edit') return null; - const count = this.formatCounts[formatType]; - if (count && count > 0 && !this.selectedAllowedFormats.has(formatType)) { - return this.t.translate('libraryCreator.creator.formatWarning', {count}); + if (this.mode() !== 'edit') return null; + const count = this.formatCounts()[formatType]; + if (count && count > 0 && !this.selectedAllowedFormats().has(formatType)) { + return this.t.translate('libraryCreator.creator.formatWarning', { count }); } return null; } hasAnyFormatWarning(): boolean { - if (this.mode !== 'edit') return false; + if (this.mode() !== 'edit') return false; return this.allBookFormats.some(f => this.getFormatWarning(f.type) !== null); } - closeDialog(): void { - this.dynamicDialogRef.close(); - } - openDirectoryPicker(): void { const ref = this.dialogLauncherService.openDirectoryPickerDialog(); ref?.onClose.subscribe((selectedFolders: string[] | null) => { if (selectedFolders && selectedFolders.length > 0) { - selectedFolders.forEach(folder => { - if (!this.folders.includes(folder)) { - this.addFolder(folder); - } + this.folders.update(current => { + const incoming = selectedFolders.filter(f => !current.includes(f)); + return incoming.length > 0 ? [...current, ...incoming] : current; }); } }); } - openIconPicker(): void { - this.iconPicker.open().subscribe(icon => { - if (icon) { - this.selectedIcon = icon; - } - }); - } - addFolder(folder: string): void { - this.folders.push(folder); + this.folders.update(current => [...current, folder]); } 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 { - this.selectedIcon = null; + this.selectedIcon.set(null); } - isLibraryDetailsValid(): boolean { - return !!this.chosenLibraryName.trim(); - } - - isDirectorySelectionValid(): boolean { - return this.folders.length > 0; + closeDialog(): void { + this.dynamicDialogRef.close(); } createOrUpdateLibrary(): void { - const trimmedLibraryName = this.chosenLibraryName.trim(); - if (trimmedLibraryName && trimmedLibraryName !== this.editModeLibraryName) { + const trimmedLibraryName = this.chosenLibraryName().trim(); + if (trimmedLibraryName && trimmedLibraryName !== this.editModeLibraryName()) { const exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName); if (exists) { 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 = { - name: this.chosenLibraryName, - icon: iconValue, - iconType: iconType, - paths: this.folders.map(folder => ({path: folder})), - watch: this.watch, - formatPriority: this.formatPriority.map(f => f.type), - allowedFormats: this.allowAllFormats ? [] : Array.from(this.selectedAllowedFormats), - metadataSource: this.metadataSource, - organizationMode: this.organizationMode + name: trimmedLibraryName, + icon: this.selectedIcon()?.value ?? null, + iconType: this.selectedIcon()?.type ?? null, + paths: this.folders().map(folder => ({ path: folder })), + watch: this.watch(), + formatPriority: this.formatPriority().map(f => f.type), + allowedFormats: this.allowAllFormats() ? [] : Array.from(this.selectedAllowedFormats()), + metadataSource: this.metadataSource(), + organizationMode: this.organizationMode(), }; - if (this.mode === 'edit') { - this.libraryService.updateLibrary(library, this.library?.id).pipe( - switchMap(() => this.libraryService.refreshLibrary(this.library!.id!)) + if (this.mode() === 'edit') { + const libraryId = (this.dynamicDialogConfig.data as LibraryCreatorDialogData)?.libraryId; + 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({ 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(); }, - error: (e) => { - this.messageService.add({severity: 'error', summary: this.t.translate('libraryCreator.creator.toast.updateFailedSummary'), detail: this.t.translate('libraryCreator.creator.toast.updateFailedDetail')}); + error: (e: Error) => { + this.messageService.add({ severity: 'error', summary: this.t.translate('libraryCreator.creator.toast.updateFailedSummary'), detail: this.t.translate('libraryCreator.creator.toast.updateFailedDetail') }); console.error(e); } }); } else { this.libraryService.scanLibraryPaths(library).pipe( switchMap(count => { - if (count < 500) { - return this.libraryService.createLibrary(library).pipe( - map(createdLibrary => ({ createdLibrary, count })) - ); - } else { + if (count >= 500) { console.warn(`Library has ${count} processable files (>500). Will use buffered loading.`); 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({ next: ({ createdLibrary, count }) => { @@ -297,22 +317,26 @@ export class LibraryCreatorComponent implements OnInit { severity: 'success', summary: this.t.translate('libraryCreator.creator.toast.createdSummary'), detail: count >= 500 - ? this.t.translate('libraryCreator.creator.toast.createdLargeDetail', {count}) - : this.t.translate('libraryCreator.creator.toast.createdDetail') + ? this.t.translate('libraryCreator.creator.toast.createdLargeDetail', { count }) + : this.t.translate('libraryCreator.creator.toast.createdDetail'), }); this.dynamicDialogRef.close(); } }, - error: (e) => { + error: (e: Error) => { 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); } }); } } - onFormatPriorityDrop(event: CdkDragDrop<{type: BookType, label: string}[]>): void { - moveItemInArray(this.formatPriority, event.previousIndex, event.currentIndex); + onFormatPriorityDrop(event: CdkDragDrop): void { + this.formatPriority.update(current => { + const next = [...current]; + moveItemInArray(next, event.previousIndex, event.currentIndex); + return next; + }); } }