refactor(frontend): rename booklore-ui to frontend

- Frontend path:
  - rename the tracked Angular app tree from `booklore-ui/` to `frontend/`
  - preserve file contents during the move so this commit stays focused on the path change itself
- Frontend docs:
  - update the moved frontend README and contribution guide where they refer to the renamed folder
  - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
James Cox
2026-04-22 17:26:39 -04:00
committed by Zach Yale
parent c99aa87877
commit 874b013f75
1493 changed files with 3 additions and 3 deletions
@@ -0,0 +1,236 @@
@if (libraries(); as libraries) {
<ng-container *transloco="let t; prefix: 'shared.bookUploader'">
<div class="book-uploader">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-cloud-upload header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">{{ t('title') }}</h2>
<p class="panel-description">
{{ t('description') }}
</p>
</div>
<p-button
icon="pi pi-times"
(click)="closeDialog()"
severity="secondary"
[text]="true"
[rounded]="true"
class="close-button"/>
</div>
<div class="upload-container">
<div class="destination-section">
<div class="section-header">
<span class="section-title">
<i class="pi pi-map-marker"></i>
{{ t('uploadDestination') }}
</span>
</div>
<div class="destination-selector">
<p-selectbutton
[options]="stateOptions"
[(ngModel)]="value"
[allowEmpty]="false"
optionLabel="label"
optionValue="value">
</p-selectbutton>
</div>
</div>
@if (value === 'library') {
<div class="gradient-divider"></div>
<div class="library-selection">
<div class="section-header">
<span class="section-title">
<i class="pi pi-building"></i>
{{ t('librarySelection') }}
</span>
</div>
<div class="selection-fields">
<div class="field-group">
<label for="library-select" class="field-label">{{ t('libraryLabel') }}</label>
<p-select
inputId="library-select"
[options]="libraries"
optionLabel="name"
[placeholder]="t('selectLibrary')"
[(ngModel)]="selectedLibrary"
class="full-width">
</p-select>
</div>
<div class="field-group">
<label for="subpath-select" class="field-label">{{ t('subpathLabel') }}</label>
<p-select
inputId="subpath-select"
[options]="selectedLibrary?.paths"
optionLabel="path"
[placeholder]="t('selectSubpath')"
[(ngModel)]="selectedPath"
[disabled]="!selectedLibrary"
class="full-width">
</p-select>
</div>
</div>
</div>
}
<div class="gradient-divider"></div>
<div class="file-upload-section">
<div class="section-header">
<span class="section-title">
<i class="pi pi-file"></i>
{{ t('selectFiles') }}
</span>
</div>
<p-fileupload
name="file"
[customUpload]="true"
[multiple]="true"
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3,.m4b,.m4a,.mp3,.opus"
(onSelect)="onFilesSelect($event)"
(uploadHandler)="uploadFiles($event)">
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
<div class="upload-actions">
<div class="action-buttons">
<p-button
severity="info"
(onClick)="choose($event, chooseCallback)"
icon="pi pi-images"
[label]="t('chooseBtn')"
[outlined]="true"
[disabled]="isChooseDisabled()"
[pTooltip]="t('chooseTooltip')"
tooltipPosition="top"/>
<p-button
(onClick)="uploadEvent(uploadCallback)"
icon="pi pi-cloud-upload"
[label]="t('uploadBtn')"
severity="success"
[disabled]="isUploadDisabled()"
[pTooltip]="t('uploadTooltip')"
tooltipPosition="top"/>
<p-button
(onClick)="onClear(clearCallback)"
icon="pi pi-times"
[label]="t('clearBtn')"
severity="danger"
[outlined]="true"
[disabled]="!filesPresent() || isUploading"
[pTooltip]="t('clearTooltip')"
tooltipPosition="top"/>
</div>
<small class="upload-hint">{{ t('uploadHint') }}</small>
</div>
</ng-template>
<ng-template #content let-files let-removeFileCallback="removeFileCallback">
@if (files?.length > 0) {
@if (isUploading || uploadCompleted) {
<div class="upload-progress-summary">
<div class="progress-row">
<span class="progress-status">
@if (isUploading) {
<i class="pi pi-spin pi-spinner"></i>
{{ t('uploading') }}
} @else {
<i class="pi pi-check-circle"></i>
{{ t('complete') }}
}
</span>
<span class="progress-files">
{{ t('filesCount', { uploaded: getUploadedCount(), total: this.files.length }) }}
@if (getFailedCount() > 0) {
<span class="failed-count">{{ t('failedCount', { count: getFailedCount() }) }}</span>
}
</span>
<span class="progress-bytes">{{ formatSize(getUploadedBytes()) }} / {{ formatSize(getTotalBytes()) }}</span>
<span class="progress-percent">{{ getOverallProgress() }}%</span>
</div>
<p-progressbar
[value]="getOverallProgress()"
[showValue]="false"
class="overall-progress-bar"/>
</div>
}
<div class="files-list">
@for (uploadFile of this.files; track uploadFile; let i = $index) {
<div class="file-item">
<div class="file-info">
<p-badge
[value]="getFileStatusLabel(uploadFile)"
[severity]="getBadgeSeverity(uploadFile.status)"/>
<span class="file-name" [pTooltip]="uploadFile.file.name" tooltipPosition="top">{{ uploadFile.file.name }}</span>
<span class="file-size">{{ formatSize(uploadFile.file.size) }}</span>
@if (uploadFile.status === 'Uploading') {
<span class="file-progress-text">{{ uploadFile.progress }}%</span>
}
</div>
<div class="file-actions">
@switch (uploadFile.status) {
@case ('Pending') {
<p-button
icon="pi pi-times"
(click)="onRemoveTemplatingFile($event, uploadFile.file, removeFileCallback, i)"
severity="danger"
[text]="true"
[rounded]="true"/>
}
@case ('Uploading') {
<i class="pi pi-spin pi-spinner status-icon uploading"></i>
}
@case ('Uploaded') {
<i class="pi pi-check status-icon success"></i>
}
@case ('Failed') {
@if (uploadFile.errorMessage?.includes('exceeds maximum size')) {
@if (hasUploadCompleted()) {
<i
class="pi pi-exclamation-triangle status-icon warning"
[pTooltip]="uploadFile.errorMessage || t('fileTooLargeTooltip')"
tooltipPosition="top">
</i>
} @else {
<p-button
icon="pi pi-times"
(click)="onRemoveTemplatingFile($event, uploadFile.file, removeFileCallback, i)"
severity="danger"
[text]="true"
[rounded]="true"/>
}
} @else {
<i
class="pi pi-exclamation-triangle status-icon error"
[pTooltip]="uploadFile.errorMessage || t('uploadFailedTooltip')"
tooltipPosition="top">
</i>
}
}
}
</div>
</div>
}
</div>
}
</ng-template>
<ng-template #file></ng-template>
<ng-template #empty>
<div class="empty-state">
<div class="empty-icon-wrapper">
<i class="pi pi-cloud-upload empty-icon" [class.active]="isUploadZoneActive()"></i>
</div>
<h3 class="empty-title">{{ t('dragDropTitle') }}</h3>
<p class="empty-description">
<span [innerHTML]="t('supportedFormats')"></span>
<br/>
{{ t('maxFileSize', { size: maxFileSizeDisplay }) }}
</p>
</div>
</ng-template>
</p-fileupload>
</div>
</div>
</div>
</ng-container>
}
@@ -0,0 +1,472 @@
@use '../../styles/panel-shared' as panel;
.book-uploader {
width: 700px;
max-width: 700px;
display: flex;
flex-direction: column;
@media (max-width: 768px) {
width: 100%;
max-width: 100%;
}
}
.panel-header {
@include panel.panel-header;
border-bottom: none;
}
.upload-container {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1.75rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 0 0 10px 10px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
@media (max-width: 480px) {
padding: 1rem;
gap: 1rem;
}
}
.destination-section,
.library-selection,
.file-upload-section {
display: flex;
flex-direction: column;
.section-header {
display: flex;
align-items: center;
justify-content: center;
padding: 0.625rem 0.875rem;
background: var(--overlay-background);
border-radius: 6px;
.section-title {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.9rem;
font-weight: 600;
color: var(--text-color);
i {
color: var(--primary-color);
font-size: 1rem;
}
}
@media (max-width: 480px) {
padding: 0.5rem 0.625rem;
.section-title {
font-size: 0.85rem;
}
}
}
}
.destination-selector {
display: flex;
justify-content: center;
}
.selection-fields {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 0 0.75rem 1rem 0.75rem;
.field-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
.field-label {
font-size: 0.875rem;
font-weight: 600;
color: var(--text-color);
padding-left: 0.25rem;
}
}
}
.file-upload-section {
::ng-deep .p-fileupload {
border: 2px dashed var(--border-color);
border-radius: 8px;
background: var(--ground-background);
transition: border-color 0.3s ease, background-color 0.3s ease;
.p-fileupload-buttonbar {
display: flex;
justify-content: center;
align-items: center;
padding: 0;
background: transparent;
border: none;
}
.p-fileupload-content {
padding: 1rem;
background: transparent;
border: none;
transition: background-color 0.3s ease;
&.p-fileupload-highlight {
background: color-mix(in srgb, var(--primary-color) 5%, transparent);
.empty-icon-wrapper {
border-color: var(--primary-color);
.empty-icon {
color: var(--primary-color);
opacity: 1;
transform: scale(1.1);
}
}
}
}
&:has(.p-fileupload-highlight) {
border-color: var(--primary-color);
}
}
.upload-actions {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
padding: 1rem;
width: 100%;
.action-buttons {
display: flex;
gap: 0.75rem;
flex-wrap: wrap;
justify-content: center;
}
.upload-hint {
color: var(--text-secondary-color);
font-size: 0.875rem;
text-align: center;
}
@media (max-width: 480px) {
padding: 0.75rem;
gap: 0.5rem;
.action-buttons {
width: 100%;
flex-direction: column;
::ng-deep .p-button {
width: 100%;
}
}
.upload-hint {
font-size: 0.8rem;
}
}
}
.upload-progress-summary {
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 0.625rem 0.875rem;
margin-bottom: 0.5rem;
.progress-row {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 0.5rem;
font-size: 0.85rem;
.progress-status {
display: flex;
align-items: center;
gap: 0.375rem;
font-weight: 600;
color: var(--text-color);
i {
font-size: 0.9rem;
color: var(--primary-color);
}
.pi-check-circle {
color: #22c55e;
}
}
.progress-files {
color: var(--text-secondary-color);
.failed-count {
color: #ef4444;
font-weight: 500;
}
}
.progress-bytes {
color: var(--text-secondary-color);
margin-left: auto;
}
.progress-percent {
font-weight: 700;
color: var(--primary-color);
min-width: 42px;
text-align: right;
}
}
::ng-deep .overall-progress-bar {
height: 6px;
border-radius: 3px;
background: var(--overlay-background);
.p-progressbar-value {
border-radius: 3px;
transition: width 0.3s ease;
}
}
@media (max-width: 480px) {
padding: 0.5rem 0.75rem;
.progress-row {
flex-wrap: wrap;
gap: 0.5rem;
font-size: 0.8rem;
.progress-bytes {
margin-left: 0;
}
}
}
}
.files-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
max-height: 400px;
overflow-y: auto;
padding-right: 0.25rem;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: var(--overlay-background);
border-radius: 3px;
}
&::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
transition: background 0.2s ease;
&:hover {
background: var(--primary-color);
}
}
scrollbar-width: thin;
scrollbar-color: var(--border-color) var(--overlay-background);
.file-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.25rem 0.75rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 8px;
transition: all 0.2s ease;
&:hover {
border-color: var(--primary-color);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}
.file-info {
display: flex;
align-items: center;
gap: 0.75rem;
flex: 1;
min-width: 0;
.file-name {
flex: 1;
font-weight: 500;
color: var(--text-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 0.9rem;
}
.file-size {
color: var(--text-secondary-color);
font-size: 0.875rem;
flex-shrink: 0;
}
.file-progress-text {
font-size: 0.85rem;
font-weight: 600;
color: var(--primary-color);
min-width: 40px;
text-align: right;
flex-shrink: 0;
}
}
.file-actions {
display: flex;
align-items: center;
flex-shrink: 0;
.status-icon {
font-size: 1.25rem;
padding: 0.5rem;
&.uploading {
color: var(--primary-color);
}
&.success {
color: #22c55e;
}
&.warning,
&.error {
color: #f97316;
}
}
}
@media (max-width: 480px) {
padding: 0.625rem;
gap: 0.5rem;
.file-info {
gap: 0.5rem;
.file-name {
font-size: 0.85rem;
}
.file-size {
font-size: 0.8rem;
}
}
.file-actions {
.status-icon {
font-size: 1rem;
padding: 0.375rem;
}
}
}
}
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 1.5rem 1rem;
.empty-icon-wrapper {
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
background: var(--overlay-background);
border-radius: 50%;
margin-bottom: 1rem;
border: 3px dashed var(--border-color);
transition: border-color 0.3s ease;
.empty-icon {
font-size: 2.5rem;
color: var(--text-secondary-color);
opacity: 0.6;
transition: color 0.3s ease, opacity 0.3s ease, transform 0.3s ease;
&.active {
color: #22c55e;
}
}
}
.empty-title {
margin: 0 0 1.5rem 0;
font-size: 1.125rem;
font-weight: 600;
color: var(--text-color);
}
.empty-description {
margin: 0;
font-size: 0.875rem;
color: var(--text-secondary-color);
max-width: 450px;
line-height: 1.5;
strong {
color: var(--text-color);
}
}
@media (max-width: 480px) {
padding: 1.5rem 0.75rem;
min-height: 180px;
.empty-icon-wrapper {
width: 70px;
height: 70px;
margin-bottom: 0.75rem;
.empty-icon {
font-size: 2rem;
}
}
.empty-title {
font-size: 1rem;
}
.empty-description {
font-size: 0.8rem;
max-width: 100%;
}
}
}
}
::host ::ng-deep .p-fileupload-content p-progressbar {
display: none !important;
}
.full-width {
width: 100%;
}
@@ -0,0 +1,356 @@
import {Component, inject, OnInit, ViewChild, effect} from '@angular/core';
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
import {Button} from 'primeng/button';
import {FormsModule} from '@angular/forms';
import {MessageService} from 'primeng/api';
import {Select} from 'primeng/select';
import {Badge} from 'primeng/badge';
import {LibraryService} from '../../../features/book/service/library.service';
import {Library, LibraryPath} from '../../../features/book/model/library.model';
import {API_CONFIG} from '../../../core/config/api-config';
import {HttpClient, HttpEventType, HttpRequest} from '@angular/common/http';
import {Tooltip} from 'primeng/tooltip';
import {AppSettingsService} from '../../service/app-settings.service';
import {SelectButton} from 'primeng/selectbutton';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {ProgressBar} from 'primeng/progressbar';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
interface UploadingFile {
file: File;
status: 'Pending' | 'Uploading' | 'Uploaded' | 'Failed';
progress: number;
errorMessage?: string;
}
type FileChooserCallback = () => void;
type FileRemoveCallback = (event: Event, index: number) => void;
@Component({
selector: 'app-book-uploader',
standalone: true,
imports: [
FileUpload,
Button,
FormsModule,
Select,
Badge,
Tooltip,
SelectButton,
ProgressBar,
TranslocoDirective
],
templateUrl: './book-uploader.component.html',
styleUrl: './book-uploader.component.scss'
})
export class BookUploaderComponent implements OnInit {
@ViewChild(FileUpload) fileUpload!: FileUpload;
files: UploadingFile[] = [];
isUploading: boolean = false;
uploadCompleted: boolean = false;
_selectedLibrary: Library | null = null;
selectedPath: LibraryPath | null = null;
private readonly libraryService = inject(LibraryService);
private readonly messageService = inject(MessageService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly http = inject(HttpClient);
private readonly ref = inject(DynamicDialogRef);
private readonly t = inject(TranslocoService);
readonly libraries = this.libraryService.libraries;
maxFileSizeBytes?: number;
maxFileSizeDisplay: string = '100 MB';
stateOptions = [
{label: this.t.translate('shared.bookUploader.destinationLibrary'), value: 'library'},
{label: this.t.translate('shared.bookUploader.destinationBookdrop'), value: 'bookdrop'}
];
value = 'library';
private readonly selectSingleLibraryEffect = effect(() => {
const libraries = this.libraries();
if (libraries.length !== 1 || this.selectedLibrary) {
return;
}
this.selectedLibrary = libraries[0];
});
private readonly loadSettingsEffect = effect(() => {
const settings = this.appSettingsService.appSettings();
if (!settings) return;
const maxSizeMb = settings.maxFileUploadSizeInMb ?? 100;
this.maxFileSizeBytes = maxSizeMb * 1024 * 1024;
this.maxFileSizeDisplay = `${maxSizeMb} MB`;
});
ngOnInit(): void {
}
get selectedLibrary(): Library | null {
return this._selectedLibrary;
}
set selectedLibrary(library: Library | null) {
this._selectedLibrary = library;
if (library?.paths?.length === 1) {
this.selectedPath = library.paths[0];
}
}
hasPendingFiles(): boolean {
return this.files.some(f => f.status === 'Pending');
}
filesPresent(): boolean {
return this.files.length > 0;
}
choose(_event: Event, chooseCallback: FileChooserCallback): void {
chooseCallback();
}
onClear(clearCallback: () => void): void {
clearCallback();
this.files = [];
}
onFilesSelect(event: FileSelectEvent): void {
if (this.value === 'library' && (!this.selectedLibrary || !this.selectedPath)) {
this.messageService.add({
severity: 'error',
summary: this.t.translate('shared.bookUploader.toast.noDestinationSummary'),
detail: this.t.translate('shared.bookUploader.toast.noDestinationDetail'),
life: 5000
});
// We need to clear the files input explicitely, otherwise the files remain selected in the file upload component
this.fileUpload.clear();
return;
}
const newFiles = event.currentFiles;
for (const file of newFiles) {
const exists = this.files.some(f => f.file.name === file.name && f.file.size === file.size);
if (exists) {
continue;
}
if (this.maxFileSizeBytes && file.size > this.maxFileSizeBytes) {
const errorMsg = `File exceeds maximum size of ${this.formatSize(this.maxFileSizeBytes)}`;
this.files.unshift({
file,
status: 'Failed',
progress: 0,
errorMessage: errorMsg
});
this.messageService.add({
severity: 'error',
summary: this.t.translate('shared.bookUploader.toast.fileTooLargeSummary'),
detail: this.t.translate('shared.bookUploader.toast.fileTooLargeDetail', {fileName: file.name, maxSize: this.formatSize(this.maxFileSizeBytes)}),
life: 5000
});
} else {
this.files.unshift({file, status: 'Pending', progress: 0});
}
}
}
onRemoveTemplatingFile(event: Event, file: File, removeFileCallback: FileRemoveCallback, _index?: number): void {
// Remove from our tracking array
this.files = this.files.filter(f => f.file !== file);
// Find and remove from p-fileupload's internal array (index may differ from ours)
const fileUploadIndex = this.fileUpload.files?.findIndex(f => f.name === file.name && f.size === file.size) ?? -1;
if (fileUploadIndex >= 0) {
removeFileCallback(event, fileUploadIndex);
}
}
uploadEvent(uploadCallback: () => void): void {
uploadCallback();
}
uploadFiles(_event: FileUploadHandlerEvent): void {
if (this.value === 'library' && (!this.selectedLibrary || !this.selectedPath)) {
this.messageService.add({
severity: 'warn',
summary: this.t.translate('shared.bookUploader.toast.missingDataSummary'),
detail: this.t.translate('shared.bookUploader.toast.missingDataDetail'),
life: 4000
});
return;
}
const filesToUpload = this.files.filter(f => f.status === 'Pending');
if (filesToUpload.length === 0) return;
this.isUploading = true;
this.uploadCompleted = false;
const destination = this.value;
const libraryId = this.selectedLibrary?.id?.toString();
const pathId = this.selectedPath?.id?.toString();
this.uploadBatch(filesToUpload, 0, 1, destination, libraryId, pathId);
}
private uploadBatch(files: UploadingFile[], startIndex: number, batchSize: number, destination: string, libraryId?: string, pathId?: string): void {
const batch = files.slice(startIndex, startIndex + batchSize);
if (batch.length === 0) {
this.isUploading = false;
this.uploadCompleted = true;
if (destination === 'bookdrop') {
this.ref.close('uploaded_to_bookdrop');
}
return;
}
let pending = batch.length;
for (const uploadFile of batch) {
uploadFile.status = 'Uploading';
uploadFile.progress = 0;
const formData = new FormData();
const cleanFile = new File([uploadFile.file], uploadFile.file.name, {type: uploadFile.file.type});
formData.append('file', cleanFile, uploadFile.file.name);
let uploadUrl: string;
if (destination === 'library') {
if (libraryId && pathId) {
formData.append('libraryId', libraryId);
formData.append('pathId', pathId);
}
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload`;
} else {
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload/bookdrop`;
}
const req = new HttpRequest('POST', uploadUrl, formData, {
reportProgress: true
});
this.http.request(req).subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
uploadFile.progress = Math.round((event.loaded / event.total) * 100);
} else if (event.type === HttpEventType.Response) {
uploadFile.status = 'Uploaded';
uploadFile.progress = 100;
if (--pending === 0) {
setTimeout(() => {
this.uploadBatch(files, startIndex + batchSize, batchSize, destination, libraryId, pathId);
}, 1000);
}
}
},
error: (err) => {
uploadFile.status = 'Failed';
uploadFile.progress = 0;
uploadFile.errorMessage = err?.error?.message || this.t.translate('shared.bookUploader.toast.uploadFailedDefault');
if (--pending === 0) {
setTimeout(() => {
this.uploadBatch(files, startIndex + batchSize, batchSize, destination, libraryId, pathId);
}, 1000);
}
}
});
}
}
isChooseDisabled(): boolean {
if (this.value === 'bookdrop') {
return this.isUploading;
}
return !this.selectedLibrary || !this.selectedPath || this.isUploading;
}
isUploadDisabled(): boolean {
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles();
}
isUploadZoneActive(): boolean {
if (this.value === 'bookdrop') {
return true;
}
return !!(this.selectedLibrary && this.selectedPath);
}
formatSize(bytes: number): string {
const k = 1024;
const dm = 2;
if (bytes < k) return `${bytes} B`;
if (bytes < k * k) return `${(bytes / k).toFixed(dm)} KB`;
return `${(bytes / (k * k)).toFixed(dm)} MB`;
}
getBadgeSeverity(status: UploadingFile['status']): 'info' | 'warn' | 'success' | 'danger' {
switch (status) {
case 'Pending':
return 'warn';
case 'Uploading':
return 'info';
case 'Uploaded':
return 'success';
case 'Failed':
return 'danger';
default:
return 'info';
}
}
getFileStatusLabel(uploadFile: UploadingFile): string {
if (uploadFile.status === 'Failed' && uploadFile.errorMessage?.includes('exceeds maximum size')) {
return this.t.translate('shared.bookUploader.statusTooLarge');
}
switch (uploadFile.status) {
case 'Pending':
return this.t.translate('shared.bookUploader.statusReady');
case 'Uploading':
return this.t.translate('shared.bookUploader.statusUploading');
case 'Uploaded':
return this.t.translate('shared.bookUploader.statusUploaded');
case 'Failed':
return this.t.translate('shared.bookUploader.statusFailed');
default:
return uploadFile.status;
}
}
hasUploadCompleted(): boolean {
return this.uploadCompleted;
}
closeDialog(): void {
this.ref.close();
}
getOverallProgress(): number {
if (this.files.length === 0) return 0;
const totalProgress = this.files.reduce((sum, f) => sum + f.progress, 0);
return Math.round(totalProgress / this.files.length);
}
getUploadedCount(): number {
return this.files.filter(f => f.status === 'Uploaded').length;
}
getFailedCount(): number {
return this.files.filter(f => f.status === 'Failed').length;
}
getUploadingCount(): number {
return this.files.filter(f => f.status === 'Uploading').length;
}
getTotalBytes(): number {
return this.files.reduce((sum, f) => sum + f.file.size, 0);
}
getUploadedBytes(): number {
return this.files
.filter(f => f.status === 'Uploaded')
.reduce((sum, f) => sum + f.file.size, 0);
}
}
@@ -0,0 +1,102 @@
<ng-container *transloco="let t; prefix: 'shared.changePassword'">
<div class="change-password-container">
<div class="change-password-card-wrapper">
<div class="change-password-card-border">
<div class="change-password-card">
<div class="change-password-header">
<div class="logo-wrapper">
<div class="icon-circle">
<i class="pi pi-key"></i>
</div>
</div>
<h1 class="change-password-title">{{ t('title') }}</h1>
<p class="change-password-subtitle">{{ t('subtitle') }}</p>
</div>
<form class="change-password-form" #changePasswordForm="ngForm" (ngSubmit)="changePassword()">
<div class="form-field">
<label for="currentPassword" class="form-label">
<i class="pi pi-lock"></i>
<span>{{ t('currentPasswordLabel') }}</span>
</label>
<p-password
id="currentPassword"
name="currentPassword"
required
[(ngModel)]="currentPassword"
[feedback]="false"
[placeholder]="t('currentPasswordPlaceholder')"
[toggleMask]="true"
[fluid]="true"
autocomplete="current-password"
></p-password>
</div>
<div class="form-field">
<label for="newPassword" class="form-label">
<i class="pi pi-lock-open"></i>
<span>{{ t('newPasswordLabel') }}</span>
</label>
<p-password
id="newPassword"
name="newPassword"
required
[(ngModel)]="newPassword"
[feedback]="false"
[placeholder]="t('newPasswordPlaceholder')"
[toggleMask]="true"
[fluid]="true"
autocomplete="new-password"
></p-password>
</div>
<div class="form-field">
<label for="confirmNewPassword" class="form-label">
<i class="pi pi-check-circle"></i>
<span>{{ t('confirmPasswordLabel') }}</span>
</label>
<p-password
id="confirmNewPassword"
name="confirmNewPassword"
required
[(ngModel)]="confirmNewPassword"
[feedback]="false"
[placeholder]="t('confirmPasswordPlaceholder')"
[toggleMask]="true"
[fluid]="true"
autocomplete="new-password"
></p-password>
@if (!passwordsMatch && confirmNewPassword) {
<small class="field-error">
<i class="pi pi-exclamation-circle"></i>
{{ t('validation.passwordsMismatch') }}
</small>
}
</div>
<p-button
fluid
type="submit"
[label]="t('updateBtn')"
icon="pi pi-check"
[disabled]="!changePasswordForm.valid || !passwordsMatch"
class="change-password-button"
/>
@if (errorMessage) {
<div class="message-container error-message">
<p-message severity="error">{{ errorMessage }}</p-message>
</div>
}
@if (successMessage) {
<div class="message-container success-message">
<p-message severity="success">{{ successMessage }}</p-message>
</div>
}
</form>
</div>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,90 @@
@use '../../styles/auth-shared' as auth;
.change-password-container {
@include auth.auth-container;
}
.change-password-wrapper {
@apply flex flex-col items-center gap-6 absolute top-1/4 transform -translate-y-1/4;
}
.change-password-card-wrapper {
@include auth.auth-card-wrapper(500px, -6rem);
}
.change-password-card-border {
@include auth.auth-card-border;
}
.change-password-card {
@include auth.auth-card;
}
.app-title {
@apply text-5xl font-extrabold text-white drop-shadow-lg;
text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
}
.change-password-header {
@include auth.auth-header;
}
.logo-wrapper {
@include auth.auth-logo;
}
.icon-circle {
@include auth.auth-icon-circle;
}
.change-password-title {
@include auth.auth-title;
}
.change-password-subtitle {
@include auth.auth-subtitle;
}
form {
@apply flex flex-col gap-4;
}
.change-password-form {
@include auth.auth-form;
}
.p-field {
@apply flex flex-col gap-2;
}
.form-field {
@include auth.form-field;
}
.form-label {
@include auth.form-label;
}
.field-error {
@include auth.field-error;
}
p-button {
@apply mt-4;
}
.change-password-button {
@include auth.auth-button;
}
.message-container {
@include auth.message-container;
}
.error-message {
@include auth.error-message;
}
.success-message {
@include auth.success-message;
}
@@ -0,0 +1,80 @@
import {Component, inject} from '@angular/core';
import {Button} from 'primeng/button';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Message} from 'primeng/message';
import {Password} from 'primeng/password';
import {MessageService} from 'primeng/api';
import {UserService} from '../../../features/settings/user-management/user.service';
import {AuthService} from '../../service/auth.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@Component({
selector: 'app-change-password',
standalone: true,
imports: [
Button,
FormsModule,
Message,
Password,
ReactiveFormsModule,
TranslocoDirective
],
templateUrl: './change-password.component.html',
styleUrl: './change-password.component.scss'
})
export class ChangePasswordComponent {
currentPassword: string = '';
newPassword: string = '';
confirmNewPassword: string = '';
errorMessage: string | null = null;
successMessage: string | null = null;
protected userService = inject(UserService);
protected authService = inject(AuthService);
protected messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
get passwordsMatch(): boolean {
return this.newPassword === this.confirmNewPassword;
}
changePassword() {
this.errorMessage = null;
this.successMessage = null;
if (!this.currentPassword || !this.newPassword || !this.confirmNewPassword) {
this.errorMessage = this.t.translate('shared.changePassword.validation.allFieldsRequired');
return;
}
if (!this.passwordsMatch) {
this.errorMessage = this.t.translate('shared.changePassword.validation.passwordsDoNotMatch');
return;
}
if (this.currentPassword === this.newPassword) {
this.errorMessage = this.t.translate('shared.changePassword.validation.sameAsCurrentPassword');
return;
}
this.userService.changePassword(this.currentPassword, this.newPassword).subscribe({
next: () => {
this.successMessage = this.t.translate('shared.changePassword.toast.success');
this.logout();
},
error: (err) => {
this.errorMessage = err.message;
this.messageService.add({
severity: 'error',
summary: this.t.translate('shared.changePassword.toast.failedSummary'),
detail: this.errorMessage ?? this.t.translate('shared.changePassword.toast.failedDetailDefault')
});
}
});
}
logout() {
this.authService.logout();
}
}
@@ -0,0 +1,235 @@
import {ChangeDetectionStrategy, Component, Input} from '@angular/core';
@Component({
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: ''
})
export class CoverGeneratorComponent {
@Input() title: string = '';
@Input() author: string = '';
@Input() isSquare: boolean = false;
private wrapText(text: string, maxLineLength: number): string[] {
const words = text.split(' ');
const lines: string[] = [];
let currentLine = '';
words.forEach(word => {
if (word.length > maxLineLength) {
if (currentLine.length > 0) {
lines.push(currentLine);
currentLine = '';
}
lines.push(word);
} else if (currentLine.length + word.length + 1 > maxLineLength) {
lines.push(currentLine);
currentLine = word;
} else {
currentLine += (currentLine.length > 0 ? ' ' : '') + word;
}
});
if (currentLine.length > 0) {
lines.push(currentLine);
}
return lines;
}
private truncateText(text: string, maxLength: number): string {
if (text.length <= maxLength) return text;
return text.substring(0, maxLength - 3) + '...';
}
private escapeXml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
private hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return Math.abs(hash);
}
generateCover(): string {
const width = 250;
const height = this.isSquare ? 250 : 350;
const hash = this.hashString(this.title + this.author);
if (this.isSquare) {
return this.generateAudiobookCover(width, height, hash);
} else {
return this.generateEbookCover(width, height, hash);
}
}
private generateEbookCover(width: number, height: number, hash: number): string {
const palettes = [
{bg1: '#1a1a2e', bg2: '#16213e', accent: '#e94560', text: '#eaeaea', textSecondary: '#b8b8b8'},
{bg1: '#2d3436', bg2: '#636e72', accent: '#74b9ff', text: '#ffffff', textSecondary: '#dfe6e9'},
{bg1: '#0c3547', bg2: '#1a5276', accent: '#f39c12', text: '#ecf0f1', textSecondary: '#bdc3c7'},
{bg1: '#1e3d59', bg2: '#17263a', accent: '#ffc13b', text: '#f5f0e1', textSecondary: '#c7b198'},
{bg1: '#2c2c54', bg2: '#474787', accent: '#ff793f', text: '#f8f8f8', textSecondary: '#d1ccc0'},
{bg1: '#1b262c', bg2: '#0f4c75', accent: '#3282b8', text: '#bbe1fa', textSecondary: '#8fbdd3'},
];
const palette = palettes[hash % palettes.length];
const {titleLines, authorLines, titleFontSize, authorFontSize} = this.processText(false);
const titleLineHeight = titleFontSize * 1.3;
const titleStartY = 80;
const titleElements = titleLines.map((line, index) => {
const y = titleStartY + (index * titleLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Georgia, serif" font-weight="600" font-size="${titleFontSize}" fill="${palette.text}">${this.escapeXml(line)}</text>`;
}).join('\n');
const authorLineHeight = authorFontSize * 1.3;
const authorStartY = height - 50 - ((authorLines.length - 1) * authorLineHeight);
const authorElements = authorLines.map((line, index) => {
const y = authorStartY + (index * authorLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-size="${authorFontSize}" fill="${palette.textSecondary}">${this.escapeXml(line)}</text>`;
}).join('\n');
const decorY = titleStartY + (titleLines.length * titleLineHeight) + 20;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
<defs>
<linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:${palette.bg1}"/>
<stop offset="100%" style="stop-color:${palette.bg2}"/>
</linearGradient>
<linearGradient id="spineGrad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgba(0,0,0,0.4)"/>
<stop offset="100%" style="stop-color:rgba(0,0,0,0)"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#bgGrad)"/>
<rect x="0" y="0" width="12" height="100%" fill="url(#spineGrad)"/>
<rect x="20" y="20" width="${width - 40}" height="${height - 40}" fill="none" stroke="${palette.accent}" stroke-width="1" opacity="0.4" rx="2"/>
<rect x="25" y="25" width="${width - 50}" height="${height - 50}" fill="none" stroke="${palette.accent}" stroke-width="0.5" opacity="0.2" rx="1"/>
${titleElements}
<line x1="80" y1="${decorY}" x2="170" y2="${decorY}" stroke="${palette.accent}" stroke-width="2" stroke-linecap="round"/>
<circle cx="125" cy="${decorY}" r="3" fill="${palette.accent}"/>
${authorElements}
<rect x="0" y="0" width="100%" height="100%" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1"/>
</svg>`;
return this.svgToDataUrl(svg);
}
private generateAudiobookCover(width: number, height: number, hash: number): string {
const palettes = [
{bg1: '#667eea', bg2: '#764ba2', accent: '#ffffff', text: '#ffffff', textSecondary: '#e8e8e8'},
{bg1: '#f093fb', bg2: '#f5576c', accent: '#ffffff', text: '#ffffff', textSecondary: '#ffeaea'},
{bg1: '#4facfe', bg2: '#00f2fe', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'},
{bg1: '#43e97b', bg2: '#38f9d7', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'},
{bg1: '#fa709a', bg2: '#fee140', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'},
{bg1: '#a18cd1', bg2: '#fbc2eb', accent: '#ffffff', text: '#2d3436', textSecondary: '#4a4a4a'},
];
const palette = palettes[hash % palettes.length];
const {titleLines, authorLines, titleFontSize, authorFontSize} = this.processText(true);
const titleLineHeight = titleFontSize * 1.3;
const titleStartY = 70;
const titleElements = titleLines.map((line, index) => {
const y = titleStartY + (index * titleLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-weight="700" font-size="${titleFontSize}" fill="${palette.text}">${this.escapeXml(line)}</text>`;
}).join('\n');
const authorLineHeight = authorFontSize * 1.3;
const authorStartY = height - 40 - ((authorLines.length - 1) * authorLineHeight);
const authorElements = authorLines.map((line, index) => {
const y = authorStartY + (index * authorLineHeight);
return `<text x="125" y="${y}" text-anchor="middle" font-family="Helvetica, Arial, sans-serif" font-size="${authorFontSize}" fill="${palette.textSecondary}">${this.escapeXml(line)}</text>`;
}).join('\n');
const iconY = titleStartY + (titleLines.length * titleLineHeight) + 25;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
<defs>
<linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:${palette.bg1}"/>
<stop offset="100%" style="stop-color:${palette.bg2}"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#bgGrad)"/>
<circle cx="125" cy="125" r="100" fill="none" stroke="${palette.accent}" stroke-width="1" opacity="0.15"/>
<circle cx="125" cy="125" r="80" fill="none" stroke="${palette.accent}" stroke-width="1" opacity="0.1"/>
${titleElements}
<g transform="translate(125, ${iconY})" opacity="0.9">
<circle cx="0" cy="0" r="18" fill="none" stroke="${palette.accent}" stroke-width="2" opacity="0.6"/>
<path d="M-6,-8 L-6,8 L8,0 Z" fill="${palette.accent}" opacity="0.8"/>
</g>
${authorElements}
</svg>`;
return this.svgToDataUrl(svg);
}
private processText(isSquare: boolean): {
titleLines: string[];
authorLines: string[];
titleFontSize: number;
authorFontSize: number;
} {
const maxTitleLength = 60;
const maxAuthorLength = 40;
const truncatedTitle = this.truncateText(this.title, maxTitleLength);
const truncatedAuthor = this.truncateText(this.author, maxAuthorLength);
const maxLineLength = 14;
const maxTitleLines = isSquare ? 3 : 4;
const maxAuthorLines = isSquare ? 2 : 3;
let titleLines = this.wrapText(truncatedTitle, maxLineLength);
let authorLines = this.wrapText(truncatedAuthor, maxLineLength);
if (titleLines.length > maxTitleLines) {
titleLines = titleLines.slice(0, maxTitleLines);
titleLines[maxTitleLines - 1] = this.truncateText(titleLines[maxTitleLines - 1], maxLineLength);
}
if (authorLines.length > maxAuthorLines) {
authorLines = authorLines.slice(0, maxAuthorLines);
authorLines[maxAuthorLines - 1] = this.truncateText(authorLines[maxAuthorLines - 1], maxLineLength);
}
const titleFontSize = this.calculateTitleFontSize(titleLines.length);
const authorFontSize = this.calculateAuthorFontSize(authorLines.length);
return {titleLines, authorLines, titleFontSize, authorFontSize};
}
private calculateTitleFontSize(lineCount: number): number {
if (lineCount <= 2) return 28;
if (lineCount === 3) return 24;
return 20;
}
private calculateAuthorFontSize(lineCount: number): number {
if (lineCount <= 2) return 18;
return 16;
}
private svgToDataUrl(svg: string): string {
const base64 = btoa(encodeURIComponent(svg).replace(/%([0-9A-F]{2})/g, (_, p1) => {
return String.fromCharCode(parseInt(p1, 16));
}));
return `data:image/svg+xml;base64,${base64}`;
}
}
@@ -0,0 +1,189 @@
<ng-container *transloco="let t; prefix: 'shared.directoryPicker'">
<div class="directory-picker">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-folder-open header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">{{ t('title') }}</h2>
<p class="panel-description">{{ t('description') }}</p>
</div>
</div>
<div class="picker-controls">
<div class="current-path">
<div class="path-label">
<i class="pi pi-map-marker"></i>
<span>{{ t('currentPath') }}</span>
</div>
<div class="path-value">
{{ selectedProductName || '/' }}
</div>
</div>
<div class="controls-row">
<p-iconfield class="search-input-wrapper">
<p-inputicon class="pi pi-search"/>
<input
fluid
type="text"
pInputText
[(ngModel)]="searchQuery"
(input)="onSearch()"
[placeholder]="t('searchPlaceholder')"
/>
@if (searchQuery) {
<i class="pi pi-times clear-icon" (click)="searchQuery = ''; onSearch()"></i>
}
</p-iconfield>
<p-button
icon="pi pi-arrow-up"
(click)="goUp()"
[disabled]="selectedProductName === '/' || selectedProductName === ''"
[pTooltip]="t('goUpTooltip')"
tooltipPosition="bottom"
/>
</div>
<div class="selection-actions">
<p-button
[label]="t('selectAllBtn')"
icon="pi pi-check-square"
severity="secondary"
[outlined]="true"
size="small"
(click)="selectAll()"
[disabled]="filteredPaths.length === 0"
[pTooltip]="t('selectAllTooltip')"
tooltipPosition="bottom"
/>
<p-button
[label]="t('deselectAllBtn')"
icon="pi pi-times-circle"
severity="secondary"
[outlined]="true"
size="small"
(click)="deselectAll()"
[disabled]="selectedFolders.length === 0"
[pTooltip]="t('deselectAllTooltip')"
tooltipPosition="bottom"
/>
<p-button
[label]="t('selectCurrentBtn')"
icon="pi pi-folder"
severity="info"
[outlined]="true"
size="small"
(click)="selectCurrent()"
[disabled]="!selectedProductName || selectedProductName === '/'"
[pTooltip]="t('selectCurrentTooltip')"
tooltipPosition="bottom"
/>
</div>
@if (selectedFolders.length > 0) {
<div class="selection-badge">
<i class="pi pi-check-circle"></i>
<span>{{ selectedFolders.length === 1 ? t('foldersSelected', { count: selectedFolders.length }) : t('foldersSelectedPlural', { count: selectedFolders.length }) }}</span>
</div>
}
</div>
<div class="directories-container">
@if (isLoading) {
<div class="loading-state">
<p-progressSpinner
class="custom-spinner"
strokeWidth="4"
animationDuration="1s"
/>
<p class="loading-text">{{ t('loadingDirectories') }}</p>
</div>
} @else if (filteredPaths.length === 0) {
<div class="empty-state">
<div class="empty-icon-wrapper">
<i class="pi pi-folder-open empty-icon"></i>
</div>
<h3 class="empty-title">
@if (searchQuery) {
{{ t('noMatchesFound') }}
} @else {
{{ t('directoryEmpty') }}
}
</h3>
<p class="empty-description">
@if (searchQuery) {
<span [innerHTML]="t('noMatchesDescription')"></span>
} @else {
{{ t('emptyDescription') }}
}
</p>
</div>
} @else {
<div class="directories-list">
<div class="list-header">
<span class="folder-count">
<i class="pi pi-folder"></i>
{{ filteredPaths.length === 1 ? t('folderAvailable', { count: filteredPaths.length }) : t('foldersAvailable', { count: filteredPaths.length }) }}
</span>
</div>
<div class="directories-grid" [class.fade-in]="!isLoading && filteredPaths.length > 0">
@for (folder of filteredPaths; track folder) {
<div
class="directory-item"
[class.selected]="isFolderSelected(folder)"
>
<div class="directory-checkbox">
<p-checkbox
[inputId]="'folder-' + folder"
[binary]="true"
[(ngModel)]="selectedFoldersMap[folder]"
(ngModelChange)="onCheckboxChange(folder, $event)"
(click)="$event.stopPropagation()"
/>
</div>
<label [for]="'folder-' + folder" class="directory-label" (click)="onRowClick(folder)">
<div class="directory-icon-wrapper">
<i class="pi pi-folder directory-icon"></i>
</div>
<div class="directory-info">
<span class="directory-name">{{ getFolderName(folder) }}</span>
<span class="directory-path">{{ folder }}</span>
</div>
<i class="pi pi-chevron-right navigate-icon"></i>
</label>
</div>
}
</div>
</div>
}
</div>
<div class="dialog-footer">
<div class="footer-info">
@if (selectedFolders.length > 0) {
<span class="selection-info">
<i class="pi pi-info-circle"></i>
{{ selectedFolders.length === 1 ? t('folderWillBeSelected', { count: selectedFolders.length }) : t('foldersWillBeSelected', { count: selectedFolders.length }) }}
</span>
}
</div>
<div class="footer-actions">
<p-button
[label]="'common.cancel' | transloco"
severity="secondary"
[outlined]="true"
(click)="onCancel()"
/>
<p-button
[label]="t('selectDirectoriesBtn')"
icon="pi pi-check"
severity="success"
(click)="onSelect()"
[disabled]="selectedFolders.length === 0"
/>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,590 @@
@use '../../styles/panel-shared' as panel;
.responsive-table {
min-width: 50rem;
@media (max-width: 768px) {
min-width: 100% !important;
width: 100% !important;
}
}
.directory-picker {
width: 700px;
max-width: 700px;
display: flex;
flex-direction: column;
height: 80vh;
max-height: 900px;
@media (max-width: 640px) {
width: 100%;
max-width: 100%;
height: 90vh;
}
}
.panel-header {
@include panel.panel-header;
}
.picker-controls {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem 2rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
.current-path {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.625rem;
background: var(--overlay-background);
border-radius: 6px;
.path-label {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--text-secondary-color);
font-weight: 600;
font-size: 0.9rem;
white-space: nowrap;
i {
color: coral;
}
}
.path-value {
flex: 1;
color: var(--text-color);
font-family: monospace;
font-size: 0.875rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.controls-row {
display: flex;
gap: 0.75rem;
.search-input-wrapper {
position: relative;
flex: 1;
::ng-deep {
.p-inputicon {
color: var(--text-secondary-color);
}
}
.clear-icon {
position: absolute;
right: 1rem;
top: 50%;
transform: translateY(-50%);
color: var(--text-secondary-color);
cursor: pointer;
transition: color 0.2s;
z-index: 1;
&:hover {
color: var(--text-color);
}
}
}
}
.selection-actions {
display: flex;
gap: 0.5rem;
align-items: center;
@media (max-width: 640px) {
flex-direction: column;
width: 100%;
::ng-deep .p-button {
width: 100%;
}
}
}
.selection-badge {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.5rem 0.875rem;
background: var(--primary-color);
color: var(--primary-contrast-color);
border-radius: 6px;
font-weight: 600;
font-size: 0.875rem;
i {
font-size: 0.875rem;
}
}
@media (max-width: 480px) {
padding: 1rem;
gap: 0.5rem;
.current-path {
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
.path-value {
width: 100%;
}
}
.controls-row {
flex-direction: column;
gap: 0.5rem;
}
}
}
.directories-container {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem 2rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
flex: 1;
min-height: 0;
overflow: hidden;
@media (max-width: 480px) {
padding: 1rem;
}
}
.loading-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex: 1;
color: var(--text-secondary-color);
::ng-deep .custom-spinner {
.p-progress-spinner-circle {
stroke: var(--primary-color);
}
}
}
.loading-text {
margin-top: 0.75rem;
color: var(--text-secondary-color);
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 2rem 1rem;
flex: 1;
.empty-icon-wrapper {
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
background: var(--overlay-background);
border-radius: 50%;
margin-bottom: 1rem;
.empty-icon {
font-size: 2.5rem;
color: var(--text-secondary-color);
opacity: 0.5;
}
}
.empty-title {
margin: 0 0 0.5rem 0;
font-size: 1.125rem;
font-weight: 600;
color: var(--text-color);
}
.empty-description {
margin: 0;
font-size: 0.875rem;
color: var(--text-secondary-color);
max-width: 350px;
line-height: 1.5;
}
@media (max-width: 480px) {
padding: 1.5rem 0.75rem;
.empty-icon-wrapper {
width: 60px;
height: 60px;
.empty-icon {
font-size: 2rem;
}
}
.empty-title {
font-size: 1rem;
}
.empty-description {
font-size: 0.8rem;
max-width: 100%;
}
}
}
.directories-list {
display: flex;
flex-direction: column;
gap: 0.625rem;
height: 100%;
overflow: hidden;
}
.list-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem 0.875rem;
background: var(--overlay-background);
border-radius: 6px;
.folder-count {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-color);
i {
color: var(--primary-color);
}
}
@media (max-width: 480px) {
padding: 0.5rem 0.625rem;
.folder-count {
font-size: 0.8rem;
}
}
}
.directories-grid {
display: flex;
flex-direction: column;
gap: 0.625rem;
overflow-y: auto;
overflow-x: hidden;
flex: 1;
padding-right: 0.25rem;
min-height: 0;
opacity: 1;
transition: opacity 0.3s ease-in-out;
width: 100%;
&.loading {
opacity: 0;
}
&.fade-in {
animation: fadeInUp 0.4s ease-out;
}
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: var(--overlay-background);
border-radius: 3px;
}
&::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
transition: background 0.2s ease;
&:hover {
background: var(--primary-color);
}
}
scrollbar-width: thin;
scrollbar-color: var(--border-color) var(--overlay-background);
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.directory-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1rem;
background: var(--ground-background);
border: 1px solid var(--border-color);
border-radius: 6px;
transition: all 0.3s ease;
cursor: pointer;
opacity: 0;
animation: fadeInItem 0.3s ease-out forwards;
width: 100%;
max-width: 100%;
@for $i from 1 through 20 {
&:nth-child(#{$i}) {
animation-delay: #{$i * 0.03}s;
}
}
&:hover {
border-color: var(--primary-color);
transform: translateY(3px);
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
.directory-icon {
color: var(--primary-color);
transform: scale(1.08);
}
.navigate-icon {
opacity: 1;
transform: translateY(2px);
}
}
&.selected {
border-color: var(--p-primary-800);
.directory-icon-wrapper {
background: var(--primary-color);
.directory-icon {
color: var(--primary-contrast-color);
}
}
}
.directory-checkbox {
display: flex;
align-items: center;
}
.directory-label {
flex: 1;
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
min-width: 0;
.directory-icon-wrapper {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
background: var(--overlay-background);
border-radius: 6px;
flex-shrink: 0;
.directory-icon {
font-size: 1rem;
color: var(--text-secondary-color);
transition: all 0.3s ease;
}
}
.directory-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.1875rem;
min-width: 0;
overflow: hidden;
.directory-name {
font-size: 0.875rem;
color: var(--text-color);
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
line-height: 1.3;
}
.directory-path {
font-size: 0.75rem;
color: var(--text-secondary-color);
font-family: monospace;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
line-height: 1.2;
}
}
.navigate-icon {
color: var(--text-secondary-color);
opacity: 0;
transition: all 0.3s ease;
flex-shrink: 0;
}
}
@media (max-width: 480px) {
padding: 0.5rem 0.625rem;
gap: 0.375rem;
.directory-label {
gap: 0.375rem;
.directory-icon-wrapper {
width: 26px;
height: 26px;
.directory-icon {
font-size: 0.875rem;
}
}
.directory-info {
.directory-name {
font-size: 0.875rem;
}
.directory-path {
display: none;
}
}
}
}
}
@keyframes fadeInItem {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.selection-note {
margin-top: 0.75rem;
color: var(--text-secondary-color);
}
.dialog-footer {
@include panel.dialog-footer;
border-top: 1px solid var(--border-color);
.selection-info {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--text-secondary-color);
font-size: 0.9rem;
i {
color: var(--primary-color);
}
}
@media (max-width: 480px) {
.footer-info {
text-align: center;
}
}
}
@media (max-width: 768px) {
.directory-picker {
border-radius: 0;
}
.picker-header,
.search-bar,
.current-path,
.directory-list,
.picker-footer {
padding-left: 1rem;
padding-right: 1rem;
}
.folder-item {
.folder-info {
.folder-path {
display: none;
}
}
}
.current-path {
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
.path-value {
width: 100%;
}
.selected-count {
align-self: flex-start;
}
}
.picker-footer {
flex-direction: column;
align-items: stretch;
.footer-info {
text-align: center;
}
.footer-actions {
width: 100%;
button {
flex: 1;
}
}
}
}
@@ -0,0 +1,183 @@
import {Component, inject, OnInit} from '@angular/core';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {UtilityService} from './utility.service';
import {TableModule} from 'primeng/table';
import {InputText} from 'primeng/inputtext';
import {FormsModule} from '@angular/forms';
import {ProgressSpinner} from 'primeng/progressspinner';
import {MenuItem} from 'primeng/api';
import {CheckboxModule} from 'primeng/checkbox';
import {InputIcon} from 'primeng/inputicon';
import {Button} from 'primeng/button';
import {IconField} from 'primeng/iconfield';
import {Tooltip} from 'primeng/tooltip';
import {TranslocoDirective, TranslocoPipe} from '@jsverse/transloco';
@Component({
selector: 'app-directory-picker-v2',
standalone: true,
templateUrl: './directory-picker.component.html',
imports: [
TableModule,
InputText,
FormsModule,
ProgressSpinner,
CheckboxModule,
InputIcon,
Button,
InputIcon,
IconField,
Tooltip,
TranslocoDirective,
TranslocoPipe
],
styleUrls: ['./directory-picker.component.scss']
})
export class DirectoryPickerComponent implements OnInit {
value: unknown;
paths: string[] = [];
filteredPaths: string[] = [];
selectedProductName: string = '';
selectedFolders: string[] = [];
selectedFoldersMap: Record<string, boolean> = {};
searchQuery: string = '';
isLoading: boolean = false;
breadcrumbItems: MenuItem[] = [];
home: MenuItem = {icon: 'pi pi-home', command: () => this.navigateToRoot()};
private utilityService = inject(UtilityService);
private dynamicDialogRef = inject(DynamicDialogRef);
ngOnInit() {
const initialPath = '/';
this.getFolders(initialPath);
}
getFolders(path: string): void {
this.isLoading = true;
this.filteredPaths = [];
this.utilityService.getFolders(path).subscribe({
next: (folders: string[]) => {
setTimeout(() => {
this.paths = folders;
this.filteredPaths = folders;
this.isLoading = false;
this.updateBreadcrumb(path);
folders.forEach(folder => {
this.selectedFoldersMap[folder] = this.selectedFolders.includes(folder);
});
}, 100);
},
error: (error) => {
console.error('Error fetching folders:', error);
this.isLoading = false;
}
});
}
updateBreadcrumb(path: string): void {
if (path === '/' || path === '') {
this.breadcrumbItems = [];
return;
}
const parts = path.split('/').filter(p => p);
this.breadcrumbItems = parts.map((part, index) => {
const fullPath = '/' + parts.slice(0, index + 1).join('/');
return {
label: part,
command: () => this.navigateToPath(fullPath)
};
});
}
navigateToRoot(): void {
this.selectedProductName = '/';
this.getFolders('/');
this.searchQuery = '';
}
navigateToPath(path: string): void {
this.selectedProductName = path;
this.getFolders(path);
this.searchQuery = '';
}
onRowClick(path: string): void {
this.selectedProductName = path;
this.getFolders(path);
this.searchQuery = '';
}
onCheckboxChange(path: string, checked: boolean): void {
const index = this.selectedFolders.indexOf(path);
if (checked && index === -1) {
this.selectedFolders.push(path);
} else if (!checked && index > -1) {
this.selectedFolders.splice(index, 1);
}
}
isFolderSelected(path: string): boolean {
return this.selectedFolders.includes(path);
}
goUp(): void {
if (this.selectedProductName === '' || this.selectedProductName === '/') {
return;
}
const result = this.selectedProductName.substring(0, this.selectedProductName.lastIndexOf('/')) || '/';
this.selectedProductName = result;
this.getFolders(result);
this.searchQuery = '';
}
onSearch(): void {
if (!this.searchQuery.trim()) {
this.filteredPaths = this.paths;
return;
}
const query = this.searchQuery.toLowerCase();
this.filteredPaths = this.paths.filter(path =>
path.toLowerCase().includes(query)
);
}
onSelect(): void {
this.dynamicDialogRef.close(this.selectedFolders);
}
onCancel(): void {
this.dynamicDialogRef.close(null);
}
selectAll(): void {
this.filteredPaths.forEach(folder => {
if (!this.selectedFolders.includes(folder)) {
this.selectedFolders.push(folder);
}
this.selectedFoldersMap[folder] = true;
});
}
deselectAll(): void {
this.selectedFolders = [];
Object.keys(this.selectedFoldersMap).forEach(key => {
this.selectedFoldersMap[key] = false;
});
}
selectCurrent(): void {
const currentPath = this.selectedProductName || '/';
if (!this.selectedFolders.includes(currentPath)) {
this.selectedFolders.push(currentPath);
}
this.selectedFoldersMap[currentPath] = true;
}
getFolderName(path: string): string {
return path.split('/').filter(p => p).pop() || path;
}
}
@@ -0,0 +1,19 @@
import {inject, Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {API_CONFIG} from '../../../core/config/api-config';
@Injectable({
providedIn: 'root'
})
export class UtilityService {
private pathUrl = `${API_CONFIG.BASE_URL}/api/v1/path`;
private http = inject(HttpClient);
getFolders(path: string): Observable<string[]> {
const params = new HttpParams().set('path', path);
return this.http.get<string[]>(this.pathUrl, {params});
}
}
@@ -0,0 +1 @@
<p>empty works!</p>
@@ -0,0 +1,12 @@
import {ChangeDetectionStrategy, Component} from '@angular/core';
@Component({
selector: 'app-empty',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './empty.component.html',
styleUrl: './empty.component.scss'
})
export class EmptyComponent {
}
@@ -0,0 +1,56 @@
import {ChangeDetectionStrategy, Component, Input} from '@angular/core';
import {Tooltip} from 'primeng/tooltip';
export type DocType = 'kobo' | 'opds' | 'metadataManager' | 'koReader' | 'email'
| 'amazonCookie' | 'fetchConfig' | 'hardcover' | 'taskManagement' | 'fileNamePatterns'
| 'authentication';
@Component({
selector: 'app-external-doc-link',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [Tooltip],
template: `
<i class="pi pi-external-link external-link-icon"
[pTooltip]="tooltip"
[tooltipPosition]="tooltipPosition"
[style.font-size]="size"
(click)="openLink()"
style="cursor: pointer;">
</i>
`,
styles: [`
.external-link-icon {
color: #0ea5e9 !important;
}
`]
})
export class ExternalDocLinkComponent {
private readonly BASE_URL = 'https://grimmory.org/docs';
private readonly DOC_URLS: Record<DocType, string> = {
kobo: `${this.BASE_URL}/integration/kobo`,
opds: `${this.BASE_URL}/integration/opds`,
metadataManager: `${this.BASE_URL}/metadata/metadata-manager`,
koReader: `${this.BASE_URL}/integration/koreader`,
email: `${this.BASE_URL}/email-setup`,
amazonCookie: `${this.BASE_URL}/metadata/amazon-cookie`,
hardcover: `${this.BASE_URL}/metadata/hardcover-token`,
fetchConfig: `${this.BASE_URL}/metadata/metadata-fetch-configuration`,
taskManagement: `${this.BASE_URL}/tools/task-manager`,
fileNamePatterns: `${this.BASE_URL}/metadata/file-naming-patterns`,
authentication: `${this.BASE_URL}/authentication/overview#setting-up-oidc`
};
@Input() docType!: DocType;
@Input() tooltip: string = 'View documentation';
@Input() tooltipPosition: 'top' | 'bottom' | 'left' | 'right' = 'right';
@Input() size: string = '1rem';
openLink(): void {
const url = this.DOC_URLS[this.docType];
if (url) {
window.open(url, '_blank');
}
}
}
@@ -0,0 +1,250 @@
<div class="file-mover-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-folder-open header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Move & Organize Files</h2>
<p class="panel-description">{{ books.length }} book{{ books.length !== 1 ? 's' : '' }} selected</p>
</div>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(click)="ref.close()"
class="close-button">
</p-button>
</div>
<div class="dialog-content">
<!-- Compact Info Banner -->
<section class="info-banner">
<div class="banner-main">
<div class="banner-icon">
<i class="pi pi-info-circle"></i>
</div>
<div class="banner-content">
<span class="banner-text">
Preview and organize <strong>{{ filePreviews.length }} file{{ filePreviews.length !== 1 ? 's' : '' }}</strong>.
Files will be renamed based on metadata and naming patterns.
</span>
<span class="banner-warning">
<i class="pi pi-exclamation-triangle"></i>
Requires good metadata quality.
</span>
</div>
<button type="button" class="banner-toggle" (click)="toggleInfoCollapsed()">
<span>{{ infoCollapsed ? 'Learn more' : 'Hide' }}</span>
<i [class]="infoCollapsed ? 'pi pi-chevron-down' : 'pi pi-chevron-up'"></i>
</button>
</div>
@if (!infoCollapsed) {
<div class="banner-details">
<div class="detail-item">
<i class="pi pi-check-circle"></i>
<span>Your files will be automatically renamed, organized, and can be moved between libraries based on your preferences. Check the preview below to see how your files will look.</span>
</div>
<div class="detail-item">
<i class="pi pi-cog"></i>
<span>Want to change how files are named? Go to <strong>Settings → File Naming Pattern</strong>. Each library can have its own naming pattern!</span>
</div>
<div class="detail-item warning">
<i class="pi pi-exclamation-triangle"></i>
<span>This will actually move and rename files on your computer across different library folders. Make sure you're happy with the preview first!</span>
</div>
<div class="detail-item danger">
<i class="pi pi-shield"></i>
<span>This feature relies entirely on your books' metadata. If your metadata is missing or inconsistent, the resulting file names will be incorrect. Only recommended for well-curated libraries.</span>
</div>
</div>
}
</section>
<!-- Naming Patterns Section -->
<section class="patterns-section">
<button type="button" class="patterns-toggle" (click)="togglePatternsCollapsed()">
<div class="toggle-content">
<i class="pi pi-code"></i>
<span>Naming Rules</span>
<span class="patterns-count">{{ libraryPatterns.length }}</span>
</div>
<i [class]="patternsCollapsed ? 'pi pi-chevron-down' : 'pi pi-chevron-up'"></i>
</button>
@if (!patternsCollapsed) {
<div class="patterns-list">
@for (pattern of libraryPatterns; track pattern.libraryId) {
<div class="pattern-card">
<div class="pattern-header">
<span class="pattern-library">{{ pattern.libraryName }}</span>
<span class="pattern-badge">{{ pattern.bookCount }} book{{ pattern.bookCount > 1 ? 's' : '' }}</span>
</div>
<code class="pattern-code">{{ pattern.pattern || 'No pattern configured' }}</code>
<span class="pattern-source">{{ pattern.source }}</span>
</div>
}
</div>
}
</section>
<!-- Bulk Select Section -->
<section class="bulk-section">
<div class="bulk-header">
<i class="pi pi-list"></i>
<span>Bulk Assignment</span>
</div>
<div class="bulk-controls">
<label class="bulk-label">Set all files to:</label>
<p-select
[options]="availableLibraries"
[(ngModel)]="defaultTargetLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select library"
(onChange)="onDefaultLibraryChange()"
class="select-library"
size="small"
appendTo="body"
></p-select>
@if (defaultAvailableLibraryPaths.length > 0) {
<p-select
[options]="defaultAvailableLibraryPaths"
[(ngModel)]="defaultTargetLibraryPathId"
optionLabel="path"
optionValue="id"
placeholder="Select path"
(onChange)="onDefaultLibraryPathChange()"
class="select-path"
size="small"
appendTo="body"
></p-select>
}
</div>
</section>
<!-- Table Section -->
<section class="table-section">
<div class="table-header">
<i class="pi pi-table"></i>
<span>File Preview</span>
</div>
<div class="table-container">
<p-table
[value]="filePreviews"
[scrollable]="true"
scrollHeight="flex"
[virtualScroll]="true"
[virtualScrollItemSize]="46"
[rows]="50"
>
<ng-template pTemplate="header">
<tr>
<th style="width: 50px;"></th>
<th style="width: 60px;">ID</th>
<th>Current Path</th>
<th style="width: 160px;">Target Library</th>
<th style="width: 160px;">Library Path</th>
<th style="width: 40px;"></th>
<th>New Path</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-preview>
<tr [class.row-moved]="preview.isMoved">
<td class="status-cell">
@if (preview.isMoved) {
<i class="pi pi-check-circle status-success"></i>
} @else {
<i class="pi pi-clock status-pending"></i>
}
</td>
<td class="id-cell">{{ preview.bookId }}</td>
<td>
<div class="path-cell">
<span class="path-library">{{ preview.currentLibraryName }}/</span>
<span class="path-value">{{ preview.relativeOriginalPath }}</span>
</div>
</td>
<td>
<p-select
[options]="availableLibraries"
[(ngModel)]="preview.targetLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select"
(onChange)="onLibraryChange(preview)"
[disabled]="preview.isMoved"
class="select-full-width"
appendTo="body"
size="small"
></p-select>
</td>
<td>
@if (preview.availableLibraryPaths.length > 0) {
<p-select
[options]="preview.availableLibraryPaths"
[(ngModel)]="preview.targetLibraryPathId"
optionLabel="path"
optionValue="id"
placeholder="Select"
(onChange)="onLibraryPathChange(preview)"
[disabled]="preview.isMoved"
class="select-full-width"
appendTo="body"
size="small"
></p-select>
} @else {
<span class="no-paths">No paths</span>
}
</td>
<td class="arrow-cell">
<i class="pi pi-arrow-right"></i>
</td>
<td>
<div class="path-cell">
<span class="path-library">{{ preview.targetLibraryName }}/</span>
<span class="path-value">{{ preview.relativeNewPath }}</span>
</div>
</td>
</tr>
</ng-template>
</p-table>
</div>
</section>
</div>
<div class="dialog-footer">
@if (movedFileCount > 0) {
<div class="success-indicator">
<i class="pi pi-check-circle"></i>
<span>{{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved</span>
</div>
}
<div class="footer-actions">
@if (movedFileCount === 0) {
<p-button
label="Cancel"
icon="pi pi-times"
severity="secondary"
[outlined]="true"
(click)="cancel()"
></p-button>
<p-button
[label]="loading ? 'Moving...' : 'Move Files'"
[icon]="loading ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
severity="success"
(click)="saveChanges()"
[disabled]="loading || filePreviews.length === 0"
></p-button>
} @else {
<p-button
label="Close"
icon="pi pi-check"
severity="primary"
(click)="cancel()"
></p-button>
}
</div>
</div>
</div>
@@ -0,0 +1,526 @@
@use '../../styles/panel-shared' as panel;
:host {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.file-mover-container {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.panel-header {
@include panel.panel-header;
flex-shrink: 0;
}
.dialog-content {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto;
min-height: 0;
padding: 1.25rem;
gap: 1.25rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
border-bottom: none;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
&:hover {
background: var(--primary-color);
}
}
}
.dialog-footer {
@include panel.dialog-footer;
justify-content: space-between;
}
// Compact Info Banner
.info-banner {
border: 1px solid var(--border-color);
border-radius: 8px;
overflow: hidden;
}
.banner-main {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.875rem 1rem;
}
.banner-icon {
display: flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
background: var(--primary-color);
border-radius: 6px;
flex-shrink: 0;
i {
font-size: 1rem;
color: var(--primary-contrast-color);
}
}
.banner-content {
flex: 1;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.375rem 1rem;
min-width: 0;
}
.banner-text {
font-size: 0.875rem;
color: var(--text-secondary-color);
line-height: 1.4;
strong {
color: var(--text-color);
}
}
.banner-warning {
display: inline-flex;
align-items: center;
gap: 0.375rem;
font-size: 0.8rem;
font-weight: 500;
color: var(--p-orange-400);
i {
font-size: 0.8rem;
}
}
.banner-toggle {
display: flex;
align-items: center;
gap: 0.375rem;
padding: 0.4rem 0.75rem;
background: transparent;
border: 1px solid var(--p-blue-400);
border-radius: 5px;
color: var(--p-blue-400);
font-size: 0.8rem;
cursor: pointer;
transition: all 0.2s ease;
flex-shrink: 0;
&:hover {
background: var(--p-blue-400);
color: white;
}
i {
font-size: 0.7rem;
}
}
.banner-details {
display: flex;
flex-direction: column;
gap: 0.625rem;
padding: 0.875rem 1rem;
border-top: 1px solid var(--border-color);
}
.detail-item {
display: flex;
align-items: flex-start;
gap: 0.5rem;
font-size: 0.85rem;
line-height: 1.4;
color: var(--text-secondary-color);
i {
font-size: 0.85rem;
margin-top: 0.125rem;
color: var(--p-green-400);
flex-shrink: 0;
}
strong {
color: var(--text-color);
}
&.warning {
color: var(--p-yellow-300);
i {
color: var(--p-yellow-400);
}
}
&.danger {
color: var(--p-red-300);
i {
color: var(--p-red-400);
}
}
}
// Patterns Section
.patterns-section {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.patterns-toggle {
display: flex;
align-items: center;
gap: 0.5rem;
width: fit-content;
padding: 0.5rem 0.75rem;
background: transparent;
border: 1px solid var(--border-color);
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
&:hover {
border-color: var(--primary-color);
}
.toggle-content {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.85rem;
font-weight: 500;
color: var(--text-color);
i {
color: var(--primary-color);
}
}
.patterns-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
padding: 0 0.375rem;
background: var(--primary-color);
color: var(--primary-contrast-color);
border-radius: 10px;
font-size: 0.7rem;
font-weight: 600;
}
> i {
font-size: 0.75rem;
color: var(--text-secondary-color);
}
}
.patterns-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.pattern-card {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.75rem;
border: 1px solid var(--border-color);
border-radius: 6px;
}
.pattern-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.pattern-library {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-color);
}
.pattern-badge {
display: inline-flex;
align-items: center;
padding: 0.125rem 0.5rem;
background: var(--p-blue-500);
color: white;
border-radius: 10px;
font-size: 0.65rem;
font-weight: 600;
}
.pattern-code {
font-family: 'SF Mono', 'Fira Code', monospace;
font-size: 0.8rem;
color: var(--primary-color);
background: var(--ground-background);
padding: 0.375rem 0.5rem;
border-radius: 4px;
border: 1px solid var(--border-color);
}
.pattern-source {
font-size: 0.7rem;
color: var(--text-secondary-color);
}
// Bulk Section
.bulk-section {
background: var(--ground-background);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 1rem;
}
.bulk-header {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.75rem;
font-size: 0.85rem;
font-weight: 500;
color: var(--text-color);
i {
color: var(--primary-color);
}
}
.bulk-controls {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.bulk-label {
font-size: 0.8rem;
color: var(--text-secondary-color);
}
// Table Section
.table-section {
background: var(--ground-background);
border: 1px solid var(--border-color);
border-radius: 8px;
overflow: hidden;
flex: 1 1 0;
display: flex;
flex-direction: column;
min-height: 0;
}
.table-header {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1rem;
background: var(--overlay-background);
border-bottom: 1px solid var(--border-color);
font-size: 0.85rem;
font-weight: 500;
color: var(--text-color);
i {
color: var(--primary-color);
}
}
.table-container {
flex: 1 1 0;
min-height: 0;
overflow: hidden;
::ng-deep .p-datatable {
height: 100%;
display: flex;
flex-direction: column;
.p-datatable-table-container {
flex: 1 1 0;
min-height: 0;
}
}
}
:host ::ng-deep {
.p-datatable-tbody > tr > td {
padding: 0.5rem 0.75rem !important;
}
.p-datatable-thead > tr > th:first-child,
.p-datatable-tbody > tr > td.status-cell {
padding-left: 1.5rem !important;
}
}
.id-cell {
font-family: monospace;
font-size: 0.75rem;
color: var(--text-secondary-color);
}
.path-cell {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 0.8rem;
}
.path-library {
color: var(--text-secondary-color);
}
.path-value {
color: var(--text-color);
}
.no-paths {
font-size: 0.75rem;
color: var(--p-red-400);
font-style: italic;
}
.arrow-cell {
text-align: center;
i {
font-size: 0.75rem;
color: var(--primary-color);
}
}
.status-cell {
text-align: center;
}
.status-success {
color: var(--p-green-500);
font-size: 1rem;
}
.status-pending {
color: var(--p-orange-400);
font-size: 1rem;
}
.row-moved {
background: rgba(34, 197, 94, 0.05) !important;
}
// Footer
.success-indicator {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--p-green-500);
font-weight: 600;
font-size: 0.9rem;
i {
font-size: 1.125rem;
animation: pulse 2s infinite;
}
}
.footer-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.6;
}
}
// Select widths
:host ::ng-deep {
.select-library {
min-width: 180px;
}
.select-path {
min-width: 220px;
}
.select-full-width {
width: 100%;
}
}
// Responsive
@media (max-width: 768px) {
.dialog-content {
padding: 1rem;
gap: 1rem;
}
.banner-main {
flex-wrap: wrap;
gap: 0.5rem;
}
.banner-content {
flex: 1 1 100%;
order: 1;
}
.banner-icon {
order: 0;
}
.banner-toggle {
order: 2;
margin-left: auto;
}
.bulk-controls {
flex-direction: column;
align-items: flex-start;
}
.dialog-footer {
flex-direction: column;
gap: 0.75rem;
.footer-actions {
width: 100%;
justify-content: flex-end;
}
}
}
@@ -0,0 +1,391 @@
import {Component, effect, inject, OnDestroy} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
import {TableModule} from 'primeng/table';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MessageService} from 'primeng/api';
import {takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
import {BookService} from '../../../features/book/service/book.service';
import {Book} from '../../../features/book/model/book.model';
import {FileMoveRequest, FileOperationsService} from '../../service/file-operations.service';
import {LibraryService} from "../../../features/book/service/library.service";
import {AppSettingsService} from '../../service/app-settings.service';
import {Select} from 'primeng/select';
import {Library, LibraryPath} from '../../../features/book/model/library.model';
import {replacePlaceholders} from '../../util/pattern-resolver';
interface FilePreview {
bookId: number;
originalPath: string;
relativeOriginalPath: string;
currentLibraryId: number | null;
currentLibraryName: string;
currentLibraryPath: string;
targetLibraryId: number | null;
targetLibraryName: string;
targetLibraryPath: string;
targetLibraryPathId: number | null;
availableLibraryPaths: LibraryPath[];
newPath: string;
relativeNewPath: string;
isMoved?: boolean;
}
@Component({
selector: 'app-file-mover-component',
standalone: true,
imports: [Button, FormsModule, TableModule, Select],
templateUrl: './file-mover-component.html',
styleUrl: './file-mover-component.scss'
})
export class FileMoverComponent implements OnDestroy {
private config = inject(DynamicDialogConfig);
ref = inject(DynamicDialogRef);
private bookService = inject(BookService);
private libraryService = inject(LibraryService);
private fileOperationsService = inject(FileOperationsService);
private messageService = inject(MessageService);
private appSettingsService = inject(AppSettingsService);
private destroy$ = new Subject<void>();
private readonly appSettings = this.appSettingsService.appSettings;
private readonly syncLibraryPatternsEffect = effect(() => {
const settings = this.appSettings();
const libraries = this.libraryService.libraries();
if (!settings) {
return;
}
this.defaultMovePattern = settings.uploadPattern || '';
const booksByLibrary = new Map<number | null, Book[]>();
this.books.forEach(book => {
const libraryId =
book.libraryId ??
book.libraryPath?.id ??
(book as { library?: { id: number } }).library?.id ??
null;
if (!booksByLibrary.has(libraryId)) {
booksByLibrary.set(libraryId, []);
}
booksByLibrary.get(libraryId)!.push(book);
});
this.libraryPatterns = Array.from(booksByLibrary.entries()).map(([libraryId, libraryBooks]) => {
let libraryName = 'Unknown Library';
let pattern = this.defaultMovePattern;
let source = 'App Default';
if (libraryId) {
const library = libraries.find(currentLibrary => currentLibrary.id === libraryId);
if (library) {
libraryName = library.name;
if (library.fileNamingPattern) {
pattern = library.fileNamingPattern;
source = 'Library Setting';
}
}
}
return {
libraryId,
libraryName,
pattern,
source,
bookCount: libraryBooks.length
};
});
this.applyPattern();
});
libraryPatterns: {
libraryId: number | null;
libraryName: string;
pattern: string;
source: string;
bookCount: number;
}[] = [];
defaultMovePattern = '';
loading = false;
patternsCollapsed = true;
infoCollapsed = true;
bookIds = new Set<number>();
books: Book[] = [];
filePreviews: FilePreview[] = [];
defaultTargetLibraryId: number | null = null;
defaultTargetLibraryPathId: number | null = null;
defaultAvailableLibraryPaths: LibraryPath[] = [];
get availableLibraries(): { id: number | null; name: string }[] {
return this.libraryService.libraries().map(lib => ({id: lib.id ?? null, name: lib.name}));
}
constructor() {
this.bookIds = new Set(this.config.data?.bookIds ?? []);
this.books = this.bookService.getBooksByIds([...this.bookIds]);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
applyPattern(): void {
this.filePreviews = this.books.map(book => {
const fileName = book.fileName ?? '';
const fileSubPath = book.fileSubPath ? `${book.fileSubPath.replace(/\/+$/g, '')}/` : '';
const relativeOriginalPath = `${fileSubPath}${fileName}`;
const currentLibraryId = book.libraryId ?? book.libraryPath?.id ?? (book as { library?: { id: number } }).library?.id ?? null;
const currentLibraryName = this.getLibraryNameById(currentLibraryId);
const currentLibraryPath = this.getLibraryPathById(currentLibraryId);
const targetLibraryId = currentLibraryId;
const targetLibraryName = currentLibraryName;
const availableLibraryPaths = this.getLibraryPathsById(targetLibraryId);
const targetLibraryPathId = availableLibraryPaths.length > 0 ? availableLibraryPaths[0].id ?? null : null;
const targetLibraryPath = availableLibraryPaths.length > 0 ? availableLibraryPaths[0].path : '';
const preview: FilePreview = {
bookId: book.id,
originalPath: this.getFullPath(currentLibraryId, relativeOriginalPath),
relativeOriginalPath,
currentLibraryId,
currentLibraryName,
currentLibraryPath,
targetLibraryId,
targetLibraryName,
targetLibraryPath,
targetLibraryPathId,
availableLibraryPaths,
newPath: '',
relativeNewPath: ''
};
this.updatePreviewPaths(preview, book);
return preview;
});
}
onDefaultLibraryChange(): void {
this.defaultAvailableLibraryPaths = this.getLibraryPathsById(this.defaultTargetLibraryId);
this.defaultTargetLibraryPathId = this.defaultAvailableLibraryPaths.length > 0 ? this.defaultAvailableLibraryPaths[0].id ?? null : null;
this.filePreviews.forEach(preview => {
if (!preview.isMoved) {
preview.targetLibraryId = this.defaultTargetLibraryId;
preview.targetLibraryName = this.getLibraryNameById(this.defaultTargetLibraryId);
preview.availableLibraryPaths = this.defaultAvailableLibraryPaths;
preview.targetLibraryPathId = this.defaultTargetLibraryPathId;
preview.targetLibraryPath = this.defaultAvailableLibraryPaths.find(p => p.id === this.defaultTargetLibraryPathId)?.path || '';
const book = this.books.find(b => b.id === preview.bookId);
if (book) {
this.updatePreviewPaths(preview, book);
}
}
});
}
onDefaultLibraryPathChange(): void {
this.filePreviews.forEach(preview => {
if (!preview.isMoved && preview.targetLibraryId === this.defaultTargetLibraryId) {
preview.targetLibraryPathId = this.defaultTargetLibraryPathId;
preview.targetLibraryPath = this.defaultAvailableLibraryPaths.find(p => p.id === this.defaultTargetLibraryPathId)?.path || '';
const book = this.books.find(b => b.id === preview.bookId);
if (book) {
this.updatePreviewPaths(preview, book);
}
}
});
}
onLibraryChange(preview: FilePreview): void {
preview.targetLibraryName = this.getLibraryNameById(preview.targetLibraryId);
preview.availableLibraryPaths = this.getLibraryPathsById(preview.targetLibraryId);
preview.targetLibraryPathId = preview.availableLibraryPaths.length > 0 ? preview.availableLibraryPaths[0].id ?? null : null;
preview.targetLibraryPath = preview.availableLibraryPaths.length > 0 ? preview.availableLibraryPaths[0].path : '';
const book = this.books.find(b => b.id === preview.bookId);
if (book) {
this.updatePreviewPaths(preview, book);
}
}
onLibraryPathChange(preview: FilePreview): void {
const selectedPath = preview.availableLibraryPaths.find(p => p.id === preview.targetLibraryPathId);
preview.targetLibraryPath = selectedPath?.path || '';
const book = this.books.find(b => b.id === preview.bookId);
if (book) {
this.updatePreviewPaths(preview, book);
}
}
private updatePreviewPaths(preview: FilePreview, book: Book): void {
const meta = book.metadata!;
const fileName = book.fileName ?? '';
const extension = fileName.match(/\.[^.]+$/)?.[0] ?? '';
const pattern = this.getPatternForLibrary(preview.targetLibraryId);
const values: Record<string, string> = {
authors: this.sanitize(meta.authors?.join(', ') || 'Unknown Author'),
title: this.sanitize(meta.title || 'Untitled'),
subtitle: this.sanitize(meta.subtitle || ''),
year: this.formatYear(meta.publishedDate),
series: this.sanitize(meta.seriesName || ''),
seriesIndex: this.formatSeriesIndex(meta.seriesNumber ?? undefined),
language: this.sanitize(meta.language || ''),
publisher: this.sanitize(meta.publisher || ''),
isbn: this.sanitize(meta.isbn13 || meta.isbn10 || ''),
currentFilename: this.sanitize(fileName)
};
let newPath: string;
if (!pattern?.trim()) {
newPath = fileName;
} else {
newPath = replacePlaceholders(pattern, values);
if (!newPath.endsWith(extension)) {
newPath += extension;
}
}
preview.relativeNewPath = newPath;
preview.newPath = this.getFullPath(preview.targetLibraryId, newPath);
}
private getPatternForLibrary(libraryId: number | null): string {
if (libraryId === null) {
return this.defaultMovePattern;
}
const libraries = this.libraryService.libraries();
const library = libraries.find((lib: Library) => lib.id === libraryId);
return library?.fileNamingPattern || this.defaultMovePattern;
}
private getLibraryNameById(libraryId: number | null): string {
if (libraryId === null) return 'Unknown Library';
return this.availableLibraries.find(lib => lib.id === libraryId)?.name || 'Unknown Library';
}
private getLibraryPathsById(libraryId: number | null): LibraryPath[] {
if (libraryId === null) return [];
const libraries = this.libraryService.libraries();
const library = libraries.find((lib: Library) => lib.id === libraryId);
return library?.paths || [];
}
private getLibraryPathById(libraryId: number | null): string {
const paths = this.getLibraryPathsById(libraryId);
return paths.map((p: LibraryPath) => p.path).join(', ');
}
private getFullPath(libraryId: number | null, relativePath: string): string {
if (!libraryId) return relativePath;
const paths = this.getLibraryPathsById(libraryId);
const libraryPath = paths.length > 0 ? paths[0].path.replace(/\/+$/g, '') : '';
return libraryPath ? `${libraryPath}/${relativePath}`.replace(/\/\/+/g, '/') : relativePath;
}
get movedFileCount(): number {
return this.filePreviews.filter(p => p.isMoved).length;
}
sanitize(input: string | undefined): string {
const sanitized = (input ?? '')
.replace(/[\\/:*?"<>|]/g, '')
.split('')
.filter(char => {
const code = char.charCodeAt(0);
return code >= 32 && code !== 127;
})
.join('');
return sanitized.replace(/\s+/g, ' ').trim();
}
formatYear(dateStr?: string): string {
if (!dateStr) return '';
const yearMatch = dateStr.match(/^(\d{4})/);
if (yearMatch) {
return yearMatch[1];
}
const date = new Date(dateStr);
return isNaN(date.getTime()) ? '' : date.getUTCFullYear().toString();
}
formatSeriesIndex(seriesNumber?: number): string {
if (seriesNumber == null) return '';
// Check if it's a whole number
if (Number.isInteger(seriesNumber)) {
// Format with leading zero for 1-9
return this.sanitize(seriesNumber.toString().padStart(2, '0'));
} else {
// For decimal numbers, format integer part with leading zero
const intPart = Math.floor(seriesNumber);
const decimalPart = (seriesNumber % 1).toFixed(10).substring(1).replace(/0+$/, '');
return this.sanitize(intPart.toString().padStart(2, '0') + decimalPart);
}
}
saveChanges(): void {
this.loading = true;
const request: FileMoveRequest = {
bookIds: [...this.bookIds],
moves: this.filePreviews.map(preview => ({
bookId: preview.bookId,
targetLibraryId: preview.targetLibraryId,
targetLibraryPathId: preview.targetLibraryPathId
}))
};
this.fileOperationsService.moveFiles(request).pipe(
takeUntil(this.destroy$)
).subscribe({
next: () => {
this.loading = false;
this.filePreviews.forEach(p => (p.isMoved = true));
this.messageService.add({
severity: 'success',
summary: 'Files Organized!',
detail: `Successfully organized ${this.filePreviews.length} file${this.filePreviews.length === 1 ? '' : 's'}.`,
life: 3000
});
},
error: () => {
this.loading = false;
this.messageService.add({
severity: 'error',
summary: 'Oops! Something went wrong',
detail: 'We had trouble organizing your files. Please try again.',
life: 3000
});
}
});
}
cancel(): void {
this.ref.close();
}
togglePatternsCollapsed(): void {
this.patternsCollapsed = !this.patternsCollapsed;
}
toggleInfoCollapsed(): void {
this.infoCollapsed = !this.infoCollapsed;
}
}
@@ -0,0 +1,145 @@
import {Component, inject, Input, OnInit, OnChanges, SimpleChanges, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {IconSelection} from '../../service/icon-picker.service';
import {NgClass, NgStyle} from '@angular/common';
import {IconCacheService} from '../../services/icon-cache.service';
import {IconService} from '../../services/icon.service';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
@Component({
selector: 'app-icon-display',
standalone: true,
imports: [NgClass, NgStyle],
template: `
@if (icon) {
@if (icon.type === 'PRIME_NG') {
<i [class]="getPrimeNgIconClass(icon.value)" [ngClass]="iconClass" [ngStyle]="getPrimeNgStyle()"></i>
} @else {
<div
class="svg-icon-inline"
[innerHTML]="getSvgContent(icon.value)"
[ngClass]="iconClass"
[ngStyle]="getSvgStyle()"
></div>
}
} @else if (displayEmpty) {
<div
[ngStyle]="getEmptyIconStyle()"
></div>
}
`,
styles: [`
:host {
display: inline-flex;
align-items: center;
justify-content: center;
}
.svg-icon-inline {
display: inline-flex;
align-items: center;
justify-content: center;
}
.svg-icon-inline :deep(svg) {
width: 100%;
height: 100%;
display: block;
}
`],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class IconDisplayComponent implements OnInit, OnChanges {
@Input() icon: IconSelection | null = null;
@Input() iconClass: string = 'icon';
@Input() iconStyle: Record<string, string> = {};
@Input() size: string = '16px';
@Input() alt: string = 'Icon';
@Input() displayEmpty: boolean = false;
private iconCache = inject(IconCacheService);
private iconService = inject(IconService);
private sanitizer = inject(DomSanitizer);
private cdr = inject(ChangeDetectorRef);
private lastLoadedIconName: string | null = null;
ngOnInit(): void {
this.loadIconIfNeeded();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['icon']) {
const currentIcon = changes['icon'].currentValue;
const previousIcon = changes['icon'].previousValue;
if (currentIcon?.type === 'CUSTOM_SVG' &&
currentIcon?.value !== previousIcon?.value) {
this.loadIconIfNeeded();
}
}
}
private loadIconIfNeeded(): void {
if (this.icon?.type === 'CUSTOM_SVG' && this.icon.value !== this.lastLoadedIconName) {
this.lastLoadedIconName = this.icon.value;
if (!this.iconCache.getCachedSanitized(this.icon.value)) {
this.iconService.getSanitizedSvgContent(this.icon.value).subscribe({
next: () => this.cdr.markForCheck(),
error: () => {
if (this.icon?.type === 'CUSTOM_SVG') {
const errorSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="red"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>';
const sanitized = this.sanitizer.bypassSecurityTrustHtml(errorSvg);
this.iconCache.cacheIcon(this.icon.value, errorSvg, sanitized);
this.cdr.markForCheck();
}
}
});
}
}
}
getSvgContent(iconName: string): SafeHtml | null {
return this.iconCache.getCachedSanitized(iconName) || null;
}
getPrimeNgIconClass(iconValue: string): string {
if (iconValue.startsWith('pi pi-')) {
return iconValue;
}
if (iconValue.startsWith('pi-')) {
return `pi ${iconValue}`;
}
return `pi pi-${iconValue}`;
}
getSvgStyle(): Record<string, string> {
return {
width: this.size,
height: this.size,
...this.iconStyle
};
}
getEmptyIconStyle(): Record<string, string> {
return {
width: this.size,
height: this.size,
};
}
getPrimeNgStyle(): Record<string, string> {
const fontSize = this.size.endsWith('px')
? `${parseInt(this.size) * 0.85}px`
: `calc(${this.size} * 0.85)`;
return {
fontSize: fontSize,
width: this.size,
height: this.size,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
...this.iconStyle
};
}
}
@@ -0,0 +1,249 @@
<div class="icon-picker">
<header class="dialog-header">
<div class="header-content">
<div class="header-icon">
<i class="pi pi-palette"></i>
</div>
<div class="header-text">
<h1>Choose an Icon</h1>
<p>Select from library or add custom SVGs</p>
</div>
</div>
<p-button
icon="pi pi-times"
[text]="true"
[rounded]="true"
severity="secondary"
(onClick)="ref.close()"
/>
</header>
<div class="dialog-body">
<p-tabs [(value)]="activeTabIndex">
<p-tablist>
<p-tab value="0">
<i class="pi pi-prime"></i>
<span>Prime Icons</span>
</p-tab>
<p-tab value="1">
<i class="pi pi-images"></i>
<span>SVG Library</span>
</p-tab>
@if (canManageIcons) {
<p-tab value="2">
<i class="pi pi-plus-circle"></i>
<span>Add Custom</span>
</p-tab>
}
</p-tablist>
<p-tabpanels>
<!-- Prime Icons Tab -->
<p-tabpanel value="0">
<div class="tab-content">
<div class="search-container">
<i class="pi pi-search search-icon"></i>
<input
type="text"
pInputText
placeholder="Search Prime icons..."
[(ngModel)]="searchText"
class="search-input"
/>
</div>
<div class="icon-grid">
@for (icon of filteredIcons(); track icon) {
<div
class="icon-item"
(click)="selectIcon(icon)"
[class.selected]="icon === selectedIcon"
[title]="icon"
>
<i [class]="icon"></i>
</div>
}
</div>
</div>
</p-tabpanel>
<!-- SVG Library Tab -->
<p-tabpanel value="1">
<div class="tab-content">
@if (isLoadingSvgIcons) {
<div class="loading-state">
<i class="pi pi-spin pi-spinner"></i>
<span>Loading icons...</span>
</div>
} @else if (svgIconsError) {
<div class="error-state">
<i class="pi pi-exclamation-triangle"></i>
<span>{{ svgIconsError }}</span>
</div>
} @else {
<div class="search-container">
<i class="pi pi-search search-icon"></i>
<input
type="text"
pInputText
placeholder="Search SVG icons..."
[(ngModel)]="svgSearchText"
class="search-input"
/>
</div>
<div class="icon-grid">
@for (iconName of filteredSvgIcons(); track iconName) {
<div
class="icon-item svg-icon-item"
(click)="selectSvgIcon(iconName)"
[class.selected]="iconName === selectedSvgIcon"
[title]="iconName"
draggable="true"
(dragstart)="onSvgIconDragStart(iconName)"
(dragend)="onSvgIconDragEnd()"
>
<div class="svg-icon-inline" [innerHTML]="getSvgContent(iconName)"></div>
</div>
}
</div>
@if (canManageIcons) {
<div class="trash-zone-container">
<div
class="trash-zone"
[class.active]="isTrashHover"
(dragover)="onTrashDragOver($event)"
(dragleave)="onTrashDragLeave($event)"
(drop)="onTrashDrop($event)"
>
<i class="pi pi-trash"></i>
<span>Drop here to delete</span>
</div>
</div>
}
}
</div>
</p-tabpanel>
<!-- Add Custom SVG Tab -->
@if (canManageIcons) {
<p-tabpanel value="2">
<div class="tab-content">
<section class="form-section">
<div class="section-header">
<i class="pi pi-code"></i>
<span>SVG Input</span>
</div>
<div class="form-fields">
<div class="form-field">
<label>Icon Name</label>
<input
type="text"
pInputText
[(ngModel)]="svgName"
placeholder="e.g., my-custom-icon"
class="input-full"
/>
</div>
<div class="form-field">
<label>SVG Code</label>
<textarea
pInputTextarea
[(ngModel)]="svgContent"
(ngModelChange)="onSvgContentChange()"
placeholder="<svg>...</svg>"
[rows]="6"
class="code-textarea"
></textarea>
</div>
@if (svgContent && svgPreview) {
<div class="preview-card">
<div class="preview-label">Preview</div>
<div class="preview-content" [innerHTML]="svgPreview"></div>
</div>
}
@if (errorMessage) {
<div class="error-message">
<i class="pi pi-exclamation-circle"></i>
<span>{{ errorMessage }}</span>
</div>
}
</div>
<div class="form-actions">
<p-button
label="Add to Queue"
icon="pi pi-plus"
[outlined]="true"
[disabled]="!svgContent || !svgName"
(onClick)="addSvgEntry()"
/>
</div>
</section>
@if (svgEntries.length > 0) {
<section class="form-section queue-section">
<div class="section-header">
<i class="pi pi-list"></i>
<span>Queue</span>
<span class="section-badge">{{ svgEntries.length }}</span>
<div class="section-actions">
<p-button
label="Clear All"
icon="pi pi-times"
severity="danger"
[text]="true"
size="small"
(onClick)="clearAllEntries()"
/>
</div>
</div>
<div class="queue-grid">
@for (entry of svgEntries; track entry.name; let i = $index) {
<div class="queue-item" [class.has-error]="entry.error">
<div class="queue-item-header">
<span class="queue-item-name">{{ entry.name }}</span>
<button class="queue-item-remove" (click)="removeSvgEntry(i)" type="button">
<i class="pi pi-times"></i>
</button>
</div>
<div class="queue-item-preview" [innerHTML]="entry.preview"></div>
@if (entry.error) {
<div class="queue-item-error">{{ entry.error }}</div>
}
</div>
}
</div>
@if (batchErrorMessage) {
<div class="error-message">
<i class="pi pi-exclamation-circle"></i>
<span>{{ batchErrorMessage }}</span>
</div>
}
<div class="form-actions">
<p-button
label="Save All Icons"
icon="pi pi-save"
severity="success"
[loading]="isSavingBatch"
[disabled]="svgEntries.length === 0"
(onClick)="saveAllSvgs()"
/>
</div>
</section>
}
</div>
</p-tabpanel>
}
</p-tabpanels>
</p-tabs>
</div>
</div>
@@ -0,0 +1,550 @@
.icon-picker {
display: flex;
flex-direction: column;
height: 80dvh;
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 12px;
overflow: hidden;
}
// Header
.dialog-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.25rem 1.5rem;
background: var(--overlay-background);
border-bottom: 1px solid var(--border-color);
flex-shrink: 0;
.header-content {
display: flex;
align-items: center;
gap: 0.875rem;
}
.header-icon {
display: flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
background: var(--primary-color);
border-radius: 10px;
i {
font-size: 1.25rem;
color: var(--primary-contrast-color);
}
}
.header-text {
h1 {
margin: 0;
font-size: 1.25rem;
font-weight: 600;
color: var(--text-color);
}
p {
margin: 0.125rem 0 0;
font-size: 0.875rem;
color: var(--text-secondary-color);
}
}
}
// Body
.dialog-body {
flex: 1;
overflow: hidden;
display: flex;
flex-direction: column;
min-height: 0;
::ng-deep {
.p-tabs {
display: flex;
flex-direction: column;
height: 100%;
}
.p-tablist {
background: var(--overlay-background);
border-bottom: 1px solid var(--border-color);
padding: 0 1rem;
}
.p-tab {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.875rem 1rem;
font-size: 0.875rem;
font-weight: 500;
i {
font-size: 0.9rem;
}
}
.p-tabpanels {
flex: 1;
overflow: hidden;
min-height: 0;
}
.p-tabpanel {
height: 100%;
padding: 0;
}
}
}
// Tab content
.tab-content {
display: flex;
flex-direction: column;
height: 100%;
padding: 1.25rem 1.5rem;
overflow-y: auto;
gap: 1.25rem;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
&:hover {
background: var(--primary-color);
}
}
}
// Search
.search-container {
position: relative;
flex-shrink: 0;
.search-icon {
position: absolute;
left: 0.875rem;
top: 50%;
transform: translateY(-50%);
font-size: 0.9rem;
color: var(--text-secondary-color);
pointer-events: none;
z-index: 1;
}
.search-input {
width: 100%;
padding: 0.75rem 1rem 0.75rem 2.5rem;
}
}
// Icon grid
.icon-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(44px, 1fr));
gap: 0.5rem;
flex: 1;
align-content: start;
}
.icon-item {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
background: var(--ground-background);
border: 1px solid transparent;
border-radius: 8px;
cursor: pointer;
transition: all 0.15s ease;
> i {
font-size: 1.25rem;
color: var(--text-color);
transition: color 0.15s ease;
}
&:hover {
border-color: var(--border-color);
background: var(--overlay-background);
> i {
color: var(--primary-color);
}
}
&.selected {
border-color: var(--primary-color);
background: rgba(var(--primary-color-rgb, 59, 130, 246), 0.1);
> i {
color: var(--primary-color);
}
}
&.svg-icon-item {
.svg-icon-inline {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
::ng-deep svg {
width: 100%;
height: 100%;
}
}
}
}
// States
.loading-state,
.error-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.75rem;
padding: 3rem;
color: var(--text-secondary-color);
font-size: 0.9rem;
i {
font-size: 1.5rem;
}
}
.error-state {
color: var(--p-red-400);
}
// Trash zone
.trash-zone-container {
position: sticky;
bottom: 0;
padding-top: 1rem;
margin-top: auto;
}
.trash-zone {
display: flex;
align-items: center;
justify-content: center;
gap: 0.625rem;
padding: 0.875rem 1.25rem;
background: var(--ground-background);
border: 2px dashed var(--border-color);
border-radius: 8px;
color: var(--text-secondary-color);
font-size: 0.875rem;
transition: all 0.2s ease;
i {
font-size: 1rem;
color: var(--p-red-400);
}
&.active {
border-color: var(--p-red-400);
background: rgba(239, 68, 68, 0.08);
color: var(--p-red-400);
}
}
// Form sections
.form-section {
background: var(--ground-background);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 1.25rem;
.section-header {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 1rem;
font-size: 0.85rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
color: var(--text-secondary-color);
> i {
font-size: 0.9rem;
color: var(--primary-color);
}
.section-badge {
display: flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
padding: 0 0.375rem;
background: var(--primary-color);
color: var(--primary-contrast-color);
border-radius: 10px;
font-size: 0.7rem;
font-weight: 600;
}
.section-actions {
margin-left: auto;
}
}
&.queue-section {
margin-top: 1rem;
}
}
// Form fields
.form-fields {
display: flex;
flex-direction: column;
gap: 1rem;
}
.form-field {
display: flex;
flex-direction: column;
gap: 0.5rem;
label {
font-size: 0.875rem;
font-weight: 500;
color: var(--text-color);
}
.input-full {
width: 100%;
padding: 0.75rem 1rem;
}
.code-textarea {
width: 100%;
padding: 0.75rem 1rem;
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
font-size: 0.875rem;
resize: vertical;
line-height: 1.5;
}
}
// Preview
.preview-card {
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 8px;
overflow: hidden;
.preview-label {
padding: 0.5rem 0.75rem;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
color: var(--text-secondary-color);
background: var(--overlay-background);
border-bottom: 1px solid var(--border-color);
}
.preview-content {
display: flex;
align-items: center;
justify-content: center;
padding: 1.5rem;
min-height: 120px;
::ng-deep svg {
max-width: 100%;
max-height: 100px;
width: auto;
height: auto;
}
}
}
// Error message
.error-message {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1rem;
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.2);
border-radius: 6px;
color: var(--p-red-400);
font-size: 0.875rem;
font-weight: 500;
i {
font-size: 0.9rem;
}
}
// Form actions
.form-actions {
display: flex;
justify-content: flex-end;
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--border-color);
}
// Queue grid
.queue-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
gap: 0.75rem;
max-height: 280px;
overflow-y: auto;
padding: 0.25rem;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 2px;
}
}
.queue-item {
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 8px;
overflow: hidden;
transition: all 0.2s ease;
&:hover {
border-color: var(--primary-color);
}
&.has-error {
border-color: var(--p-red-400);
}
.queue-item-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem 0.625rem;
background: var(--overlay-background);
border-bottom: 1px solid var(--border-color);
}
.queue-item-name {
font-size: 0.75rem;
font-weight: 600;
color: var(--text-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.queue-item-remove {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
background: transparent;
border: none;
border-radius: 4px;
color: var(--text-secondary-color);
cursor: pointer;
transition: all 0.15s ease;
&:hover {
background: rgba(239, 68, 68, 0.15);
color: var(--p-red-400);
}
i {
font-size: 0.625rem;
}
}
.queue-item-preview {
display: flex;
align-items: center;
justify-content: center;
padding: 0.75rem;
min-height: 60px;
::ng-deep svg {
max-width: 48px;
max-height: 48px;
width: auto;
height: auto;
}
}
.queue-item-error {
padding: 0.5rem 0.625rem;
font-size: 0.6875rem;
color: var(--p-red-400);
background: rgba(239, 68, 68, 0.08);
border-top: 1px solid rgba(239, 68, 68, 0.15);
}
}
// Responsive
@media (max-width: 520px) {
.icon-picker {
border-radius: 0;
height: 100dvh;
}
.dialog-header {
padding: 1rem;
.header-icon {
width: 36px;
height: 36px;
i {
font-size: 1rem;
}
}
.header-text h1 {
font-size: 1.125rem;
}
}
.tab-content {
padding: 1rem;
}
.icon-grid {
grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
gap: 0.375rem;
}
.icon-item {
width: 40px;
height: 40px;
}
.queue-grid {
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
}
}
@@ -0,0 +1,396 @@
import {Component, inject, OnInit} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {IconService} from '../../services/icon.service';
import {IconCacheService} from '../../services/icon-cache.service';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
import DOMPurify from 'dompurify';
import {UrlHelperService} from '../../service/url-helper.service';
import {MessageService} from 'primeng/api';
import {IconCategoriesHelper} from '../../helpers/icon-categories.helper';
import {Button} from 'primeng/button';
import {TabsModule} from 'primeng/tabs';
import {UserService} from '../../../features/settings/user-management/user.service';
import {from, of} from 'rxjs';
import {catchError, mergeMap, toArray} from 'rxjs/operators';
interface SvgEntry {
name: string;
content: string;
preview: SafeHtml | null;
error: string;
}
interface IconSaveResult {
iconName: string;
success: boolean;
errorMessage: string;
}
interface SvgIconBatchResponse {
totalRequested: number;
successCount: number;
failureCount: number;
results: IconSaveResult[];
}
@Component({
selector: 'app-icon-picker-component',
imports: [
FormsModule,
Button,
TabsModule
],
templateUrl: './icon-picker-component.html',
styleUrl: './icon-picker-component.scss'
})
export class IconPickerComponent implements OnInit {
private hasLoadedSvgIcons = false;
private readonly MAX_ICON_NAME_LENGTH = 255;
private readonly MAX_SVG_SIZE = 1048576; // 1MB
private readonly ICON_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
private readonly ERROR_MESSAGES = {
NO_CONTENT: 'Please paste SVG content',
NO_NAME: 'Please provide a name for the icon',
INVALID_NAME: 'Icon name can only contain alphanumeric characters and hyphens',
NAME_TOO_LONG: `Icon name must not exceed ${this.MAX_ICON_NAME_LENGTH} characters`,
INVALID_SVG: 'Invalid SVG content. Please paste valid SVG code.',
MISSING_SVG_TAG: 'Content must include <svg> tag',
SVG_TOO_LARGE: 'SVG content must not exceed 1MB',
PARSE_ERROR: 'Failed to parse SVG content',
LOAD_ICONS_ERROR: 'Failed to load SVG icons. Please try again.',
DELETE_ERROR: 'Failed to delete icon. Please try again.'
};
ref = inject(DynamicDialogRef);
iconService = inject(IconService);
iconCache = inject(IconCacheService);
sanitizer = inject(DomSanitizer);
urlHelper = inject(UrlHelperService);
messageService = inject(MessageService);
userService = inject(UserService);
searchText: string = '';
selectedIcon: string | null = null;
icons: string[] = IconCategoriesHelper.createIconList();
private _activeTabIndex: string = '0';
get activeTabIndex(): string {
return this._activeTabIndex;
}
set activeTabIndex(value: string) {
this._activeTabIndex = value;
if (value === '1' && !this.hasLoadedSvgIcons && !this.isLoadingSvgIcons) {
this.loadSvgIcons();
}
}
svgContent: string = '';
svgName: string = '';
svgPreview: SafeHtml | null = null;
errorMessage: string = '';
svgEntries: SvgEntry[] = [];
isSavingBatch: boolean = false;
batchErrorMessage: string = '';
svgIcons: string[] = [];
svgSearchText: string = '';
isLoadingSvgIcons: boolean = false;
svgIconsError: string = '';
selectedSvgIcon: string | null = null;
draggedSvgIcon: string | null = null;
isTrashHover: boolean = false;
get canManageIcons(): boolean {
const user = this.userService.getCurrentUser();
return user?.permissions.canManageIcons || user?.permissions.admin || false;
}
ngOnInit(): void {
if (this.activeTabIndex === '1' && !this.hasLoadedSvgIcons && !this.isLoadingSvgIcons) {
this.loadSvgIcons();
}
}
filteredIcons(): string[] {
if (!this.searchText) return this.icons;
return this.icons.filter(icon => icon.toLowerCase().includes(this.searchText.toLowerCase()));
}
filteredSvgIcons(): string[] {
if (!this.svgSearchText) return this.svgIcons;
return this.svgIcons.filter(icon => icon.toLowerCase().includes(this.svgSearchText.toLowerCase()));
}
selectIcon(icon: string): void {
this.selectedIcon = icon;
this.ref.close({type: 'PRIME_NG', value: icon});
}
private loadSvgIcons(): void {
this.isLoadingSvgIcons = true;
this.svgIconsError = '';
this.iconService.getIconNames().subscribe({
next: (names) => {
this.hasLoadedSvgIcons = true;
if (names.length === 0) {
this.svgIcons = [];
this.isLoadingSvgIcons = false;
return;
}
from(names).pipe(
mergeMap(name =>
this.iconCache.getCachedSanitized(name)
? of(null)
: this.iconService.getSvgIconContent(name).pipe(catchError(() => of(null))),
5
),
toArray()
).subscribe(() => {
this.svgIcons = names;
this.isLoadingSvgIcons = false;
});
},
error: () => {
this.isLoadingSvgIcons = false;
this.hasLoadedSvgIcons = false;
this.svgIconsError = this.ERROR_MESSAGES.LOAD_ICONS_ERROR;
}
});
}
getSvgContent(iconName: string): SafeHtml | null {
return this.iconCache.getCachedSanitized(iconName) || null;
}
selectSvgIcon(iconName: string): void {
this.selectedSvgIcon = iconName;
this.ref.close({type: 'CUSTOM_SVG', value: iconName});
}
onSvgContentChange(): void {
this.errorMessage = '';
if (!this.svgContent.trim()) {
this.svgPreview = null;
return;
}
const trimmedContent = this.svgContent.trim();
if (!trimmedContent.includes('<svg')) {
this.svgPreview = null;
this.errorMessage = this.ERROR_MESSAGES.MISSING_SVG_TAG;
return;
}
try {
const sanitized = DOMPurify.sanitize(this.svgContent, {
USE_PROFILES: { svg: true },
FORBID_TAGS: ['script', 'style', 'foreignObject']
});
this.svgPreview = this.sanitizer.bypassSecurityTrustHtml(sanitized);
} catch {
this.svgPreview = null;
this.errorMessage = this.ERROR_MESSAGES.PARSE_ERROR;
}
}
addSvgEntry(): void {
const validationError = this.validateSvgInput();
if (validationError) {
this.errorMessage = validationError;
return;
}
const existingIndex = this.svgEntries.findIndex(entry => entry.name === this.svgName);
if (existingIndex !== -1) {
this.svgEntries[existingIndex] = {
name: this.svgName,
content: this.svgContent,
preview: this.svgPreview,
error: ''
};
} else {
this.svgEntries.push({
name: this.svgName,
content: this.svgContent,
preview: this.svgPreview,
error: ''
});
}
this.resetSvgForm();
this.errorMessage = '';
}
removeSvgEntry(index: number): void {
this.svgEntries.splice(index, 1);
}
clearAllEntries(): void {
this.svgEntries = [];
this.batchErrorMessage = '';
}
saveAllSvgs(): void {
if (this.svgEntries.length === 0) {
this.batchErrorMessage = 'No SVG icons to save';
return;
}
this.isSavingBatch = true;
this.batchErrorMessage = '';
this.svgEntries.forEach(entry => entry.error = '');
const svgData = this.svgEntries.map(entry => ({
svgName: entry.name,
svgData: entry.content
}));
this.iconService.saveBatchSvgIcons(svgData).subscribe({
next: (response: SvgIconBatchResponse) => {
this.isSavingBatch = false;
let successCount = 0;
let failureCount = 0;
response.results.forEach(result => {
if (result.success) {
successCount++;
} else {
failureCount++;
const entry = this.svgEntries.find(e => e.name === result.iconName);
if (entry) {
entry.error = result.errorMessage;
}
}
});
if (successCount > 0 && failureCount === 0) {
this.messageService.add({
severity: 'success',
summary: 'Icons Saved',
detail: `${successCount} SVG icon${successCount > 1 ? 's' : ''} saved successfully.`,
life: 2500
});
} else if (successCount > 0 && failureCount > 0) {
this.messageService.add({
severity: 'warn',
summary: 'Partial Success',
detail: `${successCount} SVG icon${successCount > 1 ? 's' : ''} saved, ${failureCount} failed.`,
life: 3500
});
} else if (failureCount > 0) {
this.messageService.add({
severity: 'error',
summary: 'Save Failed',
detail: `Failed to save ${failureCount} SVG icon${failureCount > 1 ? 's' : ''}.`,
life: 4000
});
}
this.clearAllEntries();
this.hasLoadedSvgIcons = false;
this.loadSvgIcons();
},
error: () => {
this.isSavingBatch = false;
this.batchErrorMessage = 'Failed to save SVG icons. Please try again.';
}
});
}
private deleteSvgIcon(iconName: string): void {
this.isLoadingSvgIcons = true;
this.iconService.deleteSvgIcon(iconName).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Icon Deleted',
detail: 'SVG icon deleted successfully.',
life: 2500
});
this.svgIcons = this.svgIcons.filter(name => name !== iconName);
this.isLoadingSvgIcons = false;
},
error: (error) => {
this.isLoadingSvgIcons = false;
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: error.error?.message || this.ERROR_MESSAGES.DELETE_ERROR,
life: 4000
});
}
});
}
private validateSvgInput(): string | null {
if (!this.svgContent.trim()) {
return this.ERROR_MESSAGES.NO_CONTENT;
}
if (!this.svgName.trim()) {
return this.ERROR_MESSAGES.NO_NAME;
}
if (this.svgName.length > this.MAX_ICON_NAME_LENGTH) {
return this.ERROR_MESSAGES.NAME_TOO_LONG;
}
if (!this.ICON_NAME_PATTERN.test(this.svgName)) {
return this.ERROR_MESSAGES.INVALID_NAME;
}
const svgSize = new Blob([this.svgContent]).size;
if (svgSize > this.MAX_SVG_SIZE) {
return this.ERROR_MESSAGES.SVG_TOO_LARGE;
}
return null;
}
private resetSvgForm(): void {
this.svgContent = '';
this.svgName = '';
this.svgPreview = null;
this.errorMessage = '';
}
onSvgIconDragStart(iconName: string): void {
this.draggedSvgIcon = iconName;
}
onSvgIconDragEnd(): void {
this.draggedSvgIcon = null;
}
onTrashDragOver(event: DragEvent): void {
event.preventDefault();
this.isTrashHover = true;
}
onTrashDragLeave(event: DragEvent): void {
event.preventDefault();
this.isTrashHover = false;
}
onTrashDrop(event: DragEvent): void {
event.preventDefault();
this.isTrashHover = false;
if (this.draggedSvgIcon) {
this.deleteSvgIcon(this.draggedSvgIcon);
this.draggedSvgIcon = null;
}
}
}
@@ -0,0 +1,11 @@
<div class="notification-container live-border">
<div class="notification-header">
@if (latestNotification.severity) {
<app-tag [color]="getSeverityColor(latestNotification.severity)" size="3xs" class="tag-centered">
{{ latestNotification.severity }}
</app-tag>
}
<span class="notification-timestamp">{{ latestNotification.timestamp }}</span>
</div>
<p class="notification-message">{{ latestNotification.message }}</p>
</div>
@@ -0,0 +1,35 @@
.live-border {
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
.notification-container {
display: flex;
flex-direction: column;
padding: 1rem;
gap: 0.5rem;
}
.notification-header {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.5rem;
}
.tag-centered {
align-self: center;
}
.notification-timestamp {
font-size: 0.75rem;
color: #a1a1aa;
align-self: center;
}
.notification-message {
font-weight: 400;
color: #e4e4e7;
margin: 0;
}
@@ -0,0 +1,60 @@
import {Component, inject, OnDestroy} from '@angular/core';
import {NotificationEventService} from '../../websocket/notification-event.service';
import {LogNotification} from '../../websocket/model/log-notification.model';
import {Tag} from 'primeng/tag';
import {TranslocoService} from '@jsverse/transloco';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {TagComponent} from '../tag/tag.component';
@Component({
selector: 'app-live-notification-box',
standalone: true,
templateUrl: './live-notification-box.component.html',
styleUrls: ['./live-notification-box.component.scss'],
host: {
class: 'config-panel'
},
imports: [
TagComponent
]
})
export class LiveNotificationBoxComponent implements OnDestroy {
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
latestNotification: LogNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')};
private hasReceivedNotification = false;
private notificationService = inject(NotificationEventService);
constructor() {
this.notificationService.latestNotification$.pipe(takeUntil(this.destroy$)).subscribe(notification => {
this.hasReceivedNotification = true;
this.latestNotification = notification;
});
this.t.langChanges$.pipe(takeUntil(this.destroy$)).subscribe(() => {
if (!this.hasReceivedNotification) {
this.latestNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')};
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
getSeverityColor(severity?: string): 'red' | 'amber' | 'green' | 'gray' {
switch (severity) {
case 'ERROR':
return 'red';
case 'WARN':
return 'amber';
case 'INFO':
return 'green';
default:
return 'gray';
}
}
}
@@ -0,0 +1,112 @@
<ng-container *transloco="let t; prefix: 'auth.login'">
<div class="login-container">
<div class="login-card-wrapper">
<div class="login-card-border">
<div class="login-card">
<div class="login-header">
<div class="logo-wrapper">
<svg class="logo-icon" viewBox="0 0 126 126" fill="var(--primary-color)" xmlns="http://www.w3.org/2000/svg">
<path
d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z"/>
<path
d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z"
fill="white"/>
</svg>
</div>
<h1 class="login-title">{{ t('title') }}</h1>
<p class="login-subtitle">{{ t('subtitle') }}</p>
</div>
@if (infoMessage) {
<div class="info-message" style="margin-bottom: 1rem;">
<p-message severity="info">{{ infoMessage }}</p-message>
</div>
}
@if (errorMessage) {
<div class="error-message" style="margin-bottom: 1rem;">
<p-message severity="error">{{ errorMessage }}</p-message>
</div>
}
@if (showLocalLogin) {
<form class="login-form" #loginForm="ngForm" (ngSubmit)="login()">
<div class="form-field">
<label for="username" class="form-label">
<i class="pi pi-user"></i>
<span>{{ t('usernameLabel') }}</span>
</label>
<input
fluid
pInputText
id="username"
name="username"
required
[(ngModel)]="username"
[placeholder]="t('usernamePlaceholder')"
class="form-input"
autocomplete="username"
/>
</div>
<div class="form-field">
<label for="password" class="form-label">
<i class="pi pi-lock"></i>
<span>{{ t('passwordLabel') }}</span>
</label>
<p-password
id="password"
name="password"
required
[(ngModel)]="password"
[feedback]="false"
[placeholder]="t('passwordPlaceholder')"
[toggleMask]="true"
[fluid]="true"
autocomplete="current-password"
></p-password>
</div>
<p-button
fluid
type="submit"
[label]="t('signIn')"
icon="pi pi-sign-in"
[disabled]="!loginForm.valid || !username || !password"
class="login-button">
</p-button>
@if (oidcEnabled) {
<div class="divider">
<span>{{ t('orContinueWith') }}</span>
</div>
<p-button
fluid
severity="secondary"
[label]="isOidcLoginInProgress ? t('redirectingTo', {provider: oidcName}) : oidcName"
[icon]="isOidcLoginInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-id-card'"
[disabled]="isOidcLoginInProgress"
(click)="loginWithOidc()"
class="oidc-button"/>
}
</form>
} @else {
@if (oidcEnabled) {
<div class="login-form">
<p-button
fluid
severity="secondary"
[label]="isOidcLoginInProgress ? t('redirectingTo', {provider: oidcName}) : oidcName"
[icon]="isOidcLoginInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-id-card'"
[disabled]="isOidcLoginInProgress"
(click)="loginWithOidc()"
class="oidc-button"/>
</div>
}
}
</div>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,169 @@
@use '../../styles/auth-shared' as auth;
.login-container {
@include auth.auth-container;
}
.login-card-wrapper {
@include auth.auth-card-wrapper(460px, -8rem);
}
.login-card-border {
@include auth.auth-card-border;
}
.login-card {
@include auth.auth-card;
}
.login-header {
@include auth.auth-header;
}
.logo-wrapper {
@include auth.auth-logo;
}
.logo-icon {
@include auth.auth-logo-icon;
}
.login-title {
@include auth.auth-title;
}
.login-subtitle {
@include auth.auth-subtitle;
font-size: 1rem;
}
.oidc-warning {
margin-bottom: 1.5rem;
padding: 1rem;
border-radius: 0.75rem;
background: rgba(245, 158, 11, 0.1);
border: 1px solid rgba(245, 158, 11, 0.3);
animation: fadeIn 0.3s ease-out;
}
.warning-content {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.warning-header {
display: flex;
align-items: center;
gap: 0.5rem;
color: #fbbf24;
font-size: 0.875rem;
font-weight: 600;
i {
font-size: 1rem;
}
}
.warning-message {
font-size: 0.875rem;
color: #fcd34d;
line-height: 1.5;
margin: 0;
}
.warning-actions {
display: flex;
gap: 0.75rem;
justify-content: center;
}
.login-form {
@include auth.auth-form(1.5rem);
}
.form-field {
@include auth.form-field;
}
.form-label {
@include auth.form-label;
}
.form-input {
@include auth.form-input;
}
.login-button {
@include auth.auth-button;
margin-top: 0.5rem;
}
.error-message {
@include auth.error-message;
}
.divider {
display: flex;
align-items: center;
text-align: center;
margin: 1.5rem 0;
&::before,
&::after {
content: '';
flex: 1;
border-bottom: 1px solid rgba(255, 255, 255, 0.15);
}
span {
padding: 0 1rem;
font-size: 0.875rem;
color: rgba(255, 255, 255, 0.5);
font-weight: 500;
}
}
.oidc-button {
::ng-deep button {
height: 2.75rem;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.15);
color: rgba(255, 255, 255, 0.9);
transition: all 0.3s ease;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.1);
border-color: rgba(255, 255, 255, 0.25);
transform: translateY(-1px);
}
}
}
.help-text {
text-align: center;
margin-top: 0.5rem;
}
.text-link {
background: none;
border: none;
font-size: 0.8rem;
color: rgba(255, 255, 255, 0.5);
text-decoration: underline;
cursor: pointer;
transition: color 0.2s ease;
padding: 0;
&:hover {
color: rgba(255, 255, 255, 0.8);
}
&.primary {
color: var(--primary-color);
&:hover {
color: #60a5fa;
}
}
}
@@ -0,0 +1,190 @@
import {Component, effect, inject, OnInit} from '@angular/core';
import {AuthService} from '../../service/auth.service';
import {ActivatedRoute, Router} from '@angular/router';
import {FormsModule} from '@angular/forms';
import {Password} from 'primeng/password';
import {Button} from 'primeng/button';
import {Message} from 'primeng/message';
import {InputText} from 'primeng/inputtext';
import {take} from 'rxjs/operators';
import {AppSettingsService} from '../../service/app-settings.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {OidcService} from '../../../core/security/oidc.service';
@Component({
selector: 'app-login',
imports: [
FormsModule,
Password,
Button,
Message,
InputText,
TranslocoDirective
],
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
username = '';
password = '';
errorMessage = '';
infoMessage = '';
oidcEnabled = false;
oidcName = 'OIDC';
isOidcLoginInProgress = false;
showLocalLogin = true;
private oidcOnlyAutoRedirect = false;
private authService = inject(AuthService);
private oidcService = inject(OidcService);
private appSettingsService = inject(AppSettingsService);
private router = inject(Router);
private route = inject(ActivatedRoute);
private translocoService = inject(TranslocoService);
private readonly initPublicSettingsEffect = effect(() => {
const publicSettings = this.appSettingsService.publicAppSettings();
if (!publicSettings) return;
this.oidcEnabled = publicSettings.oidcEnabled;
this.oidcName = publicSettings.oidcProviderDetails?.providerName || 'OIDC';
if (publicSettings.oidcForceOnlyMode) {
this.route.queryParams.pipe(take(1)).subscribe(params => {
const isLocalMode = params['local'] === 'true';
const hasOidcError = !!params['oidcError'];
if (!isLocalMode && !hasOidcError) {
this.handleAutoRedirect();
}
});
}
});
private static readonly OIDC_ERROR_KEYS: Record<string, string> = {
'state_mismatch': 'auth.login.oidcErrors.stateMismatch',
'missing_code': 'auth.login.oidcErrors.stateMismatch',
'exchange_failed': 'auth.login.oidcErrors.exchangeFailed'
};
private static readonly MAX_REDIRECT_COUNT = 3;
ngOnInit(): void {
this.authService.clearSessionOnLoginPage();
this.route.queryParams.pipe(take(1)).subscribe(params => {
if (params['reason'] === 'session_revoked') {
this.infoMessage = this.translocoService.translate('auth.login.sessionRevoked');
}
const oidcError = params['oidcError'];
if (oidcError) {
this.errorMessage = this.resolveOidcError(oidcError);
}
});
}
private handleAutoRedirect(): void {
const countStr = sessionStorage.getItem('oidc_redirect_count');
const count = countStr ? parseInt(countStr, 10) : 0;
if (count >= LoginComponent.MAX_REDIRECT_COUNT) {
sessionStorage.removeItem('oidc_redirect_count');
this.errorMessage = this.translocoService.translate('auth.login.oidcOnlyRedirectFailed');
this.showLocalLogin = false;
return;
}
this.oidcOnlyAutoRedirect = true;
sessionStorage.setItem('oidc_redirect_count', String(count + 1));
this.showLocalLogin = false;
this.loginWithOidc();
}
private resolveOidcError(error: string): string {
if (error.startsWith('OIDC user')) {
return this.translocoService.translate('auth.login.oidcErrors.userNotProvisioned');
}
if (error.startsWith('Cannot reach')) {
return this.translocoService.translate('auth.login.oidcErrors.providerUnreachable');
}
if (error.startsWith('Invalid token') || error.startsWith('No token')) {
return this.translocoService.translate('auth.login.oidcErrors.invalidToken');
}
if (error.startsWith('Failed to exchange') || error.includes('token exchange')) {
return this.translocoService.translate('auth.login.oidcErrors.exchangeFailed');
}
const key = LoginComponent.OIDC_ERROR_KEYS[error];
if (key) {
return this.translocoService.translate(key);
}
return this.translocoService.translate('auth.login.oidcErrors.unknown');
}
login(): void {
this.authService.internalLogin({username: this.username, password: this.password}).subscribe({
next: (response) => {
if (response.isDefaultPassword === 'true') {
this.router.navigate(['/change-password']);
} else {
this.router.navigate(['/dashboard']);
}
},
error: (error) => {
if (error.status === 0) {
this.errorMessage = this.translocoService.translate('auth.login.connectionError');
} else if (error.status === 429) {
this.errorMessage = this.translocoService.translate('auth.login.rateLimited');
} else {
this.errorMessage = error?.error?.message || this.translocoService.translate('auth.login.unexpectedError');
}
}
});
}
async loginWithOidc(): Promise<void> {
if (this.isOidcLoginInProgress) {
return;
}
this.isOidcLoginInProgress = true;
this.errorMessage = '';
try {
const publicSettings = this.appSettingsService.publicAppSettings();
if (!publicSettings?.oidcProviderDetails) {
this.errorMessage = this.translocoService.translate('auth.login.oidcInitError');
this.isOidcLoginInProgress = false;
return;
}
const details = publicSettings.oidcProviderDetails;
const pkce = await this.oidcService.generatePkce();
const state = await this.oidcService.fetchState();
const nonce = this.oidcService.generateRandomString();
this.oidcService.storePkceState({codeVerifier: pkce.codeVerifier, state, nonce});
const authUrl = await this.oidcService.buildAuthUrl(
details.issuerUri,
details.clientId,
pkce.codeChallenge,
state,
nonce,
undefined,
details.scopes
);
window.location.href = authUrl;
} catch (error) {
console.error('OIDC login initiation failed:', error);
sessionStorage.removeItem('oidc_redirect_count');
this.errorMessage = this.translocoService.translate('auth.login.oidcErrors.providerUnreachable');
this.showLocalLogin = !this.oidcOnlyAutoRedirect;
this.isOidcLoginInProgress = false;
}
}
}
@@ -0,0 +1,93 @@
<ng-container *transloco="let t; prefix: 'shared.metadataProgress'">
<div class="task-border">
@if (Object.keys(activeTasks).length > 0) {
@for (task of activeTasks | keyvalue; track task; let idx = $index) {
<div class="task-card">
<div class="task-header-row">
<div class="task-title-group">
<p class="task-title">{{ t('taskTitle') }}</p>
</div>
<div class="task-tags">
@if (task.value.review) {
<p-tag
[value]="t('tagReview')"
severity="warn"
class="task-tag">
</p-tag>
} @else {
<p-tag
[value]="t('tagAuto')"
severity="success"
class="task-tag">
</p-tag>
}
<p-tag
[value]="getStatusLabel(task.value.status)"
[severity]="getTagSeverity(task.value.status)"
class="task-tag"
></p-tag>
</div>
</div>
<div class="task-message">
{{ task.value.message }}
</div>
<div class="task-progress-info" [innerHTML]="t('bookProgress', { current: task.value.status === 'COMPLETED' || task.value.completed >= task.value.total ? task.value.total : task.value.completed + 1, total: task.value.total })">
</div>
<p-progressBar
[style]="{ height: '15px' }"
[value]="getProgressPercent(task.value)"
[showValue]="true">
</p-progressBar>
@if (task.value.status === 'COMPLETED' || task.value.status === 'ERROR' || task.value.status === 'CANCELLED') {
<div class="action-buttons">
@if (task.value.review) {
<p-button
[label]="t('reviewBtn')"
severity="info"
icon="pi pi-search"
size="small"
outlined
(click)="reviewTask(task.key)">
</p-button>
}
<p-button
[label]="task.value.review ? t('discardBtn') : t('dismissBtn')"
icon="pi pi-times"
[severity]="task.value.review ? 'danger' : 'secondary'"
size="small"
[pTooltip]="task.value.review ? t('discardTooltip') : ''"
[tooltipPosition]="task.value.review ? 'top' : undefined"
outlined
(click)="clearTask(task.key)">
</p-button>
</div>
} @else if (task.value.status === 'IN_PROGRESS') {
<div class="action-buttons">
<p-button
[label]="t('cancelBtn')"
icon="pi pi-stop"
severity="danger"
size="small"
[pTooltip]="t('cancelTooltip')"
tooltipPosition="top"
outlined
(click)="cancelTask(task.key)">
</p-button>
</div>
}
</div>
@if (idx < Object.keys(activeTasks).length - 1) {
<p-divider></p-divider>
}
}
}
</div>
</ng-container>
@@ -0,0 +1,76 @@
.task-border {
margin-top: 1rem;
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
.task-card {
padding: 1rem;
}
.task-header-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.5rem;
}
.task-title-group {
display: flex;
align-items: center;
gap: 0.5rem;
}
.task-title {
font-size: 0.875rem;
font-weight: 600;
color: var(--primary-color);
margin: 0;
}
.task-tags {
display: flex;
align-items: center;
gap: 0.25rem;
}
:host ::ng-deep .task-tag {
font-size: 0.75rem;
}
.task-header {
display: flex;
justify-content: flex-end;
margin-bottom: 0.5rem;
}
.task-message {
font-size: 1rem;
color: #e5e7eb;
margin-bottom: 0.5rem;
}
.task-progress-info {
font-size: 0.875rem;
color: #d1d5db;
margin-bottom: 0.5rem;
}
.action-buttons {
margin-top: 1rem;
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
.review-button {
text-align: right;
margin-top: 0.75rem;
}
.review-indicator {
display: flex;
align-items: center;
gap: 0.5rem;
}
@@ -0,0 +1,176 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {KeyValuePipe} from '@angular/common';
import {ProgressBarModule} from 'primeng/progressbar';
import {ButtonModule} from 'primeng/button';
import {Divider} from 'primeng/divider';
import {Tooltip} from 'primeng/tooltip';
import {MessageService} from 'primeng/api';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../model/metadata-batch-progress.model';
import {MetadataProgressService} from '../../service/metadata-progress.service';
import {MetadataTaskService} from '../../../features/book/service/metadata-task';
import {Tag} from 'primeng/tag';
import {TaskService} from '../../../features/settings/task-management/task.service';
import {DialogLauncherService} from '../../services/dialog-launcher.service';
@Component({
selector: 'app-metadata-progress-widget',
templateUrl: './metadata-progress-widget-component.html',
styleUrls: ['./metadata-progress-widget-component.scss'],
standalone: true,
imports: [KeyValuePipe, ProgressBarModule, ButtonModule, Divider, Tooltip, Tag, TranslocoDirective]
})
export class MetadataProgressWidgetComponent implements OnInit, OnDestroy {
activeTasks: Record<string, MetadataBatchProgressNotification> = {};
private destroy$ = new Subject<void>();
private dialogLauncherService = inject(DialogLauncherService);
private metadataProgressService = inject(MetadataProgressService);
private metadataTaskService = inject(MetadataTaskService);
private taskService = inject(TaskService);
private messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private lastUpdateMap = new Map<string, number>();
private timeoutHandles = new Map<string, number>();
private readonly TASK_STALL_TIMEOUT_MS = 60 * 1000; // 1 minute
ngOnInit(): void {
this.metadataProgressService.activeTasks$
.pipe(takeUntil(this.destroy$))
.subscribe(tasks => {
this.activeTasks = tasks;
this.checkForStalledTasks(tasks);
});
}
private checkForStalledTasks(tasks: Record<string, MetadataBatchProgressNotification>): void {
const now = Date.now();
for (const taskId of this.timeoutHandles.keys()) {
if (!tasks[taskId]) {
clearTimeout(this.timeoutHandles.get(taskId));
this.timeoutHandles.delete(taskId);
this.lastUpdateMap.delete(taskId);
}
}
for (const [taskId, task] of Object.entries(tasks)) {
this.lastUpdateMap.set(taskId, now);
if (this.timeoutHandles.has(taskId)) {
clearTimeout(this.timeoutHandles.get(taskId));
}
this.timeoutHandles.set(
taskId,
setTimeout(() => {
this.markTaskStalled(taskId);
}, this.TASK_STALL_TIMEOUT_MS) as any
);
}
}
private markTaskStalled(taskId: string): void {
const task = this.activeTasks[taskId];
if (!task) return;
if (task.status !== MetadataBatchStatus.COMPLETED && task.status !== 'ERROR') {
this.activeTasks[taskId] = {
...task,
status: MetadataBatchStatus.ERROR,
message: this.t.translate('shared.metadataProgress.taskStalled')
};
this.activeTasks = {...this.activeTasks};
}
}
getProgressPercent(task: MetadataBatchProgressNotification): number {
if (task.total <= 0) return 0;
if (task.status === 'COMPLETED') return 100;
return Math.round((task.completed / task.total) * 100);
}
clearTask(taskId: string): void {
this.metadataTaskService.deleteTask(taskId).subscribe(() => {
this.metadataProgressService.clearTask(taskId);
clearTimeout(this.timeoutHandles.get(taskId));
this.timeoutHandles.delete(taskId);
this.lastUpdateMap.delete(taskId);
});
}
reviewTask(taskId: string): void {
this.dialogLauncherService.openMetadataReviewDialog(taskId);
}
cancelTask(taskId: string): void {
this.taskService.cancelTask(taskId).subscribe({
next: () => {
const task = this.activeTasks[taskId];
if (task) {
this.activeTasks[taskId] = {
...task,
status: MetadataBatchStatus.CANCELLED,
message: this.t.translate('shared.metadataProgress.taskCancelled')
};
this.activeTasks = {...this.activeTasks};
}
this.messageService.add({
severity: 'success',
summary: this.t.translate('shared.metadataProgress.cancellationScheduledSummary'),
detail: this.t.translate('shared.metadataProgress.cancellationScheduledDetail')
});
},
error: (error) => {
console.error('Failed to cancel task:', error);
this.messageService.add({
severity: 'error',
summary: this.t.translate('shared.metadataProgress.cancelFailedSummary'),
detail: this.t.translate('shared.metadataProgress.cancelFailedDetail')
});
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
for (const timeout of this.timeoutHandles.values()) {
clearTimeout(timeout);
}
this.timeoutHandles.clear();
this.lastUpdateMap.clear();
}
getTagSeverity(status: 'IN_PROGRESS' | 'COMPLETED' | 'ERROR' | 'CANCELLED'): 'info' | 'success' | 'danger' | 'warn' {
switch (status) {
case 'COMPLETED':
return 'success';
case 'ERROR':
return 'danger';
case 'CANCELLED':
return 'warn';
case 'IN_PROGRESS':
default:
return 'info';
}
}
private readonly statusLabelKeys: Record<MetadataBatchStatus, string> = {
[MetadataBatchStatus.IN_PROGRESS]: 'shared.metadataProgress.statusInProgress',
[MetadataBatchStatus.COMPLETED]: 'shared.metadataProgress.statusCompleted',
[MetadataBatchStatus.ERROR]: 'shared.metadataProgress.statusError',
[MetadataBatchStatus.CANCELLED]: 'shared.metadataProgress.statusCancelled',
};
getStatusLabel(status: MetadataBatchStatus): string {
const key = this.statusLabelKeys[status];
return key ? this.t.translate(key) : status;
}
protected readonly Object = Object;
}
@@ -0,0 +1,30 @@
import { inject, Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, map, catchError, of } from 'rxjs';
import { API_CONFIG } from '../../../core/config/api-config';
@Injectable({
providedIn: 'root',
})
export class LoginGuard implements CanActivate {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
private router = inject(Router);
canActivate(): Observable<boolean> {
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
map(res => {
if (!res.data) {
this.router.navigate(['/setup']);
return false;
}
return true;
}),
catchError(() => {
this.router.navigate(['/setup']);
return of(false);
})
);
}
}
@@ -0,0 +1,28 @@
import {inject, Injectable} from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import {API_CONFIG} from '../../../core/config/api-config';
@Injectable({
providedIn: 'root',
})
export class SetupRedirectGuard implements CanActivate {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
private router = inject(Router);
canActivate(): Observable<boolean> {
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
map(res => {
if (!res.data) {
this.router.navigate(['/setup']);
} else {
this.router.navigate(['/dashboard']);
}
return false;
})
);
}
}
@@ -0,0 +1,170 @@
<ng-container *transloco="let t; prefix: 'shared.setup'">
<div class="setup-container">
<div class="setup-card-wrapper">
<div class="setup-card-border">
<div class="setup-card">
<div class="setup-header">
<div class="logo-wrapper">
<svg class="logo-icon" viewBox="0 0 126 126" fill="var(--primary-color)" xmlns="http://www.w3.org/2000/svg">
<path
d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z"/>
<path
d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z"
fill="white"/>
</svg>
</div>
<h1 class="setup-title">{{ t('title') }}</h1>
<p class="setup-subtitle">{{ t('subtitle') }}</p>
</div>
<form class="setup-form" [formGroup]="setupForm" (ngSubmit)="onSubmit()">
<div class="form-field">
<label for="username" class="form-label">
<i class="pi pi-user"></i>
<span>{{ t('usernameLabel') }}</span>
</label>
<input
pInputText
id="username"
name="username"
required
formControlName="username"
[placeholder]="t('usernamePlaceholder')"
class="form-input"
autocomplete="username"
/>
@if (setupForm.get('username')?.invalid && setupForm.get('username')?.touched) {
<small class="field-error">
<i class="pi pi-exclamation-circle"></i>
{{ t('validation.usernameRequired') }}
</small>
}
</div>
<div class="form-field">
<label for="name" class="form-label">
<i class="pi pi-id-card"></i>
<span>{{ t('fullNameLabel') }}</span>
</label>
<input
pInputText
id="name"
name="name"
required
formControlName="name"
[placeholder]="t('fullNamePlaceholder')"
class="form-input"
autocomplete="name"
/>
@if (setupForm.get('name')?.invalid && setupForm.get('name')?.touched) {
<small class="field-error">
<i class="pi pi-exclamation-circle"></i>
{{ t('validation.nameRequired') }}
</small>
}
</div>
<div class="form-field">
<label for="email" class="form-label">
<i class="pi pi-envelope"></i>
<span>{{ t('emailLabel') }}</span>
</label>
<input
pInputText
id="email"
name="email"
type="email"
required
formControlName="email"
[placeholder]="t('emailPlaceholder')"
class="form-input"
autocomplete="email"
/>
@if (setupForm.get('email')?.invalid && setupForm.get('email')?.touched) {
<small class="field-error">
<i class="pi pi-exclamation-circle"></i>
{{ t('validation.emailRequired') }}
</small>
}
</div>
<div class="form-field">
<label for="password" class="form-label">
<i class="pi pi-lock"></i>
<span>{{ t('passwordLabel') }}</span>
</label>
<input
pInputText
id="password"
name="password"
type="password"
required
formControlName="password"
[placeholder]="t('passwordPlaceholder')"
class="form-input"
autocomplete="new-password"
/>
@if (setupForm.get('password')?.invalid && setupForm.get('password')?.touched) {
<small class="field-error">
<i class="pi pi-exclamation-circle"></i>
{{ t('validation.passwordMinLength') }}
</small>
}
</div>
<div class="form-field">
<label for="confirmPassword" class="form-label">
<i class="pi pi-lock"></i>
<span>{{ t('confirmPasswordLabel') }}</span>
</label>
<input
pInputText
id="confirmPassword"
name="confirmPassword"
type="password"
required
formControlName="confirmPassword"
[placeholder]="t('confirmPasswordPlaceholder')"
class="form-input"
autocomplete="new-password"
/>
@if (setupForm.get('confirmPassword')?.invalid && setupForm.get('confirmPassword')?.touched) {
<small class="field-error">
<i class="pi pi-exclamation-circle"></i>
{{ t('validation.confirmPasswordRequired') }}
</small>
}
@if (setupForm.get('confirmPassword')?.touched && setupForm.hasError('passwordMismatch')) {
<small class="field-error">
<i class="pi pi-exclamation-circle"></i>
{{ t('validation.passwordsMismatch') }}
</small>
}
</div>
<p-button
fluid
type="submit"
[label]="loading ? t('creatingAccountBtn') : t('createAccountBtn')"
[icon]="loading ? 'pi pi-spin pi-spinner' : 'pi pi-user-plus'"
[disabled]="loading || setupForm.invalid"
class="setup-button"
/>
@if (error) {
<div class="message-container error-message">
<p-message severity="error">{{ error }}</p-message>
</div>
}
@if (success) {
<div class="message-container success-message">
<p-message severity="success">{{ t('successMessage') }}</p-message>
</div>
}
</form>
</div>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,73 @@
@use '../../styles/auth-shared' as auth;
.setup-container {
@include auth.auth-container;
}
.setup-card-wrapper {
@include auth.auth-card-wrapper(540px, -6rem);
}
.setup-card-border {
@include auth.auth-card-border;
}
.setup-card {
@include auth.auth-card;
}
.setup-header {
@include auth.auth-header;
}
.logo-wrapper {
@include auth.auth-logo;
}
.logo-icon {
@include auth.auth-logo-icon;
}
.setup-title {
@include auth.auth-title;
}
.setup-subtitle {
@include auth.auth-subtitle;
}
.setup-form {
@include auth.auth-form;
}
.form-field {
@include auth.form-field;
}
.form-label {
@include auth.form-label;
}
.form-input {
@include auth.form-input;
}
.field-error {
@include auth.field-error;
}
.setup-button {
@include auth.auth-button;
}
.message-container {
@include auth.message-container;
}
.error-message {
@include auth.error-message;
}
.success-message {
@include auth.success-message;
}
@@ -0,0 +1,65 @@
import {Component, inject} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {SetupService} from './setup.service';
import {InputText} from 'primeng/inputtext';
import {Button} from 'primeng/button';
import {Message} from 'primeng/message';
import {passwordMatchValidator} from '../../validators/password-match.validator';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@Component({
selector: 'app-setup',
templateUrl: './setup.component.html',
styleUrls: ['./setup.component.scss'],
standalone: true,
imports: [
ReactiveFormsModule,
InputText,
Button,
Message,
TranslocoDirective
]
})
export class SetupComponent {
setupForm: FormGroup;
loading = false;
error: string | null = null;
success = false;
private readonly t = inject(TranslocoService);
constructor(
private fb: FormBuilder,
private setupService: SetupService,
private router: Router
) {
this.setupForm = this.fb.group({
name: ['', [Validators.required]],
username: ['', [Validators.required]],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
confirmPassword: ['', [Validators.required]],
}, {validators: [passwordMatchValidator('password', 'confirmPassword')]});
}
onSubmit(): void {
if (this.setupForm.invalid) return;
this.loading = true;
this.error = null;
// Remove confirm password from the payload, as it does not need to be sent to backend
const { confirmPassword, ...payload } = this.setupForm.value;
void confirmPassword;
this.setupService.createAdmin(payload).subscribe({
next: () => {
this.success = true;
setTimeout(() => this.router.navigate(['/login']), 1500);
},
error: (err) => {
this.loading = false;
this.error =
err?.error?.message || this.t.translate('shared.setup.toast.createFailedDefault');
},
});
}
}
@@ -0,0 +1,32 @@
import {inject, Injectable} from '@angular/core';
import {
CanActivate,
Router,
UrlTree
} from '@angular/router';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
import {API_CONFIG} from '../../../core/config/api-config';
@Injectable({
providedIn: 'root'
})
export class SetupGuard implements CanActivate {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
private router = inject(Router);
canActivate(): Observable<boolean | UrlTree> {
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
map(response => {
if (response?.data === true) {
return this.router.createUrlTree(['/login']);
}
return true;
})
);
}
}
@@ -0,0 +1,21 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../core/config/api-config';
export interface SetupPayload {
email: string;
password: string;
}
@Injectable({providedIn: 'root'})
export class SetupService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
createAdmin(payload: SetupPayload): Observable<void> {
return this.http.post<void>(this.url, payload);
}
}
@@ -0,0 +1,198 @@
.app-tag {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
padding: 0.1875rem 0.4375rem;
font-size: 0.875rem;
font-weight: 500;
line-height: 1.25rem;
border-radius: 0.375rem;
white-space: nowrap;
&-5xs {
padding: 0.09375rem 0.3125rem;
font-size: 0.625rem;
line-height: 0.875rem;
gap: 0.25rem;
}
&-4xs {
padding: 0.109375rem 0.328125rem;
font-size: 0.6875rem;
line-height: 0.9375rem;
gap: 0.28125rem;
}
&-3xs {
padding: 0.125rem 0.375rem;
font-size: 0.75rem;
line-height: 1rem;
gap: 0.3125rem;
}
&-2xs {
padding: 0.140625rem 0.390625rem;
font-size: 0.78125rem;
line-height: 1.0625rem;
gap: 0.328125rem;
}
&-xs {
padding: 0.15625rem 0.40625rem;
font-size: 0.8125rem;
line-height: 1.125rem;
gap: 0.34375rem;
}
&-s {
padding: 0.171875rem 0.421875rem;
font-size: 0.84375rem;
line-height: 1.1875rem;
gap: 0.359375rem;
}
&-m {
padding: 0.1875rem 0.4375rem;
font-size: 0.875rem;
line-height: 1.25rem;
gap: 0.375rem;
}
&-l {
padding: 0.203125rem 0.453125rem;
font-size: 0.90625rem;
line-height: 1.3125rem;
gap: 0.390625rem;
}
&-xl {
padding: 0.21875rem 0.46875rem;
font-size: 0.9375rem;
line-height: 1.375rem;
gap: 0.40625rem;
}
&-2xl {
padding: 0.234375rem 0.484375rem;
font-size: 0.96875rem;
line-height: 1.4375rem;
gap: 0.421875rem;
}
&-3xl {
padding: 0.25rem 0.5rem;
font-size: 1rem;
line-height: 1.5rem;
gap: 0.4375rem;
}
&-4xl {
padding: 0.28125rem 0.53125rem;
font-size: 1.0625rem;
line-height: 1.5625rem;
gap: 0.46875rem;
}
&-5xl {
padding: 0.3125rem 0.5625rem;
font-size: 1.125rem;
line-height: 1.625rem;
gap: 0.5rem;
}
&-rounded {
border-radius: 0.5rem;
}
&-pill {
border-radius: 9999px;
}
&-primary {
background-color: color-mix(in srgb, var(--p-primary-500), transparent 82%);
color: var(--p-primary-300);
border: 1px solid color-mix(in srgb, var(--p-primary-500), transparent 65%);
}
$colors: (
'secondary': 'slate',
'success': 'green',
'info': 'sky',
'warning': 'orange',
'danger': 'red',
'blue': 'blue',
'indigo': 'indigo',
'purple': 'purple',
'pink': 'pink',
'red': 'red',
'orange': 'orange',
'yellow': 'yellow',
'green': 'green',
'teal': 'teal',
'cyan': 'cyan',
'gray': 'gray',
'slate': 'slate',
'zinc': 'zinc',
'neutral': 'neutral',
'stone': 'stone',
'amber': 'amber',
'lime': 'lime',
'emerald': 'emerald',
'sky': 'sky',
'violet': 'violet',
'fuchsia': 'fuchsia',
'rose': 'rose'
);
@each $name, $color in $colors {
&-#{$name} {
background-color: color-mix(in srgb, var(--p-#{$color}-500), transparent 82%);
color: var(--p-#{$color}-300);
border: 1px solid color-mix(in srgb, var(--p-#{$color}-500), transparent 65%);
}
}
&-dark {
background-color: color-mix(in srgb, var(--p-gray-800), transparent 82%);
color: var(--p-gray-300);
border: 1px solid color-mix(in srgb, var(--p-gray-800), transparent 65%);
}
&-light {
background-color: color-mix(in srgb, var(--p-gray-300), transparent 82%);
color: var(--p-gray-600);
border: 1px solid color-mix(in srgb, var(--p-gray-300), transparent 65%);
}
&-variant-pill {
border-radius: 9999px;
padding: 0.125rem 0.375rem;
&.app-tag-primary {
background-color: var(--p-primary-600);
color: var(--p-primary-100);
border-color: var(--p-primary-500);
}
@each $name, $color in $colors {
&.app-tag-#{$name} {
background-color: var(--p-#{$color}-600);
color: var(--p-#{$color}-100);
border-color: var(--p-#{$color}-500);
}
}
&.app-tag-dark {
background-color: var(--p-gray-800);
color: var(--p-gray-100);
border-color: var(--p-gray-700);
}
&.app-tag-light {
background-color: var(--p-gray-300);
color: var(--p-gray-800);
border-color: var(--p-gray-400);
}
}
}
@@ -0,0 +1,45 @@
import {ChangeDetectionStrategy, Component, computed, input} from '@angular/core';
export type TagColor =
| 'primary' | 'secondary' | 'success' | 'info' | 'warning' | 'danger'
| 'blue' | 'indigo' | 'purple' | 'pink' | 'red' | 'orange' | 'yellow'
| 'green' | 'teal' | 'cyan' | 'gray' | 'slate' | 'zinc' | 'neutral'
| 'stone' | 'amber' | 'lime' | 'emerald' | 'sky' | 'violet' | 'fuchsia'
| 'rose' | 'dark' | 'light';
export type TagSize = '5xs' | '4xs' | '3xs' | '2xs' | 'xs' | 's' | 'm' | 'l' | 'xl' | '2xl' | '3xl' | '4xl' | '5xl';
export type TagVariant = 'label' | 'pill';
@Component({
selector: 'app-tag',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<span
[class]="tagClasses()"
[style.background-color]="customBgColor()"
[style.color]="customTextColor()"
>
<ng-content></ng-content>
</span>
`,
styleUrls: ['./tag.component.scss']
})
export class TagComponent {
color = input<TagColor>('primary');
size = input<TagSize>('m');
variant = input<TagVariant>('label');
rounded = input(false);
pill = input(false);
customBgColor = input<string>();
customTextColor = input<string>();
protected tagClasses = computed(() => {
const classes = ['app-tag', `app-tag-${this.color()}`, `app-tag-${this.size()}`];
if (this.variant() === 'pill') classes.push('app-tag-variant-pill');
if (this.rounded()) classes.push('app-tag-rounded');
if (this.pill()) classes.push('app-tag-pill');
return classes.join(' ');
});
}
@@ -0,0 +1,9 @@
<div class="metadata-progress-box">
<app-live-notification-box/>
@if (hasMetadataTasks$ | async) {
<app-metadata-progress-widget/>
}
@if (hasPendingBookdropFiles$ | async) {
<app-bookdrop-files-widget-component/>
}
</div>
@@ -0,0 +1,14 @@
.metadata-progress-box {
display: flex;
flex-direction: column;
gap: 1rem;
width: 25rem;
max-height: 60vh;
overflow-y: auto;
border-radius: 0.5rem;
}
::ng-deep .p-divider-horizontal {
margin: 0 !important;
padding: 0 !important;
}
@@ -0,0 +1,31 @@
import {Component, inject} from '@angular/core';
import {LiveNotificationBoxComponent} from '../live-notification-box/live-notification-box.component';
import {MetadataProgressService} from '../../service/metadata-progress.service';
import {map} from 'rxjs/operators';
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';
@Component({
selector: 'app-unified-notification-popover-component',
imports: [
LiveNotificationBoxComponent,
MetadataProgressWidgetComponent,
AsyncPipe,
BookdropFilesWidgetComponent
],
templateUrl: './unified-notification-popover-component.html',
standalone: true,
styleUrl: './unified-notification-popover-component.scss'
})
export class UnifiedNotificationBoxComponent {
metadataProgressService = inject(MetadataProgressService);
bookdropFileService = inject(BookdropFileService);
hasMetadataTasks$ = this.metadataProgressService.activeTasks$.pipe(
map(tasks => Object.keys(tasks).length > 0)
);
hasPendingBookdropFiles$ = this.bookdropFileService.hasPendingFiles$;
}
@@ -0,0 +1,8 @@
export const ResetProgressTypes = {
KOREADER: 'KOREADER',
// TODO(grimmory-cleanup): Switch backend/API payloads to emit a real GRIMMORY reset type and drop the BOOKLORE alias.
GRIMMORY: 'BOOKLORE',
KOBO: 'KOBO'
} as const;
export type ResetProgressType = typeof ResetProgressTypes[keyof typeof ResetProgressTypes];
@@ -0,0 +1,44 @@
export class IconCategoriesHelper {
static readonly CATEGORIES: string[] = [
"address-book", "align-center", "align-justify", "align-left", "align-right", "amazon", "android",
"angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left",
"angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right", "arrow-circle-up",
"arrow-down", "arrow-down-left", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-right", "arrow-left",
"arrow-right", "arrow-right-arrow-left", "arrow-up", "arrow-up-left", "arrow-up-right", "arrow-up-right-and-arrow-down-left-from-center",
"arrows-alt", "arrows-h", "arrows-v", "asterisk", "at", "backward", "ban", "barcode", "bars", "bell", "bell-slash",
"bitcoin", "bolt", "book", "bookmark", "bookmark-fill", "box", "briefcase", "building", "building-columns", "bullseye",
"calculator", "calendar", "calendar-clock", "calendar-minus", "calendar-plus", "calendar-times", "camera", "car",
"caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus", "chart-bar",
"chart-line", "chart-pie", "chart-scatter", "check", "check-circle", "check-square", "chevron-circle-down",
"chevron-circle-left", "chevron-circle-right", "chevron-circle-up", "chevron-down", "chevron-left", "chevron-right",
"chevron-up", "circle", "circle-fill", "circle-off", "circle-on", "clipboard", "clock", "clone", "cloud", "cloud-download",
"cloud-upload", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left",
"desktop", "directions", "directions-alt", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v",
"envelope", "equals", "eraser", "ethereum", "euro", "exclamation-circle", "exclamation-triangle", "expand",
"external-link", "eye", "eye-slash", "face-smile", "facebook", "fast-backward", "fast-forward", "file", "file-arrow-up",
"file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word",
"filter", "filter-fill", "filter-slash", "flag", "flag-fill", "folder", "folder-open", "folder-plus", "forward", "gauge",
"gift", "github", "globe", "google", "graduation-cap", "hammer", "hashtag", "headphones", "heart", "heart-fill", "history",
"home", "hourglass", "id-card", "image", "images", "inbox", "indian-rupee", "info", "info-circle", "instagram", "key",
"language", "lightbulb", "link", "linkedin", "list", "list-check", "lock", "lock-open", "map", "map-marker", "mars", "megaphone",
"microchip", "microchip-ai", "microphone", "microsoft", "minus", "minus-circle", "mobile", "money-bill", "moon", "objects-column",
"palette", "paperclip", "pause", "pause-circle", "paypal", "pen-to-square", "pencil", "percentage", "phone", "pinterest", "play",
"play-circle", "plus", "plus-circle", "pound", "power-off", "prime", "print", "qrcode", "question", "question-circle", "receipt",
"reddit", "refresh", "replay", "reply", "save", "search", "search-minus", "search-plus", "send", "server", "share-alt", "shield",
"shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort",
"sort-alpha-down", "sort-alpha-down-alt", "sort-alpha-up", "sort-alpha-up-alt", "sort-alt", "sort-alt-slash",
"sort-amount-down", "sort-amount-down-alt", "sort-amount-up", "sort-amount-up-alt", "sort-down", "sort-down-fill",
"sort-numeric-down", "sort-numeric-down-alt", "sort-numeric-up", "sort-numeric-up-alt", "sort-up", "sort-up-fill", "sparkles",
"spinner", "spinner-dotted", "star", "star-fill", "star-half", "star-half-fill", "step-backward", "step-backward-alt",
"step-forward", "step-forward-alt", "stop", "stop-circle", "stopwatch", "sun", "sync", "table", "tablet", "tag", "tags",
"telegram", "th-large", "thumbs-down", "thumbs-down-fill", "thumbs-up", "thumbs-up-fill", "thumbtack", "ticket", "tiktok",
"times", "times-circle", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user",
"user-edit", "user-minus", "user-plus", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off",
"volume-up", "wallet", "warehouse", "wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench",
"youtube"
];
static createIconList(): string[] {
return this.CATEGORIES.map(iconName => `pi pi-${iconName}`);
}
}
@@ -0,0 +1,4 @@
export interface MenuChangeEvent {
key: string;
routeEvent?: boolean;
}
@@ -0,0 +1,12 @@
<div class="layout-wrapper" [ngClass]="containerClass">
<app-topbar></app-topbar>
<div class="layout-sidebar">
<app-sidebar></app-sidebar>
</div>
<div class="layout-main-container">
<div class="layout-main">
<router-outlet></router-outlet>
</div>
</div>
<div class="layout-mask"></div>
</div>
@@ -0,0 +1,125 @@
import {Component, OnDestroy, OnInit, Renderer2, ViewChild} from '@angular/core';
import {NavigationEnd, Router, RouterOutlet} from '@angular/router';
import {filter, Subscription} from 'rxjs';
import {LayoutService} from "./service/app.layout.service";
import {AppSidebarComponent} from "../layout-sidebar/app.sidebar.component";
import {AppTopBarComponent} from '../layout-topbar/app.topbar.component';
import {NgClass} from '@angular/common';
import {ToastModule} from 'primeng/toast';
import {LocalStorageService} from '../../../service/local-storage.service';
@Component({
selector: 'app-layout',
imports: [
RouterOutlet,
AppSidebarComponent,
AppTopBarComponent,
NgClass,
ToastModule
],
templateUrl: './app.layout.component.html'
})
export class AppLayoutComponent implements OnInit, OnDestroy {
overlayMenuOpenSubscription: Subscription;
menuOutsideClickListener: (() => void) | null = null;
profileMenuOutsideClickListener: (() => void) | null = null;
@ViewChild(AppSidebarComponent) appSidebar!: AppSidebarComponent;
@ViewChild(AppTopBarComponent) appTopbar!: AppTopBarComponent;
constructor(public layoutService: LayoutService, public renderer: Renderer2, public router: Router, private localStorageService: LocalStorageService) {
this.overlayMenuOpenSubscription = this.layoutService.overlayOpen$.subscribe(() => {
if (!this.menuOutsideClickListener) {
this.menuOutsideClickListener = this.renderer.listen('document', 'click', (event) => {
if (this.isOutsideClicked(event)) {
this.hideMenu();
}
});
}
if (this.layoutService.state.staticMenuMobileActive) {
this.blockBodyScroll();
}
});
this.router.events.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(() => {
this.hideMenu();
this.hideProfileMenu();
});
}
ngOnInit(): void {
const width = this.localStorageService.get<number>('sidebarWidth') ?? 225;
document.documentElement.style.setProperty('--sidebar-width', width + 'px');
}
isOutsideClicked(event: MouseEvent): boolean {
const sidebarEl = document.querySelector('.layout-sidebar');
const topbarEl = document.querySelector('.layout-menu-button');
const eventTarget = event.target as Node;
const clickedInsideSidebar = sidebarEl?.isSameNode(eventTarget) || sidebarEl?.contains(eventTarget);
const clickedInsideTopbar = topbarEl?.isSameNode(eventTarget) || topbarEl?.contains(eventTarget);
return !(clickedInsideSidebar || clickedInsideTopbar);
}
hideMenu() {
this.layoutService.state.overlayMenuActive = false;
this.layoutService.state.staticMenuMobileActive = false;
this.layoutService.state.menuHoverActive = false;
if (this.menuOutsideClickListener) {
this.menuOutsideClickListener();
this.menuOutsideClickListener = null;
}
this.unblockBodyScroll();
}
hideProfileMenu() {
this.layoutService.state.profileSidebarVisible = false;
if (this.profileMenuOutsideClickListener) {
this.profileMenuOutsideClickListener();
this.profileMenuOutsideClickListener = null;
}
}
blockBodyScroll(): void {
if (document.body.classList) {
document.body.classList.add('blocked-scroll');
} else {
document.body.className += ' blocked-scroll';
}
}
unblockBodyScroll(): void {
if (document.body.classList) {
document.body.classList.remove('blocked-scroll');
} else {
document.body.className = document.body.className.replace(new RegExp('(^|\\b)' +
'blocked-scroll'.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
get containerClass() {
return {
'layout-overlay': this.layoutService.config().menuMode === 'overlay',
'layout-static': this.layoutService.config().menuMode === 'static',
'layout-static-inactive': this.layoutService.state.staticMenuDesktopInactive && this.layoutService.config().menuMode === 'static',
'layout-overlay-active': this.layoutService.state.overlayMenuActive,
'layout-mobile-active': this.layoutService.state.staticMenuMobileActive
}
}
ngOnDestroy() {
if (this.overlayMenuOpenSubscription) {
this.overlayMenuOpenSubscription.unsubscribe();
}
if (this.menuOutsideClickListener) {
this.menuOutsideClickListener();
}
}
}
@@ -0,0 +1,138 @@
import {Injectable, effect, signal} from '@angular/core';
import {Subject} from 'rxjs';
export interface AppConfig {
inputStyle: string;
colorScheme: string;
theme: string;
ripple: boolean;
menuMode: string;
scale: number;
}
interface LayoutState {
staticMenuDesktopInactive: boolean;
overlayMenuActive: boolean;
profileSidebarVisible: boolean;
configSidebarVisible: boolean;
staticMenuMobileActive: boolean;
menuHoverActive: boolean;
}
@Injectable({
providedIn: 'root',
})
export class LayoutService {
_config: AppConfig = {
ripple: false,
inputStyle: 'outlined',
menuMode: 'static',
colorScheme: 'light',
theme: 'lara-light-indigo',
scale: 14,
};
config = signal<AppConfig>(this._config);
state: LayoutState = {
staticMenuDesktopInactive: false,
overlayMenuActive: false,
profileSidebarVisible: false,
configSidebarVisible: false,
staticMenuMobileActive: false,
menuHoverActive: false,
};
private configUpdate = new Subject<AppConfig>();
private overlayOpen = new Subject<unknown>();
overlayOpen$ = this.overlayOpen.asObservable();
constructor() {
effect(() => {
const config = this.config();
if (this.updateStyle(config)) {
this.changeTheme();
}
this.changeScale(config.scale);
this.onConfigUpdate();
});
}
updateStyle(config: AppConfig) {
return (
config.theme !== this._config.theme ||
config.colorScheme !== this._config.colorScheme
);
}
onMenuToggle() {
if (this.isOverlay()) {
this.state.overlayMenuActive = !this.state.overlayMenuActive;
if (this.state.overlayMenuActive) {
this.overlayOpen.next(null);
}
}
if (this.isDesktop()) {
this.state.staticMenuDesktopInactive = !this.state.staticMenuDesktopInactive;
} else {
this.state.staticMenuMobileActive = !this.state.staticMenuMobileActive;
if (this.state.staticMenuMobileActive) {
this.overlayOpen.next(null);
}
}
}
isOverlay() {
return this.config().menuMode === 'overlay';
}
isDesktop() {
return window.innerWidth > 991;
}
onConfigUpdate() {
this._config = {...this.config()};
this.configUpdate.next(this.config());
}
changeTheme() {
const config = this.config();
const themeLink = document.getElementById('theme-css') as HTMLLinkElement;
const themeLinkHref = themeLink.getAttribute('href')!;
const newHref = themeLinkHref
.split('/')
.map((el) =>
el == this._config.theme
? (el = config.theme)
: el == `theme-${this._config.colorScheme}`
? (el = `theme-${config.colorScheme}`)
: el
)
.join('/');
this.replaceThemeLink(newHref);
}
replaceThemeLink(href: string) {
const id = 'theme-css';
const themeLink = document.getElementById(id) as HTMLLinkElement;
const cloneLinkElement = themeLink.cloneNode(true) as HTMLLinkElement;
cloneLinkElement.setAttribute('href', href);
cloneLinkElement.setAttribute('id', id + '-clone');
themeLink.parentNode!.insertBefore(
cloneLinkElement,
themeLink.nextSibling
);
cloneLinkElement.addEventListener('load', () => {
themeLink.remove();
cloneLinkElement.setAttribute('id', id);
});
}
changeScale(value: number) {
document.documentElement.style.fontSize = `${value}px`;
}
}
@@ -0,0 +1,91 @@
<ng-container *transloco="let t; prefix: 'layout.menu'">
<div class="menu-container">
<div>
<div class="home-menu-section">
<ul class="layout-menu">
@if (homeMenu(); as homeMenu) {
@for (item of homeMenu; track item.label; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="home"></li>
}
}
}
</ul>
<i class="pi pi-objects-column sidebar-width-btn"
(click)="widthPanel.toggle($event)"></i>
<p-popover #widthPanel appendTo="body">
<div class="sidebar-width-popover">
<label class="sidebar-width-popover-label">{{ sidebarWidth }}px</label>
<p-slider
[(ngModel)]="sidebarWidth"
[min]="175"
[max]="400"
[step]="1"
(onChange)="onSidebarWidthChange()"
(onSlideEnd)="saveSidebarWidth()">
</p-slider>
</div>
</p-popover>
</div>
<ul class="layout-menu">
@if (libraryMenu(); as libraryMenu) {
@for (item of libraryMenu; track item.label; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="library"></li>
}
}
}
</ul>
<ul class="layout-menu">
@if (shelfMenu(); as shelfMenu) {
@for (item of shelfMenu; track item.label; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="shelf"></li>
}
}
}
</ul>
<ul class="layout-menu">
@if (magicShelfMenu(); as shelfMenu) {
@for (item of shelfMenu; track item.label; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true" menuKey="magicShelf"></li>
}
}
}
</ul>
</div>
@if (versionInfo) {
<div class="version-info" style="margin-top: auto;">
<div class="version-text">
@if (isSemanticVersion(versionInfo.current)) {
<a
[href]="getVersionUrl(versionInfo.current)"
target="_blank"
rel="noopener noreferrer"
class="version-link"
>
{{ versionInfo.current }}
</a>
} @else {
<span class="version-label">{{ versionInfo.current }}</span>
}
</div>
@if (isSemanticVersion(versionInfo.current) && versionInfo.latest && versionInfo.latest !== versionInfo.current) {
<div>
<a
(click)="openChangelogDialog()"
class="update-link"
>
{{ t('update') }}
</a>
</div>
}
</div>
}
</div>
</ng-container>
@@ -0,0 +1,78 @@
.menu-container {
display: flex;
flex-direction: column;
height: 100%;
}
.home-menu-section {
position: relative;
.sidebar-width-btn {
position: absolute;
top: 0.125rem;
right: 0.5rem;
font-size: 0.8rem;
color: var(--p-surface-500);
cursor: pointer;
transition: color 0.2s ease;
&:hover {
color: var(--p-primary-color);
}
}
}
.sidebar-width-popover {
display: flex;
align-items: center;
gap: 0.75rem;
min-width: 200px;
padding: 0.25rem;
.sidebar-width-popover-label {
font-size: 0.8rem;
color: var(--p-text-muted-color);
white-space: nowrap;
min-width: 38px;
text-align: right;
}
p-slider {
flex: 1;
}
}
.version-info {
padding: 1rem;
text-align: center;
width: 100%;
font-size: 0.875rem;
}
.version-text {
color: #e5e7eb;
}
.version-link {
font-size: 0.875rem;
&:hover {
text-decoration: underline;
color: #f3f4f6;
}
}
.version-label {
font-size: 0.875rem;
}
.update-link {
cursor: pointer;
color: #fb923c;
font-size: 0.75rem;
&:hover {
text-decoration: underline;
color: #fdba74;
}
}
@@ -0,0 +1,349 @@
import {Component, computed, effect, inject, OnInit, signal} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop';
import {AppMenuitemComponent} from './app.menuitem.component';
import {MenuModule} from 'primeng/menu';
import {LibraryService} from '../../../../features/book/service/library.service';
import {LibraryHealthService} from '../../../../features/book/service/library-health.service';
import {ShelfService} from '../../../../features/book/service/shelf.service';
import {BookService} from '../../../../features/book/service/book.service';
import {LibraryShelfMenuService} from '../../../../features/book/service/library-shelf-menu.service';
import {AppVersion, VersionService} from '../../../service/version.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {MagicShelfService} from '../../../../features/magic-shelf/service/magic-shelf.service';
import {SeriesDataService} from '../../../../features/series-browser/service/series-data.service';
import {AuthorService} from '../../../../features/author-browser/service/author.service';
import {MenuItem} from 'primeng/api';
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Slider} from 'primeng/slider';
import {FormsModule} from '@angular/forms';
import {Popover} from 'primeng/popover';
import {LocalStorageService} from '../../../service/local-storage.service';
@Component({
selector: 'app-menu',
standalone: true,
imports: [AppMenuitemComponent, MenuModule, TranslocoDirective, Slider, FormsModule, Popover],
templateUrl: './app.menu.component.html',
styleUrl: './app.menu.component.scss',
})
export class AppMenuComponent implements OnInit {
versionInfo: AppVersion | null = null;
dynamicDialogRef: DynamicDialogRef | undefined | null;
private libraryService = inject(LibraryService);
private libraryHealthService = inject(LibraryHealthService);
private shelfService = inject(ShelfService);
private bookService = inject(BookService);
private versionService = inject(VersionService);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
private dialogLauncherService = inject(DialogLauncherService);
private userService = inject(UserService);
private magicShelfService = inject(MagicShelfService);
private seriesDataService = inject(SeriesDataService);
private authorService = inject(AuthorService);
private t = inject(TranslocoService);
private localStorageService = inject(LocalStorageService);
private activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()});
private readonly currentUser = this.userService.currentUser;
private allAuthors = this.authorService.allAuthors;
librarySortField = signal<'name' | 'id'>('name');
librarySortOrder = signal<'asc' | 'desc'>('desc');
shelfSortField = signal<'name' | 'id'>('name');
shelfSortOrder = signal<'asc' | 'desc'>('asc');
magicShelfSortField = signal<'name' | 'id'>('name');
magicShelfSortOrder = signal<'asc' | 'desc'>('asc');
sidebarWidth = 225;
private readonly libraryBookCounts = computed(() => {
const counts = new Map<number, number>();
for (const book of this.bookService.books()) {
if (book.libraryId != null) {
counts.set(book.libraryId, (counts.get(book.libraryId) ?? 0) + 1);
}
}
return counts;
});
private readonly shelfBookCounts = computed(() => {
const currentUserId = this.currentUser()?.id;
const counts = new Map<number, number>();
let unshelvedCount = 0;
for (const book of this.bookService.books()) {
if (!book.shelves || book.shelves.length === 0) {
unshelvedCount++;
} else {
for (const shelf of book.shelves) {
if (shelf.id != null) {
counts.set(shelf.id, (counts.get(shelf.id) ?? 0) + 1);
}
}
}
}
// For shelves not owned by the current user, fall back to the shelf's bookCount field
for (const shelf of this.shelfService.shelves()) {
if (shelf.userId !== currentUserId && shelf.id != null) {
counts.set(shelf.id, shelf.bookCount || 0);
}
}
counts.set(-1, unshelvedCount); // sentinel key for unshelved count
return counts;
});
private readonly magicShelfBookCounts = computed(() => {
const counts = new Map<number, number>();
const shelves = this.magicShelfService.shelves();
if (shelves.length === 0) return counts;
for (const shelf of shelves) {
if (shelf.id != null) {
counts.set(shelf.id, this.magicShelfService.getBookCountValue(shelf.id));
}
}
return counts;
});
readonly homeMenu = computed<MenuItem[]>(() => {
this.activeLang();
return [
{
label: this.t.translate('layout.menu.home'),
items: [
{
label: this.t.translate('layout.menu.dashboard'),
icon: 'pi pi-fw pi-home',
routerLink: ['/dashboard'],
},
{
label: this.t.translate('layout.menu.allBooks'),
type: 'All Books',
icon: 'pi pi-fw pi-book',
routerLink: ['/all-books'],
bookCount: this.bookService.books().length,
},
{
label: this.t.translate('layout.menu.series'),
type: 'Series',
icon: 'pi pi-fw pi-objects-column',
routerLink: ['/series'],
bookCount: this.seriesDataService.allSeries().length,
},
{
label: this.t.translate('layout.menu.authors'),
type: 'Authors',
icon: 'pi pi-fw pi-users',
routerLink: ['/authors'],
bookCount: this.allAuthors()?.length ?? 0,
},
{
label: this.t.translate('layout.menu.notebook'),
icon: 'pi pi-fw pi-pencil',
routerLink: ['/notebook'],
}
],
},
];
});
readonly libraryMenu = computed<MenuItem[]>(() => {
this.activeLang();
const libCounts = this.libraryBookCounts();
const sortedLibraries = this.sortArray(
this.libraryService.libraries(),
this.librarySortField(),
this.librarySortOrder()
);
return [
{
label: this.t.translate('layout.menu.libraries'),
type: 'library',
hasDropDown: true,
hasCreate: true,
items: sortedLibraries.map((library) => ({
menu: this.libraryShelfMenuService.initializeLibraryMenuItems(library),
label: library.name,
type: 'Library',
icon: library.icon || undefined,
iconType: (library.iconType || undefined) as 'PRIME_NG' | 'CUSTOM_SVG' | undefined,
routerLink: [`/library/${library.id}/books`],
bookCount: libCounts.get(library.id ?? 0) ?? 0,
unhealthy: this.libraryHealthService.isUnhealthy(library.id ?? 0),
})),
},
];
});
readonly magicShelfMenu = computed<MenuItem[]>(() => {
this.activeLang();
const sortedShelves = this.sortArray(
this.magicShelfService.shelves(),
this.magicShelfSortField(),
this.magicShelfSortOrder()
);
return [
{
label: this.t.translate('layout.menu.magicShelves'),
type: 'magicShelf',
hasDropDown: true,
hasCreate: true,
items: sortedShelves.map((shelf) => ({
label: shelf.name,
type: 'magicShelfItem',
icon: shelf.icon || undefined,
iconType: (shelf.iconType || undefined) as 'PRIME_NG' | 'CUSTOM_SVG' | undefined,
menu: this.libraryShelfMenuService.initializeMagicShelfMenuItems(shelf),
routerLink: [`/magic-shelf/${shelf.id}/books`],
bookCount: this.magicShelfBookCounts().get(shelf.id ?? 0) ?? 0,
})),
},
];
});
readonly shelfMenu = computed<MenuItem[]>(() => {
this.activeLang();
const shelfCounts = this.shelfBookCounts();
const sortedShelves = this.sortArray(
this.shelfService.shelves(),
this.shelfSortField(),
this.shelfSortOrder()
);
const shelves = [...sortedShelves];
const koboShelfIndex = shelves.findIndex(shelf => shelf.name === 'Kobo');
let koboShelf = null;
if (koboShelfIndex !== -1) {
koboShelf = shelves.splice(koboShelfIndex, 1)[0];
}
const shelfItems = shelves.map((shelf) => ({
menu: this.libraryShelfMenuService.initializeShelfMenuItems(shelf),
label: shelf.name,
type: 'Shelf',
icon: shelf.icon || undefined,
iconType: (shelf.iconType || undefined) as 'PRIME_NG' | 'CUSTOM_SVG' | undefined,
routerLink: [`/shelf/${shelf.id}/books`],
bookCount: shelfCounts.get(shelf.id ?? 0) ?? 0,
}));
const items: MenuItem[] = [{
label: this.t.translate('layout.menu.unshelved'),
type: 'Shelf',
icon: 'pi pi-inbox',
iconType: 'PRIME_NG' as 'PRIME_NG' | 'CUSTOM_SVG',
routerLink: ['/unshelved-books'],
bookCount: shelfCounts.get(-1) ?? 0,
}];
if (koboShelf) {
items.push({
label: koboShelf.name,
type: 'Shelf',
icon: koboShelf.icon || undefined,
iconType: (koboShelf.iconType || undefined) as 'PRIME_NG' | 'CUSTOM_SVG' | undefined,
routerLink: [`/shelf/${koboShelf.id}/books`],
bookCount: shelfCounts.get(koboShelf.id ?? 0) ?? 0,
});
}
items.push(...shelfItems);
return [
{
type: 'shelf',
label: this.t.translate('layout.menu.shelves'),
hasDropDown: true,
hasCreate: true,
items,
},
];
});
private readonly syncSortPreferencesEffect = effect(() => {
const user = this.currentUser();
if (!user) {
return;
}
if (user.userSettings.sidebarLibrarySorting) {
this.librarySortField.set(this.validateSortField(user.userSettings.sidebarLibrarySorting.field));
this.librarySortOrder.set(this.validateSortOrder(user.userSettings.sidebarLibrarySorting.order));
}
if (user.userSettings.sidebarShelfSorting) {
this.shelfSortField.set(this.validateSortField(user.userSettings.sidebarShelfSorting.field));
this.shelfSortOrder.set(this.validateSortOrder(user.userSettings.sidebarShelfSorting.order));
}
if (user.userSettings.sidebarMagicShelfSorting) {
this.magicShelfSortField.set(this.validateSortField(user.userSettings.sidebarMagicShelfSorting.field));
this.magicShelfSortOrder.set(this.validateSortOrder(user.userSettings.sidebarMagicShelfSorting.order));
}
});
ngOnInit(): void {
this.sidebarWidth = this.localStorageService.get<number>('sidebarWidth') ?? 225;
this.versionService.getVersion().subscribe((data) => {
this.versionInfo = data;
});
}
onSidebarWidthChange(): void {
document.documentElement.style.setProperty('--sidebar-width', this.sidebarWidth + 'px');
}
saveSidebarWidth(): void {
this.localStorageService.set('sidebarWidth', this.sidebarWidth);
}
openChangelogDialog() {
this.dialogLauncherService.openVersionChangelogDialog();
}
getVersionUrl(version: string | undefined): string {
if (!version) return '#';
return version.startsWith('v')
? `https://github.com/grimmory-tools/grimmory/releases/tag/${version}`
: `https://github.com/grimmory-tools/grimmory/commit/${version}`;
}
isSemanticVersion(version: string | undefined): boolean {
if (!version) return false;
const semanticVersionPattern = /^v\d+\.\d+\.\d+$/;
return semanticVersionPattern.test(version);
}
private sortArray<T extends { name?: string | null; id?: number | null }>(
items: T[],
field: 'name' | 'id',
order: 'asc' | 'desc'
): T[] {
const sorted = [...items].sort((a, b) => {
if (field === 'id') {
return (a.id ?? 0) - (b.id ?? 0);
}
return (a.name ?? '').localeCompare(b.name ?? '');
});
return order === 'desc' ? sorted.reverse() : sorted;
}
private validateSortField(field: string): 'name' | 'id' {
return field === 'id' ? 'id' : 'name';
}
private validateSortOrder(order: string): 'asc' | 'desc' {
return order === 'desc' ? 'desc' : 'asc';
}
}
@@ -0,0 +1,111 @@
<ng-container>
@if (root) {
@if (item.hasDropDown) {
<div class="layout-menuitem-root-text root-item-with-dropdown">
<div class="root-item-label-container">
<div>{{ item.label }}</div>
@if (item.hasCreate) {
<i
class="pi pi-plus plus-icon"
(click)="openDialog(item)"
></i>
}
</div>
<i
(click)="toggleExpand(key)"
[ngClass]="{
'pi': true,
'pi-angle-up': isExpanded(key),
'pi-angle-down': !isExpanded(key)
}"
class="expand-icon"
></i>
</div>
} @else {
<div class="layout-menuitem-root-text root-item">
<div>{{ item.label }}</div>
</div>
}
}
<div>
<div
class="menu-item-container"
[class.active-route-container]="isRouteActive"
(click)="triggerLink()"
>
@if ((item.routerLink && !item.items)) {
<a
#link
(click)="itemClick($event)"
[ngClass]="item.class"
class="menu-item-link"
[class.active-route]="isRouteActive"
[routerLink]="item.routerLink"
[fragment]="item.fragment"
[queryParamsHandling]="item.queryParamsHandling"
[preserveFragment]="item.preserveFragment"
[skipLocationChange]="item.skipLocationChange"
[replaceUrl]="item.replaceUrl"
[state]="item.state"
[queryParams]="item.queryParams"
[attr.target]="item.target"
tabindex="0"
pRipple
>
@if (item.unhealthy) {
<span
class="library-health-dot"
[pTooltip]="'common.libraryPathInaccessible' | transloco"
tooltipPosition="right"
></span>
}
<app-icon-display
[icon]="getIconSelection()"
iconClass="layout-menuitem-icon"
size="18px"
[displayEmpty]="true"
></app-icon-display>
<span class="layout-menuitem-text menu-item-text">
{{ item.label }}
</span>
</a>
}
<span class="menu-item-end-content">
@if (item.type === 'Library' || item.type === 'Shelf' || item.type === 'magicShelfItem') {
@if ((item.type !== 'Library' || (admin || canManipulateLibrary)) && item.label !== 'Unshelved' && item.label !== 'Kobo') {
<p-button
(click)="entitymenu.toggle($event); $event.stopPropagation()"
(mouseover)="hovered = true"
(mouseleave)="hovered = false"
[text]="true"
[outlined]="false"
[rounded]="true"
[label]="hovered ? '' : item.bookCount?.toString() || ''"
[icon]="hovered ? 'pi pi-ellipsis-v' : ''"
class="entity-menu-button"
></p-button>
}
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
}
@if (item.type === 'Library' && (!admin && !canManipulateLibrary) || item.type === 'All Books' || item.type === 'Series' || item.type === 'Authors' || item.label === 'Unshelved' || item.label === 'Kobo') {
<p class="book-count">
{{ formatCount(item.bookCount) }}
</p>
}
</span>
</div>
<div [@children]="isExpanded(key) ? 'expanded' : 'collapsed'" class="submenu-container">
@if (item.items) {
<ul>
@for (child of item.items; track child.routerLink?.[0] ?? child.label; let i = $index) {
<li app-menuitem [item]="child" [index]="i" [parentKey]="key" [class]="child.badgeClass"></li>
}
</ul>
}
</div>
</div>
</ng-container>
@@ -0,0 +1,116 @@
.plus-icon {
color: var(--p-primary-color);
transition: color 0.2s ease;
font-size: 0.8rem;
cursor: pointer;
&:hover {
color: var(--p-green-400);
}
}
.root-item-with-dropdown {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
padding-top: 1rem;
}
.root-item-label-container {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
cursor: pointer;
}
.expand-icon {
color: var(--p-surface-500);
padding-right: 0.75rem;
&:hover {
color: var(--p-surface-200);
}
}
.root-item {
display: flex;
align-items: center;
justify-content: space-between;
}
.menu-item-container {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
border-radius: 8px;
cursor: pointer;
&:hover {
background-color: var(--p-surface-800);
border-radius: 8px;
}
}
.menu-item-container.active-route-container {
background-color: color-mix(in srgb, var(--p-primary-300), transparent 93%);
border-radius: 8px;
}
.menu-item-link {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
}
.menu-item-text {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-left: 0.35rem;
font-size: 0.985rem;
}
.menu-item-end-content {
display: flex;
}
.entity-menu-button {
height: 30px;
display: flex;
}
.book-count {
color: var(--primary-color);
padding-right: 0.75rem;
}
.submenu-container {
overflow: hidden;
}
.library-health-dot {
display: inline-block;
flex-shrink: 0;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ef4444;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
}
50% {
opacity: 0.85;
box-shadow: 0 0 0 5px rgba(239, 68, 68, 0);
}
}
@@ -0,0 +1,197 @@
import {Component, effect, ElementRef, HostBinding, inject, Input, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {NavigationEnd, Router, RouterLink} from '@angular/router';
import {animate, state, style, transition, trigger} from '@angular/animations';
import {Subscription} from 'rxjs';
import {filter} from 'rxjs/operators';
import {MenuService} from './service/app.menu.service';
import {NgClass} from '@angular/common';
import {Ripple} from 'primeng/ripple';
import {Button} from 'primeng/button';
import {Menu} from 'primeng/menu';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
import {BookDialogHelperService} from '../../../../features/book/components/book-browser/book-dialog-helper.service';
import {IconDisplayComponent} from '../../../components/icon-display/icon-display.component';
import {Tooltip} from 'primeng/tooltip';
import {MenuItem} from 'primeng/api';
import {IconSelection} from '../../../service/icon-picker.service';
import {TranslocoPipe} from '@jsverse/transloco';
@Component({
selector: '[app-menuitem]',
templateUrl: './app.menuitem.component.html',
styleUrls: ['./app.menuitem.component.scss'],
imports: [
RouterLink,
NgClass,
Ripple,
Button,
Menu,
IconDisplayComponent,
Tooltip,
TranslocoPipe
],
animations: [
trigger('children', [
state('collapsed', style({
height: '0'
})),
state('expanded', style({
height: '*'
})),
transition('collapsed <=> expanded', animate('400ms cubic-bezier(0.86, 0, 0.07, 1)'))
])
]
})
export class AppMenuitemComponent implements OnInit, OnDestroy {
@Input() item: any;
@Input() index!: number;
@Input() @HostBinding('class.layout-root-menuitem') root!: boolean;
@Input() parentKey!: string;
@Input() menuKey!: string;
@ViewChild('linkRef') linkRef!: ElementRef<HTMLAnchorElement>;
hovered = false;
active = false;
key: string = "";
canManipulateLibrary: boolean = false;
admin: boolean = false;
expandedItems = new Set<string>();
get isRouteActive(): boolean {
if (!this.item?.routerLink?.[0]) return false;
return this.router.url.split('?')[0] === this.item.routerLink[0];
}
private userService = inject(UserService);
menuSourceSubscription: Subscription;
menuResetSubscription: Subscription;
private routerSubscription: Subscription;
constructor(
public router: Router,
private menuService: MenuService,
private dialogLauncher: DialogLauncherService,
private bookDialogHelperService: BookDialogHelperService
) {
effect(() => {
const user = this.userService.currentUser();
if (user) {
this.canManipulateLibrary = user.permissions.canManageLibrary;
this.admin = user.permissions.admin;
}
});
this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => {
Promise.resolve(null).then(() => {
if (value.routeEvent) {
this.active = (value.key === this.key || value.key.startsWith(this.key + '-')) ? true : false;
} else {
if (value.key !== this.key && !value.key.startsWith(this.key + '-')) {
this.active = false;
}
}
});
});
this.menuResetSubscription = this.menuService.resetSource$.subscribe(() => {
this.active = false;
});
this.routerSubscription = this.router.events.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(() => {
if (this.item.routerLink) {
this.updateActiveStateFromRoute();
}
});
}
ngOnInit() {
const rootKey = this.menuKey ? this.menuKey + '-' : '';
this.key = this.parentKey ? this.parentKey + '-' + this.index : rootKey + String(this.index);
this.expandedItems.add(this.key);
if (this.item.routerLink) {
this.updateActiveStateFromRoute();
}
}
ngOnDestroy() {
this.menuSourceSubscription?.unsubscribe();
this.menuResetSubscription?.unsubscribe();
this.routerSubscription?.unsubscribe();
}
toggleExpand(key: string) {
if (this.expandedItems.has(key)) {
this.expandedItems.delete(key);
} else {
this.expandedItems.add(key);
}
}
isExpanded(key: string): boolean {
return this.expandedItems.has(key);
}
updateActiveStateFromRoute() {
const activeRoute = this.router.isActive(this.item.routerLink[0], {
paths: 'exact',
queryParams: 'ignored',
matrixParams: 'ignored',
fragment: 'ignored'
});
if (activeRoute) {
this.menuService.onMenuStateChange({key: this.key, routeEvent: true});
}
}
itemClick(event: Event) {
if (this.item.disabled) {
event.preventDefault();
return;
}
if (this.item.command) {
this.item.command({originalEvent: event, item: this.item});
}
if (this.item.items) {
this.active = !this.active;
} else {
this.active = true;
}
this.menuService.onMenuStateChange({key: this.key});
}
openDialog(item: any) {
if (item.type === 'library' && this.canManipulateLibrary) {
this.dialogLauncher.openLibraryCreateDialog();
}
if (item.type === 'magicShelf') {
this.dialogLauncher.openMagicShelfCreateDialog();
}
if (item.type === 'shelf') {
this.bookDialogHelperService.openShelfCreatorDialog();
}
}
triggerLink() {
if (this.item.routerLink && !this.item.items && this.linkRef) {
this.linkRef.nativeElement.click();
}
}
formatCount(count: number | null | undefined): string {
if (count == null) return '0';
if (count >= 1000) return Math.floor(count / 1000) + 'K';
return count.toString();
}
getIconSelection(): IconSelection | null {
if (!this.item.icon) return null;
return {
type: this.item.iconType || 'PRIME_NG',
value: this.item.icon
};
}
}
@@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { MenuChangeEvent } from '../../../api/menuchangeevent';
@Injectable({
providedIn: 'root'
})
export class MenuService {
private menuSource = new Subject<MenuChangeEvent>();
private resetSource = new Subject();
menuSource$ = this.menuSource.asObservable();
resetSource$ = this.resetSource.asObservable();
onMenuStateChange(event: MenuChangeEvent) {
this.menuSource.next(event);
}
reset() {
this.resetSource.next(true);
}
}
@@ -0,0 +1,50 @@
<ng-container *transloco="let t; prefix: 'layout.changelog'">
<div class="changelog-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-sparkles header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">{{ t('title') }}</h2>
<p class="panel-description">{{ t('description') }}</p>
</div>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(click)="dialogRef.close()"
class="close-button">
</p-button>
</div>
<div class="dialog-content">
@if (loading) {
<div class="loading-state">
{{ t('loading') }}
</div>
}
@if (!loading && changelog.length === 0) {
<div class="empty-state">
{{ t('empty') }}
</div>
}
@if (!loading && changelog.length > 0) {
<div class="changelog-list">
@for (release of changelog; track release) {
<div class="release-item">
<p class="release-title">
<a [href]="release.url" target="_blank" rel="noopener noreferrer" class="release-link">
{{ release.name }} ({{ release.publishedAt | date: 'mediumDate' }})
</a>
</p>
<div [innerHTML]="markdownToHtml(release.changelog)" class="release-content"></div>
</div>
}
</div>
}
</div>
</div>
</ng-container>
@@ -0,0 +1,139 @@
@use '../../../../../shared/styles/panel-shared' as panel;
.changelog-container {
display: flex;
flex-direction: column;
max-height: 90dvh;
}
.panel-header {
@include panel.panel-header;
}
.dialog-content {
padding: 1.5rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
border-radius: 0 0 10px 10px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
overflow-y: auto;
flex: 1;
}
.loading-state,
.empty-state {
padding: 1rem;
text-align: center;
color: var(--text-secondary-color);
}
.changelog-list {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.release-item {
padding-bottom: 1rem;
border-bottom: 1px solid var(--border-color);
&:last-child {
border-bottom: none;
}
}
.release-title {
font-weight: 700;
font-size: 1.25rem;
padding-bottom: 0.5rem;
margin: 0;
}
.release-link {
color: var(--primary-color);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.release-content {
width: 100%;
max-width: 100%;
line-height: 1.75;
color: var(--text-color);
:host ::ng-deep & {
h1, h2, h3, h4, h5, h6 {
margin-top: 1.5rem;
margin-bottom: 0.75rem;
font-weight: 600;
line-height: 1.25;
color: var(--text-color);
&:first-child {
margin-top: 0;
}
}
h3 {
margin-top: 0;
font-size: 1.125rem;
}
p {
margin-top: 0.75rem;
margin-bottom: 0.75rem;
}
ul, ol {
margin-top: 0.75rem;
margin-bottom: 0.75rem;
padding-left: 1.5rem;
}
li {
margin-top: 0.25rem;
margin-bottom: 0.25rem;
}
code {
font-size: 0.875em;
background: var(--surface-ground);
padding: 0.125rem 0.375rem;
border-radius: 0.25rem;
}
pre {
margin-top: 1rem;
margin-bottom: 1rem;
padding: 1rem;
background: var(--surface-ground);
border-radius: 0.5rem;
overflow-x: auto;
code {
background: transparent;
padding: 0;
}
}
a {
color: var(--primary-color);
text-decoration: underline;
&:hover {
text-decoration: none;
}
}
blockquote {
margin: 1rem 0;
padding-left: 1rem;
border-left: 3px solid var(--border-color);
color: var(--text-secondary-color);
}
}
}
@@ -0,0 +1,49 @@
import { Component, inject, OnInit } from '@angular/core';
import { ReleaseNote, VersionService } from '../../../../service/version.service';
import showdown from 'showdown';
import DOMPurify from 'dompurify';
import {DatePipe} from '@angular/common';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Button} from 'primeng/button';
import {TranslocoDirective} from '@jsverse/transloco';
@Component({
selector: 'app-version-changelog-dialog',
standalone: true,
imports: [
DatePipe,
Button,
TranslocoDirective
],
templateUrl: './version-changelog-dialog.component.html',
styleUrl: './version-changelog-dialog.component.scss'
})
export class VersionChangelogDialogComponent implements OnInit {
private versionService = inject(VersionService);
dialogRef = inject(DynamicDialogRef);
changelog: ReleaseNote[] = [];
loading = true;
private converter = new showdown.Converter({ tables: true, emoji: true });
ngOnInit(): void {
this.versionService.getChangelog().subscribe({
next: (data) => {
this.changelog = data;
this.loading = false;
},
error: () => {
this.loading = false;
}
});
}
markdownToHtml(markdown: string): string {
let html = this.converter.makeHtml(markdown);
html = html.replace(/<h2\b([^>]*)>/g, '<h3$1>').replace(/<\/h2>/g, '</h3>');
return DOMPurify.sanitize(html);
}
}
@@ -0,0 +1 @@
<app-menu></app-menu>
@@ -0,0 +1,15 @@
import { Component, ElementRef } from '@angular/core';
import { LayoutService } from "../layout-main/service/app.layout.service";
import {AppMenuComponent} from '../layout-menu/app.menu.component';
@Component({
selector: 'app-sidebar',
imports: [
AppMenuComponent
],
templateUrl: './app.sidebar.component.html'
})
export class AppSidebarComponent {
constructor(public layoutService: LayoutService, public el: ElementRef) { }
}
@@ -0,0 +1,309 @@
<ng-container *transloco="let t; prefix: 'layout.topbar'">
<div class="layout-topbar">
<a class="layout-topbar-logo topbar-logo" routerLink="">
<!--
<svg class="logo-icon half-title" viewBox="0 0 126 126" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path
d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z"/>
<path
d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z"
fill="white"/>
</svg>
-->
<span class="logo-text">Grimmory</span>
</a>
<p-button
class="layout-menu-button"
#menubutton
icon="pi pi-bars"
[rounded]="true"
[outlined]="true"
(click)="toggleMenu()"
[ngClass]="{ 'rotate-right': !isMenuVisible, 'rotate-left': isMenuVisible }"
>
</p-button>
<div class="topbar-content">
<app-book-searcher class="topbar-search"></app-book-searcher>
<ul class="topbar-items topbar-desktop-items">
<div class="topbar-action-group">
@if (user(); as currentUser) {
@if (currentUser.permissions?.canAccessBookdrop || currentUser.permissions?.admin) {
<li>
<a class="topbar-item" (click)="navigateToBookdrop()" [pTooltip]="t('bookdrop')" tooltipPosition="bottom">
<i class="pi pi-inbox topbar-icon"></i>
</a>
</li>
}
@if (currentUser.permissions?.canManageLibrary || currentUser.permissions?.admin) {
<li>
<a class="topbar-item" (click)="openLibraryCreatorDialog()" [pTooltip]="t('createNewLibrary')" tooltipPosition="bottom">
<i class="pi pi-plus-circle topbar-icon"></i>
</a>
</li>
}
@if (currentUser.permissions?.canUpload || currentUser.permissions?.admin) {
<li>
<a class="topbar-item" (click)="openFileUploadDialog()" [pTooltip]="t('uploadBook')" tooltipPosition="bottom">
<i class="pi pi-upload topbar-icon"></i>
</a>
</li>
}
}
@if (hasStatsAccess) {
<li>
<button
class="topbar-item"
(click)="shouldShowStatsMenu ? statsMenu?.toggle($event) : handleStatsButtonClick($event)"
[pTooltip]="statsTooltip"
tooltipPosition="bottom">
<svg class="multi-color-chart-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="width: 1.25rem; height: 1.25rem;">
<rect x="2" y="13" width="4" height="9" rx="1" fill="#ef4444"/>
<rect x="7.5" y="3" width="4" height="19" rx="1" fill="#f59e0b"/>
<rect x="13" y="9" width="4" height="13" rx="1" fill="#3b82f6"/>
<rect x="18.5" y="5" width="4" height="17" rx="1" fill="#10b981"/>
</svg>
</button>
@if (shouldShowStatsMenu) {
<p-menu #statsMenu [model]="statsMenuItems" [popup]="true" appendTo="body"/>
}
</li>
}
@if (user(); as currentUser) {
@if (currentUser.permissions?.canManageLibrary || currentUser.permissions?.admin) {
<li>
<a class="topbar-item" (click)="navigateToMetadataManager()" [pTooltip]="t('metadataManager')" tooltipPosition="bottom">
<i class="pi pi-sparkles topbar-icon"></i>
</a>
</li>
}
}
<li>
<a class="topbar-item" (click)="navigateToSettings()" [pTooltip]="t('settings')" tooltipPosition="bottom">
<i class="pi pi-cog topbar-icon"></i>
</a>
</li>
</div>
<p-divider layout="vertical"/>
<div class="topbar-action-group">
<li class="topbar-item-relative">
<button
type="button"
class="topbar-item"
(click)="notificationPopover.toggle($event)"
>
<i
class="pi"
[ngClass]="iconClass"
[ngStyle]="{ color: iconColor }"
style="font-size: 1.25rem"
[class.pulsating]="iconPulsating"
[attr.aria-label]="t('notificationAriaLabel')"
></i>
</button>
@if (shouldShowNotificationBadge) {
<span class="notification-badge">{{ completedTaskCount }}</span>
}
<p-popover #notificationPopover>
<app-unified-notification-popover-component></app-unified-notification-popover-component>
</p-popover>
</li>
<li class="topbar-item-relative">
<button
type="button"
class="topbar-item"
(click)="langMenu.toggle($event)"
[pTooltip]="t('language')"
tooltipPosition="bottom">
<i class="pi pi-language topbar-icon"></i>
</button>
<p-menu #langMenu [model]="langMenuItems" [popup]="true" appendTo="body"/>
</li>
<li class="topbar-item-relative">
<button type="button"
class="topbar-item config-item"
enterActiveClass="animate-scalein"
enterFromClass="hidden"
leaveActiveClass="animate-fadeout"
leaveToClass="hidden"
pStyleClass="@next" [hideOnOutsideClick]="true">
<i class="pi pi-palette"></i>
</button>
<app-theme-configurator></app-theme-configurator>
</li>
</div>
<p-divider layout="vertical"/>
<div class="topbar-action-group">
<li>
<a class="topbar-item"
href="https://grimmory.org/docs/getting-started"
target="_blank"
rel="noopener noreferrer"
[pTooltip]="t('documentation')"
tooltipPosition="bottom">
<i class="pi pi-info-circle topbar-icon"></i>
</a>
</li>
<!-- Show Profile only to non-demo users -->
@if (user(); as currentUser) {
@if (!currentUser.permissions?.demoUser) {
<li>
<button class="topbar-item" (click)="openUserProfileDialog()" [pTooltip]="t('profile')" tooltipPosition="bottom">
<i class="pi pi-user topbar-icon"></i>
</button>
</li>
}
}
<li>
<button class="topbar-item" (click)="logout()" [pTooltip]="t('logout')" tooltipPosition="left">
<i class="pi pi-sign-out topbar-icon"></i>
</button>
</li>
</div>
</ul>
<!-- Trigger Button -->
<div class="mobile-trigger">
<p-button
icon="pi pi-ellipsis-v"
outlined
(click)="mobileMenu.toggle($event)"
/>
<p-popover #mobileMenu>
<ul class="mobile-menu-list">
@if (user(); as currentUser) {
@if (currentUser.permissions?.canAccessBookdrop || currentUser.permissions?.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToBookdrop(); mobileMenu.hide()"
>
<i class="pi pi-inbox topbar-icon"></i>
{{ t('bookdrop') }}
</button>
</li>
}
@if (currentUser.permissions?.canManageLibrary || currentUser.permissions?.admin) {
<li>
<button
class="mobile-menu-item"
(click)="openLibraryCreatorDialog(); mobileMenu.hide()"
>
<i class="pi pi-plus-circle topbar-icon"></i>
{{ t('createLibrary') }}
</button>
</li>
}
@if (currentUser.permissions?.canUpload || currentUser.permissions?.admin) {
<li>
<button
class="mobile-menu-item"
(click)="openFileUploadDialog(); mobileMenu.hide()"
>
<i class="pi pi-upload topbar-icon"></i>
{{ t('uploadBook') }}
</button>
</li>
}
@if (currentUser.permissions?.canAccessLibraryStats || currentUser.permissions?.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToStats(); mobileMenu.hide()"
>
<i class="pi pi-chart-line topbar-icon"></i>
{{ t('libraryStats') }}
</button>
</li>
}
@if (currentUser.permissions?.canAccessUserStats || currentUser.permissions?.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToUserStats(); mobileMenu.hide()"
>
<i class="pi pi-users topbar-icon"></i>
{{ t('readingStats') }}
</button>
</li>
}
@if (currentUser.permissions?.canManageLibrary || currentUser.permissions?.admin) {
<li>
<button
class="mobile-menu-item"
(click)="navigateToMetadataManager(); mobileMenu.hide()"
>
<i class="pi pi-sparkles topbar-icon"></i>
{{ t('metadataManager') }}
</button>
</li>
}
}
<li>
<button
class="mobile-menu-item"
(click)="navigateToSettings(); mobileMenu.hide()"
>
<i class="pi pi-cog topbar-icon"></i>
{{ t('settings') }}
</button>
</li>
<li>
<a
class="mobile-menu-item"
href="https://grimmory.org/docs/getting-started"
target="_blank"
rel="noopener noreferrer">
<i class="pi pi-info-circle topbar-icon"></i>
{{ t('documentation') }}
</a>
</li>
<li>
<button
class="mobile-menu-item"
(click)="langMenuMobile.toggle($event)"
>
<i class="pi pi-language topbar-icon"></i>
{{ t('language') }}
</button>
<p-menu #langMenuMobile [model]="langMenuItems" [popup]="true"/>
</li>
@if (user(); as currentUser) {
@if (!currentUser.permissions?.demoUser) {
<li>
<button
class="mobile-menu-item"
(click)="openUserProfileDialog(); mobileMenu.hide()"
>
<i class="pi pi-user topbar-icon"></i>
{{ t('profile') }}
</button>
</li>
}
}
<li>
<button
class="mobile-menu-item"
(click)="logout(); mobileMenu.hide()"
>
<i class="pi pi-sign-out topbar-icon"></i>
{{ t('logout') }}
</button>
</li>
</ul>
</p-popover>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,243 @@
.topbar-logo {
padding-left: 1.25rem;
padding-right: 6rem;
gap: 0.5rem;
}
.logo-text {
font-size: 1.875rem;
line-height: 2.25rem;
margin: 0;
}
.topbar-content {
display: flex;
align-items: center;
width: 100%;
min-width: 0;
gap: 1rem;
@media (max-width: 767px) {
gap: 0.5rem;
}
}
.topbar-search {
flex-grow: 1;
min-width: 0;
}
.topbar-desktop-items {
display: none;
align-items: center;
gap: 0.75rem;
margin-left: auto;
padding-left: 1rem;
@media (min-width: 768px) {
display: flex;
}
}
.topbar-action-group {
display: flex;
gap: 1rem;
}
.topbar-icon {
color: var(--p-surface-100);
}
.topbar-item-relative {
position: relative;
}
.heart-button {
overflow: visible;
cursor: pointer;
position: relative;
&:hover .heart-icon {
animation: heartbeat 0.6s ease-in-out;
filter: drop-shadow(0 0 8px rgba(236, 72, 153, 0.8));
}
&:hover .heart-ripple {
animation: ripple-burst 1.2s ease-out infinite;
}
&:hover .heart-ripple-delayed {
animation-delay: 0.4s;
}
}
.heart-ripple {
position: absolute;
z-index: -1;
inset: 0;
border-radius: 50%;
border: 1.5px solid #ec4899;
opacity: 0;
pointer-events: none;
}
.heart-orbit {
position: absolute;
z-index: 11;
width: 4px;
height: 4px;
border-radius: 50%;
pointer-events: none;
top: calc(50% - 2px);
left: calc(50% - 2px);
}
.heart-orbit-1 {
background: #f472b6;
box-shadow: 0 0 10px #f472b6, 0 0 4px #f472b6;
animation: orbit-1 2.5s linear infinite;
}
.heart-orbit-2 {
background: #a78bfa;
box-shadow: 0 0 10px #a78bfa, 0 0 4px #a78bfa;
animation: orbit-2 3.2s linear infinite reverse;
}
.heart-orbit-3 {
background: #38bdf8;
box-shadow: 0 0 10px #38bdf8, 0 0 4px #38bdf8;
animation: orbit-3 4s linear infinite;
}
.heart-icon {
z-index: 10;
color: #e8366d !important;
font-size: 1.05rem;
animation: heart-float 2.5s ease-in-out infinite;
filter: drop-shadow(0 0 6px rgba(232, 54, 109, 0.8));
transition: filter 0.3s;
}
.heart-button-static {
.heart-icon {
animation: none;
filter: none;
}
&:hover .heart-icon {
animation: none;
filter: none;
}
}
.mobile-trigger {
display: none;
position: relative;
margin-left: auto;
@media (max-width: 767px) {
display: block;
}
}
.mobile-menu-list {
display: flex;
flex-direction: column;
gap: 0.25rem;
width: 12rem;
}
.mobile-menu-item {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
text-align: left;
padding: 0.5rem;
border-radius: 0.25rem;
background: none;
border: none;
color: inherit;
font: inherit;
cursor: pointer;
text-decoration: none;
&:hover {
background: var(--p-surface-700);
}
}
.highlight {
color: red !important;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.spin {
animation: spin 1.5s linear infinite;
}
@keyframes orbit-1 {
0% { transform: rotate(0deg) translateX(16px) rotate(0deg); }
100% { transform: rotate(360deg) translateX(16px) rotate(-360deg); }
}
@keyframes orbit-2 {
0% { transform: rotate(120deg) translateX(14px) rotate(-120deg); }
100% { transform: rotate(480deg) translateX(14px) rotate(-480deg); }
}
@keyframes orbit-3 {
0% { transform: rotate(240deg) translateX(18px) rotate(-240deg); }
100% { transform: rotate(600deg) translateX(18px) rotate(-600deg); }
}
@keyframes ripple-burst {
0% { transform: scale(0.8); opacity: 0.6; }
100% { transform: scale(2.2); opacity: 0; }
}
@keyframes heart-float {
0%, 100% { transform: translateY(1px); }
50% { transform: translateY(-1px); }
}
@keyframes heartbeat {
0% { transform: scale(1); }
25% { transform: scale(1.35); }
40% { transform: scale(0.95); }
55% { transform: scale(1.2); }
100% { transform: scale(1); }
}
@keyframes pulsate {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.25); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
.pulsating {
animation: pulsate 1.5s infinite ease-in-out;
}
.notification-badge {
position: absolute;
top: -0.4rem;
right: -0.4rem;
background-color: red;
color: white;
border-radius: 50%;
width: 1.2rem;
height: 1.2rem;
font-size: 0.75rem;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
user-select: none;
}
@@ -0,0 +1,328 @@
import {Component, computed, effect, ElementRef, inject, OnDestroy, ViewChild} from '@angular/core';
import {MenuItem} from 'primeng/api';
import {LayoutService} from '../layout-main/service/app.layout.service';
import {Router, RouterLink} from '@angular/router';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {TooltipModule} from 'primeng/tooltip';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {BookSearcherComponent} from '../../../../features/book/components/book-searcher/book-searcher.component';
import {NgClass, NgStyle} from '@angular/common';
import {NotificationEventService} from '../../../websocket/notification-event.service';
import {Button} from 'primeng/button';
import {StyleClass} from 'primeng/styleclass';
import {Divider} from 'primeng/divider';
import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component';
import {AuthService} from '../../../service/auth.service';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {Popover} from 'primeng/popover';
import {MetadataProgressService} from '../../../service/metadata-progress.service';
import {takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
import {MetadataBatchProgressNotification} from '../../../model/metadata-batch-progress.model';
import {BookdropFileService} from '../../../../features/bookdrop/service/bookdrop-file.service';
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
import {UnifiedNotificationBoxComponent} from '../../../components/unified-notification-popover/unified-notification-popover-component';
import {Severity, LogNotification} from '../../../websocket/model/log-notification.model';
import {Menu} from 'primeng/menu';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {AVAILABLE_LANGS, LANG_LABELS} from '../../../../core/config/transloco-loader';
import {LANG_STORAGE_KEY} from '../../../../core/config/language-initializer';
@Component({
selector: 'app-topbar',
templateUrl: './app.topbar.component.html',
styleUrls: ['./app.topbar.component.scss'],
standalone: true,
imports: [
RouterLink,
TooltipModule,
FormsModule,
InputTextModule,
BookSearcherComponent,
Button,
ThemeConfiguratorComponent,
StyleClass,
NgClass,
Divider,
Popover,
UnifiedNotificationBoxComponent,
NgStyle,
Menu,
TranslocoDirective,
],
})
export class AppTopBarComponent implements OnDestroy {
protected readonly userService = inject(UserService);
protected readonly user = this.userService.currentUser;
items!: MenuItem[];
ref?: DynamicDialogRef;
statsMenuItems: MenuItem[] = [];
@ViewChild('menubutton') menuButton!: ElementRef;
@ViewChild('topbarmenubutton') topbarMenuButton!: ElementRef;
@ViewChild('topbarmenu') menu!: ElementRef;
@ViewChild('statsMenu') statsMenu: Menu | undefined;
isMenuVisible = true;
progressHighlight = false;
completedTaskCount = 0;
hasActiveOrCompletedTasks = false;
showPulse = false;
hasAnyTasks = false;
hasPendingBookdropFiles = false;
private eventTimer: number | undefined;
private destroy$ = new Subject<void>();
private latestTasks: Record<string, MetadataBatchProgressNotification> = {};
private latestHasPendingFiles = false;
private latestNotificationSeverity?: Severity;
activeLang = '';
langMenuItems: MenuItem[] = [];
private translocoService: TranslocoService;
constructor(
public layoutService: LayoutService,
private notificationService: NotificationEventService,
private router: Router,
private authService: AuthService,
private metadataProgressService: MetadataProgressService,
private bookdropFileService: BookdropFileService,
private dialogLauncher: DialogLauncherService,
translocoService: TranslocoService
) {
this.translocoService = translocoService;
this.activeLang = translocoService.getActiveLang();
this.langMenuItems = AVAILABLE_LANGS.map(lang => ({
label: LANG_LABELS[lang] || lang,
icon: lang === this.activeLang ? 'pi pi-check' : undefined,
command: () => this.switchLanguage(lang),
}));
this.subscribeToMetadataProgress();
this.subscribeToNotifications();
this.metadataProgressService.activeTasks$
.pipe(takeUntil(this.destroy$))
.subscribe((tasks) => {
this.latestTasks = tasks;
this.hasAnyTasks = Object.keys(tasks).length > 0;
this.updateCompletedTaskCount();
this.updateTaskVisibility(tasks);
});
this.bookdropFileService.hasPendingFiles$
.pipe(takeUntil(this.destroy$))
.subscribe((hasPending) => {
this.latestHasPendingFiles = hasPending;
this.hasPendingBookdropFiles = hasPending;
this.updateCompletedTaskCount();
this.updateTaskVisibilityWithBookdrop();
});
effect(() => {
this.user();
this.initializeStatsMenu();
});
this.translocoService.langChanges$
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.initializeStatsMenu();
});
}
ngOnDestroy(): void {
if (this.ref) this.ref.close();
clearTimeout(this.eventTimer);
this.destroy$.next();
this.destroy$.complete();
}
toggleMenu() {
this.isMenuVisible = !this.isMenuVisible;
this.layoutService.onMenuToggle();
}
openLibraryCreatorDialog(): void {
this.dialogLauncher.openLibraryCreateDialog();
}
openFileUploadDialog(): void {
this.dialogLauncher.openFileUploadDialog();
}
openUserProfileDialog(): void {
this.dialogLauncher.openUserProfileDialog();
}
navigateToSettings() {
this.router.navigate(['/settings']);
}
navigateToBookdrop() {
this.router.navigate(['/bookdrop']);
}
navigateToMetadataManager() {
this.router.navigate(['/metadata-manager']);
}
navigateToStats() {
this.router.navigate(['/library-stats']);
}
navigateToUserStats() {
this.router.navigate(['/reading-stats']);
}
switchLanguage(lang: string) {
if (lang === this.activeLang) return;
this.translocoService.load(lang).subscribe(() => {
this.translocoService.setActiveLang(lang);
localStorage.setItem(LANG_STORAGE_KEY, lang);
this.activeLang = lang;
this.langMenuItems = AVAILABLE_LANGS.map(l => ({
label: LANG_LABELS[l] || l,
icon: l === lang ? 'pi pi-check' : undefined,
command: () => this.switchLanguage(l),
}));
});
}
logout() {
this.authService.logout();
}
handleStatsButtonClick(event: Event) {
if (this.statsMenuItems.length === 0) {
return;
}
if (this.statsMenuItems.length === 1) {
this.statsMenuItems[0].command?.({originalEvent: event, item: this.statsMenuItems[0]});
}
}
private subscribeToMetadataProgress() {
this.metadataProgressService.progressUpdates$
.pipe(takeUntil(this.destroy$))
.subscribe((progress) => {
this.progressHighlight = progress.status === 'IN_PROGRESS';
});
}
private subscribeToNotifications() {
this.notificationService.latestNotification$
.pipe(takeUntil(this.destroy$))
.subscribe((notification: LogNotification) => {
this.latestNotificationSeverity = notification.severity;
this.triggerPulseEffect();
});
}
private triggerPulseEffect() {
this.showPulse = true;
clearTimeout(this.eventTimer);
this.eventTimer = setTimeout(() => {
this.showPulse = false;
}, 4000) as unknown as number;
}
private updateCompletedTaskCount() {
const completedMetadataTasks = Object.values(this.latestTasks).length;
const bookdropFileTaskCount = this.latestHasPendingFiles ? 1 : 0;
this.completedTaskCount = completedMetadataTasks + bookdropFileTaskCount;
}
private updateTaskVisibility(tasks: Record<string, MetadataBatchProgressNotification>) {
this.hasActiveOrCompletedTasks =
this.progressHighlight || this.completedTaskCount > 0 || Object.keys(tasks).length > 0;
this.updateTaskVisibilityWithBookdrop();
}
private updateTaskVisibilityWithBookdrop() {
this.hasActiveOrCompletedTasks = this.hasActiveOrCompletedTasks || this.hasPendingBookdropFiles;
}
private initializeStatsMenu() {
const user = this.user();
this.statsMenuItems = [];
if (user?.permissions?.canAccessLibraryStats || user?.permissions?.admin) {
this.statsMenuItems.push({
label: this.translocoService.translate('layout.topbar.libraryStats'),
icon: 'pi pi-chart-line',
command: () => this.navigateToStats()
});
}
if (user?.permissions?.canAccessUserStats || user?.permissions?.admin) {
this.statsMenuItems.push({
label: this.translocoService.translate('layout.topbar.readingStats'),
icon: 'pi pi-users',
command: () => this.navigateToUserStats()
});
}
}
get hasStatsAccess(): boolean {
return this.statsMenuItems.length > 0;
}
get shouldShowStatsMenu(): boolean {
return this.statsMenuItems.length > 1;
}
get statsTooltip(): string {
if (this.statsMenuItems.length === 0) {
return this.translocoService.translate('layout.topbar.stats');
}
if (this.statsMenuItems.length === 1) {
return this.statsMenuItems[0].label || this.translocoService.translate('layout.topbar.stats');
}
return this.translocoService.translate('layout.topbar.stats');
}
get iconClass(): string {
if (this.progressHighlight) return 'pi-spinner spin';
if (this.iconPulsating) return 'pi-wave-pulse';
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles) return 'pi-bell';
return 'pi-wave-pulse';
}
get iconColor(): string {
if (this.progressHighlight) return 'gold';
if (this.showPulse) {
switch (this.latestNotificationSeverity) {
case Severity.ERROR:
return 'crimson';
case Severity.INFO:
return 'aqua';
case Severity.WARN:
return 'orange';
default:
return 'orange';
}
}
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles)
return 'limegreen';
return 'inherit';
}
get iconPulsating(): boolean {
return !this.progressHighlight && (this.showPulse);
}
get shouldShowNotificationBadge(): boolean {
return (
(this.completedTaskCount > 0 || this.hasPendingBookdropFiles) &&
!this.progressHighlight &&
!this.showPulse
);
}
}
@@ -0,0 +1,26 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, map, tap} from 'rxjs';
import {API_CONFIG} from '../../../../core/config/api-config';
@Injectable({providedIn: 'root'})
export class BackgroundUploadService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/background`;
private readonly http = inject(HttpClient);
uploadFile(file: File): Observable<string> {
const formData = new FormData();
formData.append('file', file);
return this.http.post<{ url: string }>(`${this.baseUrl}/upload`, formData).pipe(
tap(response => console.log('File upload response:', response)),
map(resp => resp?.url)
);
}
uploadUrl(url: string): Observable<string> {
return this.http.post<{ url: string }>(`${this.baseUrl}/url`, {url}).pipe(
tap(response => console.log('URL upload response:', response)),
map(resp => resp?.url)
);
}
}
@@ -0,0 +1,27 @@
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class FaviconService {
private svgTemplate = (color: string) => `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 126 126" fill="currentColor">
<path d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z" fill="${color}"/>
<path d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z" fill="white"/>
</svg>
`;
updateFavicon(color: string) {
const svg = this.svgTemplate(color);
const blob = new Blob([svg], {type: 'image/svg+xml'});
const url = URL.createObjectURL(blob);
let favicon = document.querySelector("link[rel*='icon']") as HTMLLinkElement;
if (!favicon) {
favicon = document.createElement('link');
favicon.rel = 'icon';
document.head.appendChild(favicon);
}
favicon.type = 'image/svg+xml';
favicon.href = url;
}
}
@@ -0,0 +1,35 @@
<ng-container *transloco="let t; prefix: 'layout.theme'">
<div class="config-panel-content">
<div class="config-panel-colors">
<span class="config-panel-label">{{ t('primary') }}</span>
<div>
@for (primaryColor of primaryColors(); track primaryColor.name) {
<button
type="button"
[title]="primaryColor.name"
(click)="updateColors($event, 'primary', primaryColor)"
[ngClass]="{ 'active-color': primaryColor.name === selectedPrimaryColor() }"
[style]="{ 'background-color': primaryColor.name === 'noir' ? 'var(--text-color)' : primaryColor.palette['500'] || 'transparent' }"
></button>
}
</div>
</div>
<div class="config-panel-colors">
<span class="config-panel-label">{{ t('surface') }}</span>
<div>
@for (surface of surfaces; track surface.name) {
<button
type="button"
[title]="surface.name"
(click)="updateColors($event, 'surface', surface)"
[ngClass]="{ 'active-color': selectedSurfaceColor() ? selectedSurfaceColor() === surface.name : surface.name === 'zinc' }"
[style]="{'background-color': surface.name === 'noir' ? 'var(--text-color)' : surface.palette['500'] }">
</button>
}
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,84 @@
import {CommonModule} from '@angular/common';
import {ChangeDetectionStrategy, Component, computed, effect, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {ButtonModule} from 'primeng/button';
import {RadioButtonModule} from 'primeng/radiobutton';
import {ToggleSwitchModule} from 'primeng/toggleswitch';
import Aura from '../theme-palette-extend';
import {AppConfigService} from '../../../service/app-config.service';
import {TranslocoDirective} from '@jsverse/transloco';
import {FaviconService} from './favicon-service';
type ColorPalette = Record<string, string>;
interface Palette {
name: string;
palette: ColorPalette;
}
@Component({
selector: 'app-theme-configurator',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './theme-configurator.component.html',
host: {
class: 'config-panel hidden'
},
imports: [
CommonModule,
FormsModule,
ButtonModule,
RadioButtonModule,
ToggleSwitchModule,
TranslocoDirective
]
})
export class ThemeConfiguratorComponent {
readonly configService = inject(AppConfigService);
readonly faviconService = inject(FaviconService);
readonly surfaces = this.configService.surfaces;
readonly selectedPrimaryColor = computed(() => this.configService.appState().primary);
readonly selectedSurfaceColor = computed(() => this.configService.appState().surface);
readonly faviconColor = computed(() => {
const name = this.selectedPrimaryColor() ?? 'green';
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
const colorPalette = presetPalette[name];
return colorPalette?.[500] ?? name;
});
private readonly _faviconSyncEffect = effect(() => {
this.faviconService.updateFavicon(this.faviconColor());
});
readonly primaryColors = computed<Palette[]>(() => {
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
const colors = [
'emerald', 'green', 'lime', 'orange', 'amber', 'yellow',
'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet',
'purple', 'fuchsia', 'pink', 'rose', 'red',
'coralSunset', 'roseBlush', 'melonBlush', 'cottonCandy',
'apricotSunrise', 'antiqueBronze', 'butteryYellow', 'vanillaCream',
'citrusMint', 'freshMint', 'sagePearl', 'skyBlue','periwinkleCream',
'pastelRoyalBlue', 'lavenderDream', 'dustyNeutral'
];
return [{name: 'noir', palette: {}}].concat(
colors.map(name => ({
name,
palette: presetPalette[name] ?? {}
}))
);
});
updateColors(event: Event, type: 'primary' | 'surface', color: { name: string; palette?: ColorPalette }) {
this.configService.appState.update((state) => ({
...state,
[type]: color.name
}));
event.stopPropagation();
}
}
@@ -0,0 +1,61 @@
<ng-container *transloco="let t; prefix: 'layout.uploadDialog'">
<div class="upload-dialog-content">
<div class="upload-section">
<div class="file-selector">
<label class="file-label">{{ t('chooseFile') }}</label>
<p-button
[label]="t('selectImage')"
icon="pi pi-upload"
(click)="fileInput.click()"
outlined
severity="info">
</p-button>
</div>
<input
#fileInput
type="file"
accept=".jpg,.jpeg,.png,image/jpeg,image/png"
(change)="onFileSelected($event)"
style="display: none;">
<small class="file-note">{{ t('fileNote') }}</small>
@if (uploadFile) {
<small class="selected-file">{{ uploadFile.name }}</small>
}
</div>
<p-divider align="center" type="solid">
<span class="or-text">{{ t('or') }}</span>
</p-divider>
<div class="url-section">
<label for="urlInput" class="url-label">{{ t('imageUrl') }}</label>
<input
id="urlInput"
type="text"
[(ngModel)]="uploadImageUrl"
[placeholder]="t('urlPlaceholder')"
class="url-input"
pInputText>
<small class="url-note">{{ t('urlNote') }}</small>
</div>
@if (uploadError) {
<p-message severity="error">{{uploadError}}</p-message>
}
<div class="dialog-footer">
<p-button
[label]="'common.cancel' | transloco"
icon="pi pi-times"
(click)="cancel()"
severity="secondary"
outlined>
</p-button>
<p-button
[label]="'common.submit' | transloco"
icon="pi pi-check"
(click)="submit()">
</p-button>
</div>
</div>
</ng-container>
@@ -0,0 +1,82 @@
.upload-dialog-content {
display: flex;
flex-direction: column;
gap: 1.5rem;
padding: 1rem 0;
.upload-section {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1rem;
.file-selector {
display: flex;
align-items: center;
gap: 1rem;
}
.file-label {
font-weight: 500;
color: var(--text-color);
}
.file-input {
padding: 0.75rem;
border: 1px solid var(--border-color);
border-radius: var(--p-border-radius);
background: var(--ground-background);
}
.file-note {
color: var(--text-secondary-color);
font-size: 0.875rem;
margin-top: 0.25rem;
}
.selected-file {
color: var(--text-secondary-color);
font-style: italic;
}
}
.url-section {
display: flex;
flex-direction: column;
gap: 0.25rem;
.url-label {
font-weight: 500;
color: var(--text-color);
margin-bottom: 0.5rem;
}
.url-input {
width: 100%;
padding: 0.75rem;
}
.url-note {
color: var(--text-secondary-color);
font-size: 0.875rem;
margin-top: 0.25rem;
}
}
.or-text {
font-size: 0.9rem;
color: var(--text-color);
font-weight: 500;
}
p-message {
margin-top: 1rem;
}
.dialog-footer {
display: flex;
gap: 1rem;
justify-content: flex-end;
margin-top: 1rem;
}
}
@@ -0,0 +1,76 @@
import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {ButtonModule} from 'primeng/button';
import {InputTextModule} from 'primeng/inputtext';
import {DividerModule} from 'primeng/divider';
import {MessageModule} from 'primeng/message';
import {BackgroundUploadService} from '../background-upload.service';
import {take} from 'rxjs';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
@Component({
selector: 'app-upload-dialog',
standalone: true,
templateUrl: './upload-dialog.component.html',
styleUrls: ['./upload-dialog.component.scss'],
imports: [
CommonModule,
FormsModule,
ButtonModule,
InputTextModule,
DividerModule,
MessageModule,
TranslocoDirective,
TranslocoPipe
]
})
export class UploadDialogComponent {
private readonly dialogRef = inject(DynamicDialogRef);
private readonly backgroundUploadService = inject(BackgroundUploadService);
private readonly t = inject(TranslocoService);
uploadImageUrl = '';
uploadFile: File | null = null;
uploadError = '';
onFileSelected(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
this.uploadFile = input.files[0];
this.uploadImageUrl = '';
}
}
submit() {
this.uploadError = '';
let upload$;
if (this.uploadFile) {
upload$ = this.backgroundUploadService.uploadFile(this.uploadFile);
} else if (this.uploadImageUrl.trim()) {
upload$ = this.backgroundUploadService.uploadUrl(this.uploadImageUrl.trim());
} else {
this.uploadError = this.t.translate('layout.uploadDialog.errorNoInput');
return;
}
upload$.pipe(take(1)).subscribe({
next: (imageUrl) => {
if (imageUrl) {
this.dialogRef.close({ imageUrl });
} else {
this.uploadError = 'Failed to upload image.';
}
},
error: (err) => {
console.error('Upload failed:', err);
this.uploadError = 'Upload failed. Please try again.';
}
});
}
cancel() {
this.dialogRef.close();
}
}
@@ -0,0 +1,222 @@
import Aura from '@primeuix/themes/aura';
type ColorPalette = Record<string, string>;
const customPalettes: Record<string, ColorPalette> = {
coralSunset: {
50: '#fef7f0',
100: '#feede1',
200: '#fcd9c2',
300: '#f9be9e',
400: '#f59673',
500: '#ef7550',
600: '#de5a3a',
700: '#b94730',
800: '#943a2e',
900: '#78322a',
950: '#401814'
},
roseBlush: {
50: '#fef7f7',
100: '#feebeb',
200: '#fddcdc',
300: '#fbbfbf',
400: '#f69393',
500: '#ed6767',
600: '#d93f3f',
700: '#b73030',
800: '#982d2d',
900: '#7f2d2d',
950: '#451313'
},
melonBlush: {
50: '#fffafb',
100: '#fff2f4',
200: '#ffdfe7',
300: '#ffcbd4',
400: '#ffaebb',
500: '#ff90a2',
600: '#ff6f88',
700: '#e8506b',
800: '#b7384d',
900: '#7f2231',
950: '#3f1118'
},
cottonCandy: {
50: '#fff9fb',
100: '#fff0f6',
200: '#ffdfee',
300: '#ffc0e0',
400: '#ffa3cf',
500: '#ff86bf',
600: '#ff69ad',
700: '#e14f93',
800: '#b93a72',
900: '#86284f',
950: '#42142a'
},
apricotSunrise: {
50: '#fffaf7',
100: '#fff1e8',
200: '#ffe2c9',
300: '#ffd2a8',
400: '#ffbf88',
500: '#ffad68',
600: '#ff974f',
700: '#e67a3b',
800: '#b6572b',
900: '#7f351b',
950: '#3f190f'
},
antiqueBronze: {
50: '#faf7f2',
100: '#f4ede0',
200: '#e8d9c0',
300: '#d9c199',
400: '#c8a56f',
500: '#b8904f',
600: '#a67c44',
700: '#8a6439',
800: '#715233',
900: '#5c442c',
950: '#302316'
},
butteryYellow: {
50: '#fffef7',
100: '#fffceb',
200: '#fff7d1',
300: '#ffeea7',
400: '#ffe072',
500: '#ffcf45',
600: '#ffb61f',
700: '#ff9b0a',
800: '#cc7606',
900: '#a35f0c',
950: '#633204'
},
vanillaCream: {
50: '#fefdfb',
100: '#fefbf6',
200: '#fdf5ea',
300: '#fbecd5',
400: '#f7dbb5',
500: '#f1c589',
600: '#e8a95c',
700: '#d88d3e',
800: '#b47134',
900: '#915c2e',
950: '#4e2f17'
},
citrusMint: {
50: '#fbfff9',
100: '#f4fff2',
200: '#e8ffd9',
300: '#d1ffbc',
400: '#b7ffa0',
500: '#96ff84',
600: '#76e96e',
700: '#4fb84c',
800: '#2f7f32',
900: '#1a4f20',
950: '#0a2410'
},
freshMint: {
50: '#f8fff9',
100: '#f0fff3',
200: '#dcffea',
300: '#bfffd6',
400: '#99ffc2',
500: '#7fffae',
600: '#5fe592',
700: '#3fbf75',
800: '#2d8f55',
900: '#1e5f39',
950: '#0f2f1d'
},
sagePearl: {
50: '#fbfdfb',
100: '#f4f8f4',
200: '#e6efe6',
300: '#d1e6d1',
400: '#bcdcbf',
500: '#9fcfa8',
600: '#84b792',
700: '#5f8f6e',
800: '#3f6648',
900: '#25442e',
950: '#0f2118'
},
skyBlue: {
50: '#f7fbff',
100: '#eef6ff',
200: '#dceefd',
300: '#c1e8ff',
400: '#99dfff',
500: '#6fc8ff',
600: '#48afff',
700: '#2e88e6',
800: '#2360b3',
900: '#153d80',
950: '#071d40'
},
periwinkleCream: {
50: '#fbfbff',
100: '#f2f3ff',
200: '#e7eaff',
300: '#d2dcff',
400: '#b9c9ff',
500: '#9fb2ff',
600: '#7f97ff',
700: '#5f78e6',
800: '#4559b3',
900: '#2b387f',
950: '#151c40'
},
pastelRoyalBlue: {
50: '#f6fbff',
100: '#eef6ff',
200: '#dbeeff',
300: '#b9ddff',
400: '#92c7ff',
500: '#63aaff',
600: '#3b88ff',
700: '#2e66cc',
800: '#235099',
900: '#183366',
950: '#0d1a33'
},
lavenderDream: {
50: '#fbf7ff',
100: '#f6eeff',
200: '#ebdcff',
300: '#dcc0ff',
400: '#caa1ff',
500: '#b47fff',
600: '#9366e6',
700: '#6f45b3',
800: '#4c2f80',
900: '#2d1b4f',
950: '#15082a'
},
dustyNeutral: {
50: '#faf9f7',
100: '#f3f1ed',
200: '#e8e3db',
300: '#d8cfc2',
400: '#c4b5a3',
500: '#b39c85',
600: '#a28a70',
700: '#87725d',
800: '#6f5e4e',
900: '#5a4e42',
950: '#2f2821'
}
};
if (!Aura.primitive) {
Aura.primitive = {};
}
Object.assign(Aura.primitive, customPalettes);
export default Aura;
@@ -0,0 +1,43 @@
import {BookType} from '../../features/book/model/book.model';
import {ALL_COMIC_METADATA_FIELDS} from './metadata-field.config';
const EBOOK_EMBEDDABLE: ReadonlySet<string> = new Set([
'title', 'subtitle', 'authors', 'publisher', 'publishedDate', 'language',
'categories', 'description', 'seriesName', 'seriesNumber', 'seriesTotal',
'isbn10', 'isbn13', 'moods', 'tags', 'ageRating', 'contentRating', 'pageCount',
'asin', 'amazonRating', 'amazonReviewCount', 'googleId',
'goodreadsId', 'goodreadsRating', 'goodreadsReviewCount',
'hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount',
'lubimyczytacId', 'lubimyczytacRating',
'comicvineId', 'ranobedbId', 'ranobedbRating',
'audibleId', 'audibleRating', 'audibleReviewCount',
]);
const CBX_EMBEDDABLE: ReadonlySet<string> = new Set([
'title', 'description', 'publisher', 'publishedDate', 'language',
'authors', 'categories', 'tags', 'seriesName', 'seriesNumber', 'seriesTotal',
'pageCount', 'isbn13', 'ageRating',
...ALL_COMIC_METADATA_FIELDS.map(f => f.controlName),
]);
const AUDIOBOOK_EMBEDDABLE: ReadonlySet<string> = new Set([
'title', 'authors', 'narrator', 'description', 'publisher', 'publishedDate',
'categories', 'language', 'seriesName', 'seriesNumber', 'seriesTotal',
]);
const EMBEDDABLE_FIELDS: Partial<Record<BookType, ReadonlySet<string>>> = {
EPUB: EBOOK_EMBEDDABLE,
PDF: EBOOK_EMBEDDABLE,
CBX: CBX_EMBEDDABLE,
AUDIOBOOK: AUDIOBOOK_EMBEDDABLE,
};
export function isFieldEmbeddable(bookType: BookType | undefined, controlName: string): boolean {
if (!bookType) return false;
return EMBEDDABLE_FIELDS[bookType]?.has(controlName) ?? false;
}
export function hasMetadataWriter(bookType: BookType | undefined): boolean {
if (!bookType) return false;
return bookType in EMBEDDABLE_FIELDS;
}
@@ -0,0 +1,4 @@
export * from './metadata-field.config';
export * from './metadata-utils.service';
export * from './metadata-form.builder';
export * from './embeddable-fields.config';
@@ -0,0 +1,176 @@
import { MetadataProviderSpecificFields } from '../model/app-settings.model';
export type FieldType = 'string' | 'number' | 'array' | 'textarea' | 'boolean';
export interface MetadataFieldConfig {
label: string;
controlName: string;
lockedKey: string;
fetchedKey: string;
type: FieldType;
providerKey?: keyof MetadataProviderSpecificFields;
}
export const ALL_METADATA_FIELDS: MetadataFieldConfig[] = [
{ label: 'Title', controlName: 'title', lockedKey: 'titleLocked', fetchedKey: 'title', type: 'string' },
{ label: 'Subtitle', controlName: 'subtitle', lockedKey: 'subtitleLocked', fetchedKey: 'subtitle', type: 'string' },
{ label: 'Publisher', controlName: 'publisher', lockedKey: 'publisherLocked', fetchedKey: 'publisher', type: 'string' },
{ label: 'Published', controlName: 'publishedDate', lockedKey: 'publishedDateLocked', fetchedKey: 'publishedDate', type: 'string' },
{ label: 'Authors', controlName: 'authors', lockedKey: 'authorsLocked', fetchedKey: 'authors', type: 'array' },
{ label: 'Genres', controlName: 'categories', lockedKey: 'categoriesLocked', fetchedKey: 'categories', type: 'array' },
{ label: 'Moods', controlName: 'moods', lockedKey: 'moodsLocked', fetchedKey: 'moods', type: 'array' },
{ label: 'Tags', controlName: 'tags', lockedKey: 'tagsLocked', fetchedKey: 'tags', type: 'array' },
{ label: 'Description', controlName: 'description', lockedKey: 'descriptionLocked', fetchedKey: 'description', type: 'textarea' },
{ label: 'Series', controlName: 'seriesName', lockedKey: 'seriesNameLocked', fetchedKey: 'seriesName', type: 'string' },
{ label: 'Book #', controlName: 'seriesNumber', lockedKey: 'seriesNumberLocked', fetchedKey: 'seriesNumber', type: 'number' },
{ label: 'Total Books', controlName: 'seriesTotal', lockedKey: 'seriesTotalLocked', fetchedKey: 'seriesTotal', type: 'number' },
{ label: 'Language', controlName: 'language', lockedKey: 'languageLocked', fetchedKey: 'language', type: 'string' },
{ label: 'ISBN-10', controlName: 'isbn10', lockedKey: 'isbn10Locked', fetchedKey: 'isbn10', type: 'string' },
{ label: 'ISBN-13', controlName: 'isbn13', lockedKey: 'isbn13Locked', fetchedKey: 'isbn13', type: 'string' },
{ label: 'Pages', controlName: 'pageCount', lockedKey: 'pageCountLocked', fetchedKey: 'pageCount', type: 'number' },
{ label: 'Google ID', controlName: 'googleId', lockedKey: 'googleIdLocked', fetchedKey: 'googleId', type: 'string', providerKey: 'googleId' },
{ label: 'ASIN', controlName: 'asin', lockedKey: 'asinLocked', fetchedKey: 'asin', type: 'string', providerKey: 'asin' },
{ label: 'Amazon #', controlName: 'amazonReviewCount', lockedKey: 'amazonReviewCountLocked', fetchedKey: 'amazonReviewCount', type: 'number', providerKey: 'amazonReviewCount' },
{ label: 'Amazon ★', controlName: 'amazonRating', lockedKey: 'amazonRatingLocked', fetchedKey: 'amazonRating', type: 'number', providerKey: 'amazonRating' },
{ label: 'Goodreads ID', controlName: 'goodreadsId', lockedKey: 'goodreadsIdLocked', fetchedKey: 'goodreadsId', type: 'string', providerKey: 'goodreadsId' },
{ label: 'Goodreads #', controlName: 'goodreadsReviewCount', lockedKey: 'goodreadsReviewCountLocked', fetchedKey: 'goodreadsReviewCount', type: 'number', providerKey: 'goodreadsReviewCount' },
{ label: 'Goodreads ★', controlName: 'goodreadsRating', lockedKey: 'goodreadsRatingLocked', fetchedKey: 'goodreadsRating', type: 'number', providerKey: 'goodreadsRating' },
{ label: 'HC Book ID', controlName: 'hardcoverBookId', lockedKey: 'hardcoverBookIdLocked', fetchedKey: 'hardcoverBookId', type: 'number', providerKey: 'hardcoverBookId' },
{ label: 'Hardcover ID', controlName: 'hardcoverId', lockedKey: 'hardcoverIdLocked', fetchedKey: 'hardcoverId', type: 'string', providerKey: 'hardcoverId' },
{ label: 'Hardcover #', controlName: 'hardcoverReviewCount', lockedKey: 'hardcoverReviewCountLocked', fetchedKey: 'hardcoverReviewCount', type: 'number', providerKey: 'hardcoverReviewCount' },
{ label: 'Hardcover ★', controlName: 'hardcoverRating', lockedKey: 'hardcoverRatingLocked', fetchedKey: 'hardcoverRating', type: 'number', providerKey: 'hardcoverRating' },
{ label: 'Comicvine ID', controlName: 'comicvineId', lockedKey: 'comicvineIdLocked', fetchedKey: 'comicvineId', type: 'string', providerKey: 'comicvineId' },
{ label: 'LB ID', controlName: 'lubimyczytacId', lockedKey: 'lubimyczytacIdLocked', fetchedKey: 'lubimyczytacId', type: 'string', providerKey: 'lubimyczytacId' },
{ label: 'LB ★', controlName: 'lubimyczytacRating', lockedKey: 'lubimyczytacRatingLocked', fetchedKey: 'lubimyczytacRating', type: 'number', providerKey: 'lubimyczytacRating' },
{ label: 'Ranobedb ID', controlName: 'ranobedbId', lockedKey: 'ranobedbIdLocked', fetchedKey: 'ranobedbId', type: 'string', providerKey: 'ranobedbId' },
{ label: 'Ranobedb ★', controlName: 'ranobedbRating', lockedKey: 'ranobedbRatingLocked', fetchedKey: 'ranobedbRating', type: 'number', providerKey: 'ranobedbRating' },
{ label: 'Audible ID', controlName: 'audibleId', lockedKey: 'audibleIdLocked', fetchedKey: 'audibleId', type: 'string', providerKey: 'audibleId' },
{ label: 'Audible ★', controlName: 'audibleRating', lockedKey: 'audibleRatingLocked', fetchedKey: 'audibleRating', type: 'number', providerKey: 'audibleRating' },
{ label: 'Audible #', controlName: 'audibleReviewCount', lockedKey: 'audibleReviewCountLocked', fetchedKey: 'audibleReviewCount', type: 'number', providerKey: 'audibleReviewCount' }
];
// Audiobook content metadata fields (narrator/abridged) - now stored at top level of BookMetadata
export const AUDIOBOOK_METADATA_FIELDS: MetadataFieldConfig[] = [
{ label: 'Narrator', controlName: 'narrator', lockedKey: 'narratorLocked', fetchedKey: 'narrator', type: 'string' },
{ label: 'Abridged', controlName: 'abridged', lockedKey: 'abridgedLocked', fetchedKey: 'abridged', type: 'boolean' }
];
// Comic book metadata fields - stored nested under BookMetadata.comicMetadata
export const COMIC_TEXT_METADATA_FIELDS: MetadataFieldConfig[] = [
{ label: 'Issue #', controlName: 'comicIssueNumber', lockedKey: 'comicIssueNumberLocked', fetchedKey: 'issueNumber', type: 'string' },
{ label: 'Volume', controlName: 'comicVolumeName', lockedKey: 'comicVolumeNameLocked', fetchedKey: 'volumeName', type: 'string' },
{ label: 'Volume #', controlName: 'comicVolumeNumber', lockedKey: 'comicVolumeNumberLocked', fetchedKey: 'volumeNumber', type: 'number' },
{ label: 'Story Arc', controlName: 'comicStoryArc', lockedKey: 'comicStoryArcLocked', fetchedKey: 'storyArc', type: 'string' },
{ label: 'Arc #', controlName: 'comicStoryArcNumber', lockedKey: 'comicStoryArcNumberLocked', fetchedKey: 'storyArcNumber', type: 'number' },
{ label: 'Alt. Series', controlName: 'comicAlternateSeries', lockedKey: 'comicAlternateSeriesLocked', fetchedKey: 'alternateSeries', type: 'string' },
{ label: 'Alt. Issue', controlName: 'comicAlternateIssue', lockedKey: 'comicAlternateIssueLocked', fetchedKey: 'alternateIssue', type: 'string' },
{ label: 'Imprint', controlName: 'comicImprint', lockedKey: 'comicImprintLocked', fetchedKey: 'imprint', type: 'string' },
{ label: 'Format', controlName: 'comicFormat', lockedKey: 'comicFormatLocked', fetchedKey: 'format', type: 'string' },
{ label: 'Reading Dir.', controlName: 'comicReadingDirection', lockedKey: 'comicReadingDirectionLocked', fetchedKey: 'readingDirection', type: 'string' },
{ label: 'Web Link', controlName: 'comicWebLink', lockedKey: 'comicWebLinkLocked', fetchedKey: 'webLink', type: 'string' },
{ label: 'B&W', controlName: 'comicBlackAndWhite', lockedKey: 'comicBlackAndWhiteLocked', fetchedKey: 'blackAndWhite', type: 'boolean' },
{ label: 'Manga', controlName: 'comicManga', lockedKey: 'comicMangaLocked', fetchedKey: 'manga', type: 'boolean' },
];
export const COMIC_ARRAY_METADATA_FIELDS: MetadataFieldConfig[] = [
{ label: 'Pencillers', controlName: 'comicPencillers', lockedKey: 'comicPencillersLocked', fetchedKey: 'pencillers', type: 'array' },
{ label: 'Inkers', controlName: 'comicInkers', lockedKey: 'comicInkersLocked', fetchedKey: 'inkers', type: 'array' },
{ label: 'Colorists', controlName: 'comicColorists', lockedKey: 'comicColoristsLocked', fetchedKey: 'colorists', type: 'array' },
{ label: 'Letterers', controlName: 'comicLetterers', lockedKey: 'comicLetterersLocked', fetchedKey: 'letterers', type: 'array' },
{ label: 'Cover Artists', controlName: 'comicCoverArtists', lockedKey: 'comicCoverArtistsLocked', fetchedKey: 'coverArtists', type: 'array' },
{ label: 'Editors', controlName: 'comicEditors', lockedKey: 'comicEditorsLocked', fetchedKey: 'editors', type: 'array' },
{ label: 'Characters', controlName: 'comicCharacters', lockedKey: 'comicCharactersLocked', fetchedKey: 'characters', type: 'array' },
{ label: 'Teams', controlName: 'comicTeams', lockedKey: 'comicTeamsLocked', fetchedKey: 'teams', type: 'array' },
{ label: 'Locations', controlName: 'comicLocations', lockedKey: 'comicLocationsLocked', fetchedKey: 'locations', type: 'array' },
];
export const COMIC_TEXTAREA_METADATA_FIELDS: MetadataFieldConfig[] = [
{ label: 'Notes', controlName: 'comicNotes', lockedKey: 'comicNotesLocked', fetchedKey: 'notes', type: 'textarea' },
];
export const ALL_COMIC_METADATA_FIELDS: MetadataFieldConfig[] = [
...COMIC_TEXT_METADATA_FIELDS,
...COMIC_ARRAY_METADATA_FIELDS,
...COMIC_TEXTAREA_METADATA_FIELDS,
];
// Maps form lockedKey → ComicMetadata lock property name (1:1 per-field locks).
export const COMIC_FORM_TO_MODEL_LOCK: Record<string, string> = {
'comicIssueNumberLocked': 'issueNumberLocked',
'comicVolumeNameLocked': 'volumeNameLocked',
'comicVolumeNumberLocked': 'volumeNumberLocked',
'comicStoryArcLocked': 'storyArcLocked',
'comicStoryArcNumberLocked': 'storyArcNumberLocked',
'comicAlternateSeriesLocked': 'alternateSeriesLocked',
'comicAlternateIssueLocked': 'alternateIssueLocked',
'comicImprintLocked': 'imprintLocked',
'comicFormatLocked': 'formatLocked',
'comicBlackAndWhiteLocked': 'blackAndWhiteLocked',
'comicMangaLocked': 'mangaLocked',
'comicReadingDirectionLocked': 'readingDirectionLocked',
'comicWebLinkLocked': 'webLinkLocked',
'comicNotesLocked': 'notesLocked',
'comicPencillersLocked': 'pencillersLocked',
'comicInkersLocked': 'inkersLocked',
'comicColoristsLocked': 'coloristsLocked',
'comicLetterersLocked': 'letterersLocked',
'comicCoverArtistsLocked': 'coverArtistsLocked',
'comicEditorsLocked': 'editorsLocked',
'comicCharactersLocked': 'charactersLocked',
'comicTeamsLocked': 'teamsLocked',
'comicLocationsLocked': 'locationsLocked',
};
export const TOP_FIELD_NAMES = ['title', 'subtitle', 'publisher', 'publishedDate'];
export const ARRAY_FIELD_NAMES = ['authors', 'categories', 'moods', 'tags'];
export const TEXTAREA_FIELD_NAMES = ['description'];
export const SERIES_FIELD_NAMES = ['seriesName', 'seriesNumber', 'seriesTotal'];
export const BOOK_DETAILS_FIELD_NAMES = ['language', 'isbn10', 'isbn13', 'pageCount'];
export function getTopFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => TOP_FIELD_NAMES.includes(f.controlName));
}
export function getArrayFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => f.type === 'array');
}
export function getTextareaFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => f.type === 'textarea');
}
export function getSeriesFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => SERIES_FIELD_NAMES.includes(f.controlName));
}
export function getBookDetailsFields(): MetadataFieldConfig[] {
return ALL_METADATA_FIELDS.filter(f => BOOK_DETAILS_FIELD_NAMES.includes(f.controlName));
}
export function getProviderFields(enabledProviderFields?: MetadataProviderSpecificFields | null): MetadataFieldConfig[] {
const providerFields = ALL_METADATA_FIELDS.filter(f => !!f.providerKey);
if (enabledProviderFields) {
return providerFields.filter(field =>
!field.providerKey || enabledProviderFields[field.providerKey]
);
}
return providerFields;
}
export function getBottomFields(enabledProviderFields?: MetadataProviderSpecificFields | null): MetadataFieldConfig[] {
const bottomFields = ALL_METADATA_FIELDS.filter(f =>
!TOP_FIELD_NAMES.includes(f.controlName) &&
!ARRAY_FIELD_NAMES.includes(f.controlName) &&
!TEXTAREA_FIELD_NAMES.includes(f.controlName)
);
if (enabledProviderFields) {
return bottomFields.filter(field =>
!field.providerKey || enabledProviderFields[field.providerKey]
);
}
return bottomFields;
}
@@ -0,0 +1,112 @@
import {Injectable} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
import {ALL_COMIC_METADATA_FIELDS, ALL_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, MetadataFieldConfig} from './metadata-field.config';
@Injectable({
providedIn: 'root'
})
export class MetadataFormBuilder {
buildForm(
includeLockedControls: boolean = true,
fields: MetadataFieldConfig[] = ALL_METADATA_FIELDS
): FormGroup {
const controls: Record<string, FormControl> = {};
for (const field of fields) {
const defaultValue = this.getDefaultValue(field.type);
controls[field.controlName] = new FormControl(defaultValue);
if (includeLockedControls) {
controls[field.lockedKey] = new FormControl(false);
}
}
// Add audiobook-specific metadata fields
for (const field of AUDIOBOOK_METADATA_FIELDS) {
const defaultValue = this.getDefaultValue(field.type);
controls[field.controlName] = new FormControl(defaultValue);
if (includeLockedControls) {
controls[field.lockedKey] = new FormControl(false);
}
}
// Add comic book metadata fields
for (const field of ALL_COMIC_METADATA_FIELDS) {
const defaultValue = this.getDefaultValue(field.type);
controls[field.controlName] = new FormControl(defaultValue);
if (includeLockedControls) {
controls[field.lockedKey] = new FormControl(false);
}
}
controls['thumbnailUrl'] = new FormControl('');
controls['audiobookThumbnailUrl'] = new FormControl('');
if (includeLockedControls) {
controls['coverLocked'] = new FormControl(false);
controls['audiobookCoverLocked'] = new FormControl(false);
}
return new FormGroup(controls);
}
private getDefaultValue(type: string): unknown {
switch (type) {
case 'array':
return [];
case 'number':
return null;
case 'boolean':
return null;
default:
return '';
}
}
applyLockStates(
metadataForm: FormGroup,
lockedFields: Record<string, boolean>,
fields: MetadataFieldConfig[] = ALL_METADATA_FIELDS
): void {
for (const key of Object.keys(metadataForm.controls)) {
if (!key.endsWith('Locked')) {
metadataForm.get(key)?.enable({emitEvent: false});
}
}
// Apply locks for standard fields
for (const field of fields) {
if (lockedFields[field.lockedKey]) {
metadataForm.get(field.controlName)?.disable({emitEvent: false});
}
}
// Apply locks for audiobook metadata fields
for (const field of AUDIOBOOK_METADATA_FIELDS) {
if (lockedFields[field.lockedKey]) {
metadataForm.get(field.controlName)?.disable({emitEvent: false});
}
}
// Apply locks for comic book metadata fields
for (const field of ALL_COMIC_METADATA_FIELDS) {
if (lockedFields[field.lockedKey]) {
metadataForm.get(field.controlName)?.disable({emitEvent: false});
}
}
}
setAllFieldsLocked(metadataForm: FormGroup, locked: boolean): void {
for (const key of Object.keys(metadataForm.controls)) {
if (key.endsWith('Locked')) {
metadataForm.get(key)?.setValue(locked);
const fieldName = key.replace('Locked', '');
if (locked) {
metadataForm.get(fieldName)?.disable();
} else {
metadataForm.get(fieldName)?.enable();
}
}
}
}
}
@@ -0,0 +1,150 @@
import {Injectable} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {BookMetadata} from '../../features/book/model/book.model';
@Injectable({
providedIn: 'root'
})
export class MetadataUtilsService {
copyFieldToForm(
field: string,
fetchedMetadata: BookMetadata,
metadataForm: FormGroup,
copiedFields: Record<string, boolean>
): boolean {
const value = fetchedMetadata[field as keyof BookMetadata];
if (value !== null && value !== undefined && value !== '') {
metadataForm.get(field)?.setValue(value);
copiedFields[field] = true;
return true;
}
return false;
}
copyMissingFields(
fetchedMetadata: BookMetadata,
metadataForm: FormGroup,
copiedFields: Record<string, boolean>,
copyCallback: (field: string) => void
): void {
for (const field of Object.keys(fetchedMetadata)) {
const isLocked = metadataForm.get(`${field}Locked`)?.value;
const currentValue = metadataForm.get(field)?.value;
const fetchedValue = fetchedMetadata[field as keyof BookMetadata];
const isEmpty = Array.isArray(currentValue)
? currentValue.length === 0
: (currentValue === null || currentValue === undefined || currentValue === '');
const hasFetchedValue = fetchedValue !== null && fetchedValue !== undefined && fetchedValue !== '';
if (!isLocked && isEmpty && hasFetchedValue) {
copyCallback(field);
}
}
}
copyAllFields(
fetchedMetadata: BookMetadata,
metadataForm: FormGroup,
copyCallback: (field: string) => void,
excludeFields: string[] = ['thumbnailUrl', 'bookId']
): void {
for (const field of Object.keys(fetchedMetadata)) {
if (excludeFields.includes(field)) continue;
const isLocked = metadataForm.get(`${field}Locked`)?.value;
const fetchedValue = fetchedMetadata[field as keyof BookMetadata];
if (!isLocked && fetchedValue != null && fetchedValue !== '') {
copyCallback(field);
}
}
}
isValueEmpty(value: unknown): boolean {
if (value === null || value === undefined || value === '') return true;
if (Array.isArray(value)) return value.length === 0;
return false;
}
areFieldsEqual(field1: unknown, field2: unknown): boolean {
const [normalized1, normalized2] = this.normalizeForComparison(field1, field2);
return normalized1 === normalized2;
}
normalizeForComparison(field1: unknown, field2: unknown): [string | undefined, string | undefined] {
let val1: string | undefined = undefined;
let val2: string | undefined = undefined;
if (Array.isArray(field1)) {
val1 = field1.length > 0 ? JSON.stringify([...field1].sort()) : undefined;
} else if (field1 != null && field1 !== '') {
val1 = String(field1);
}
if (Array.isArray(field2)) {
val2 = field2.length > 0 ? JSON.stringify([...field2].sort()) : undefined;
} else if (field2 != null && field2 !== '') {
val2 = String(field2);
}
return [val1, val2];
}
isValueChanged(field: string, metadataForm: FormGroup, originalMetadata?: BookMetadata): boolean {
if (!originalMetadata) return false;
const [current, original] = this.normalizeForComparison(
metadataForm.get(field)?.value,
originalMetadata[field as keyof BookMetadata]
);
return (!!current && current !== original) || (!current && !!original);
}
isFetchedDifferent(field: string, metadataForm: FormGroup, fetchedMetadata: BookMetadata): boolean {
const [current, fetched] = this.normalizeForComparison(
metadataForm.get(field)?.value,
fetchedMetadata[field as keyof BookMetadata]
);
return !!fetched && fetched !== current;
}
resetField(
field: string,
metadataForm: FormGroup,
originalMetadata: BookMetadata | undefined,
copiedFields: Record<string, boolean>,
hoveredFields?: Record<string, boolean>
): void {
// All fields including narrator/abridged are now at top level of BookMetadata
metadataForm.get(field)?.setValue(originalMetadata?.[field as keyof BookMetadata]);
copiedFields[field] = false;
if (hoveredFields) {
hoveredFields[field] = false;
}
}
patchMetadataToForm(
metadata: BookMetadata,
metadataForm: FormGroup,
fields: Array<{ controlName: string; lockedKey: string; type: string }>
): void {
const patchData: Record<string, unknown> = {};
for (const field of fields) {
const key = field.controlName as keyof BookMetadata;
const lockedKey = field.lockedKey as keyof BookMetadata;
const value = metadata[key];
if (field.type === 'array') {
patchData[field.controlName] = [...(value as string[] ?? [])].sort();
} else {
patchData[field.controlName] = value ?? null;
}
patchData[field.lockedKey] = metadata[lockedKey] ?? false;
}
metadataForm.patchValue(patchData);
}
}
@@ -0,0 +1,248 @@
import {MetadataRefreshOptions} from '../../features/metadata/model/request/metadata-refresh-options.model';
export interface MetadataMatchWeights {
title: number;
subtitle: number;
description: number;
authors: number;
publisher: number;
publishedDate: number;
seriesName: number;
seriesNumber: number;
seriesTotal: number;
isbn13: number;
isbn10: number;
language: number;
pageCount: number;
categories: number;
amazonRating: number;
amazonReviewCount: number;
goodreadsRating: number;
goodreadsReviewCount: number;
hardcoverRating: number;
hardcoverReviewCount: number;
doubanRating: number;
doubanReviewCount: number;
lubimyczytacRating: number;
ranobedbRating: number;
audibleRating: number;
audibleReviewCount: number;
coverImage: number;
}
export interface OidcProviderDetails {
providerName: string;
clientId: string;
clientSecret?: string;
issuerUri: string;
scopes?: string;
claimMapping: {
username: string;
email: string;
name: string;
groups: string;
};
}
export interface OidcAutoProvisionDetails {
enableAutoProvisioning: boolean;
allowLocalAccountLinking: boolean;
defaultPermissions: string[];
defaultLibraryIds: number[];
}
export interface MetadataProviderSettings {
amazon: Amazon;
google: Google;
goodReads: Goodreads;
ranobedb: Ranobedb;
hardcover: Hardcover;
comicvine: Comicvine;
douban: Douban;
lubimyczytac: Lubimyczytac;
audible: Audible;
}
export interface Amazon {
enabled: boolean;
cookie: string;
domain: string;
}
export interface Google {
enabled: boolean;
language: string;
apiKey: string;
}
export interface Goodreads {
enabled: boolean;
}
export interface Ranobedb {
enabled: boolean;
}
export interface Hardcover {
enabled: boolean;
apiKey: string;
}
export interface Comicvine {
enabled: boolean;
apiKey: string;
}
export interface Douban {
enabled: boolean;
}
export interface Lubimyczytac {
enabled: boolean;
}
export interface Audible {
enabled: boolean;
domain: string;
}
export interface FormatWriteSettings {
enabled: boolean;
maxFileSizeInMb: number;
}
export interface SaveToOriginalFileSettings {
epub: FormatWriteSettings;
pdf: FormatWriteSettings;
cbx: FormatWriteSettings;
audiobook: FormatWriteSettings;
}
export interface SidecarSettings {
enabled: boolean;
writeOnUpdate: boolean;
writeOnScan: boolean;
includeCoverFile: boolean;
}
export interface MetadataPersistenceSettings {
moveFilesToLibraryPattern: boolean;
saveToOriginalFile: SaveToOriginalFileSettings;
convertCbrCb7ToCbz: boolean;
sidecarSettings?: SidecarSettings;
}
export interface ReviewProviderConfig {
provider: string;
enabled: boolean;
maxReviews: number;
}
export interface PublicReviewSettings {
downloadEnabled: boolean;
autoDownloadEnabled: boolean;
providers: ReviewProviderConfig[];
}
export interface KoboSettings {
convertToKepub: boolean;
conversionLimitInMb: number;
conversionImageCompressionPercentage: number;
convertCbxToEpub: boolean;
conversionLimitInMbForCbx: number;
forceEnableHyphenation: boolean;
}
export interface CoverCroppingSettings {
verticalCroppingEnabled: boolean;
horizontalCroppingEnabled: boolean;
aspectRatioThreshold: number;
smartCroppingEnabled: boolean;
}
export interface OidcTestCheck {
name: string;
status: 'PASS' | 'FAIL' | 'WARN' | 'SKIP';
message: string;
}
export interface OidcTestResult {
success: boolean;
checks: OidcTestCheck[];
}
export interface AppSettings {
autoBookSearch: boolean;
similarBookRecommendation: boolean;
defaultMetadataRefreshOptions: MetadataRefreshOptions;
libraryMetadataRefreshOptions: MetadataRefreshOptions[];
uploadPattern: string;
opdsServerEnabled: boolean;
komgaApiEnabled: boolean;
komgaGroupUnknown: boolean;
remoteAuthEnabled: boolean;
oidcEnabled: boolean;
oidcProviderDetails: OidcProviderDetails;
oidcAutoProvisionDetails: OidcAutoProvisionDetails;
maxFileUploadSizeInMb: number;
metadataProviderSettings: MetadataProviderSettings;
metadataMatchWeights: MetadataMatchWeights;
metadataPersistenceSettings: MetadataPersistenceSettings;
metadataPublicReviewsSettings: PublicReviewSettings;
koboSettings: KoboSettings;
coverCroppingSettings: CoverCroppingSettings;
metadataDownloadOnBookdrop: boolean;
metadataProviderSpecificFields: MetadataProviderSpecificFields;
oidcSessionDurationHours: number | null;
oidcGroupSyncMode: string | null;
oidcForceOnlyMode: boolean;
diskType: string;
}
export interface MetadataProviderSpecificFields {
asin: boolean;
amazonRating: boolean;
amazonReviewCount: boolean;
googleId: boolean;
goodreadsId: boolean;
goodreadsRating: boolean;
goodreadsReviewCount: boolean;
hardcoverId: boolean;
hardcoverBookId: boolean;
hardcoverRating: boolean;
hardcoverReviewCount: boolean;
comicvineId: boolean;
lubimyczytacId: boolean;
lubimyczytacRating: boolean;
ranobedbId: boolean;
ranobedbRating: boolean;
audibleId: boolean;
audibleRating: boolean;
audibleReviewCount: boolean;
}
export enum AppSettingKey {
QUICK_BOOK_MATCH = 'QUICK_BOOK_MATCH',
AUTO_BOOK_SEARCH = 'AUTO_BOOK_SEARCH',
SIMILAR_BOOK_RECOMMENDATION = 'SIMILAR_BOOK_RECOMMENDATION',
LIBRARY_METADATA_REFRESH_OPTIONS = 'LIBRARY_METADATA_REFRESH_OPTIONS',
UPLOAD_FILE_PATTERN = 'UPLOAD_FILE_PATTERN',
OPDS_SERVER_ENABLED = 'OPDS_SERVER_ENABLED',
KOMGA_API_ENABLED = 'KOMGA_API_ENABLED',
KOMGA_GROUP_UNKNOWN = 'KOMGA_GROUP_UNKNOWN',
OIDC_ENABLED = 'OIDC_ENABLED',
OIDC_PROVIDER_DETAILS = 'OIDC_PROVIDER_DETAILS',
OIDC_AUTO_PROVISION_DETAILS = 'OIDC_AUTO_PROVISION_DETAILS',
MAX_FILE_UPLOAD_SIZE_IN_MB = 'MAX_FILE_UPLOAD_SIZE_IN_MB',
METADATA_PROVIDER_SETTINGS = 'METADATA_PROVIDER_SETTINGS',
METADATA_MATCH_WEIGHTS = 'METADATA_MATCH_WEIGHTS',
METADATA_PERSISTENCE_SETTINGS = 'METADATA_PERSISTENCE_SETTINGS',
METADATA_DOWNLOAD_ON_BOOKDROP = 'METADATA_DOWNLOAD_ON_BOOKDROP',
METADATA_PUBLIC_REVIEWS_SETTINGS = 'METADATA_PUBLIC_REVIEWS_SETTINGS',
KOBO_SETTINGS = 'KOBO_SETTINGS',
COVER_CROPPING_SETTINGS = 'COVER_CROPPING_SETTINGS',
METADATA_PROVIDER_SPECIFIC_FIELDS = 'METADATA_PROVIDER_SPECIFIC_FIELDS',
OIDC_SESSION_DURATION_HOURS = 'OIDC_SESSION_DURATION_HOURS',
OIDC_GROUP_SYNC_MODE = 'OIDC_GROUP_SYNC_MODE',
OIDC_FORCE_ONLY_MODE = 'OIDC_FORCE_ONLY_MODE',
}
@@ -0,0 +1,5 @@
export interface AppState {
preset?: string;
primary?: string;
surface?: string;
}
@@ -0,0 +1,23 @@
export interface CustomFont {
id: number;
fontName: string;
originalFileName: string;
format: FontFormat;
fileSize: number;
uploadedAt: string;
}
export enum FontFormat {
TTF = 'TTF',
OTF = 'OTF',
WOFF = 'WOFF',
WOFF2 = 'WOFF2'
}
export function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
@@ -0,0 +1,22 @@
export enum MetadataBatchStatus {
IN_PROGRESS = 'IN_PROGRESS',
COMPLETED = 'COMPLETED',
ERROR = 'ERROR',
CANCELLED = 'CANCELLED',
}
export const MetadataBatchStatusLabels: Record<MetadataBatchStatus, string> = {
[MetadataBatchStatus.IN_PROGRESS]: 'In Progress',
[MetadataBatchStatus.COMPLETED]: 'Completed',
[MetadataBatchStatus.ERROR]: 'Error',
[MetadataBatchStatus.CANCELLED]: 'Cancelled',
};
export interface MetadataBatchProgressNotification {
taskId: string;
completed: number;
total: number;
message: string;
status: MetadataBatchStatus;
review: boolean;
}
@@ -0,0 +1,8 @@
export interface OidcGroupMapping {
id?: number;
oidcGroupClaim: string;
isAdmin: boolean;
permissions: string[];
libraryIds: number[];
description: string;
}
@@ -0,0 +1,6 @@
export interface APIException {
status: number;
message: string;
timestamp?: string;
error?: string;
}
@@ -0,0 +1,61 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export type AnnotationStyle = 'highlight' | 'underline' | 'strikethrough' | 'squiggly';
export interface Annotation {
id: number;
userId?: number;
bookId: number;
cfi: string;
text: string;
color: string;
style: AnnotationStyle;
note?: string;
chapterTitle?: string;
createdAt: string;
updatedAt?: string;
}
export interface CreateAnnotationRequest {
bookId: number;
cfi: string;
text: string;
color?: string;
style?: AnnotationStyle;
note?: string;
chapterTitle?: string;
}
export interface UpdateAnnotationRequest {
color?: string;
style?: AnnotationStyle;
note?: string;
}
@Injectable({
providedIn: 'root'
})
export class AnnotationService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/annotations`;
private readonly http = inject(HttpClient);
getAnnotationsForBook(bookId: number): Observable<Annotation[]> {
return this.http.get<Annotation[]>(`${this.url}/book/${bookId}`);
}
createAnnotation(request: CreateAnnotationRequest): Observable<Annotation> {
return this.http.post<Annotation>(this.url, request);
}
deleteAnnotation(annotationId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${annotationId}`);
}
updateAnnotation(annotationId: number, request: UpdateAnnotationRequest): Observable<Annotation> {
return this.http.put<Annotation>(`${this.url}/${annotationId}`, request);
}
}
@@ -0,0 +1,435 @@
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { effect, inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
import { $t, updatePreset, updateSurfacePalette } from '@primeuix/themes';
import Aura from '@primeuix/themes/aura';
import { AppState } from '../model/app-state.model';
type ColorPalette = Record<string, string>;
interface Palette {
name: string;
palette: ColorPalette;
}
@Injectable({
providedIn: 'root',
})
export class AppConfigService {
private readonly STORAGE_KEY = 'appConfigState';
appState = signal<AppState>({});
document = inject(DOCUMENT);
platformId = inject(PLATFORM_ID);
private initialized = false;
readonly surfaces: Palette[] = [
{
name: 'slate',
palette: {
0: '#ffffff',
50: '#f8fafc',
100: '#f1f5f9',
200: '#e2e8f0',
300: '#cbd5e1',
400: '#94a3b8',
500: '#64748b',
600: '#475569',
700: '#334155',
800: '#283548',
900: '#0f172a',
950: '#020617'
}
},
{
name: 'gray',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f4f4f5',
200: '#e4e4e7',
300: '#d4d4d8',
400: '#a1a1aa',
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#313136',
900: '#18181b',
950: '#09090b'
}
},
{
name: 'neutral',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#303030',
900: '#171717',
950: '#0a0a0a'
}
},
{
name: 'zinc',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f4f4f5',
200: '#e4e4e7',
300: '#d4d4d8',
400: '#a1a1aa',
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#313136',
900: '#18181b',
950: '#09090b'
}
},
{
name: 'stone',
palette: {
0: '#ffffff',
50: '#fafaf9',
100: '#f5f5f4',
200: '#e7e5e4',
300: '#d6d3d1',
400: '#a8a29e',
500: '#78716c',
600: '#57534e',
700: '#44403c',
800: '#342f2b',
900: '#1c1917',
950: '#0c0a09'
}
},
{
name: 'iron',
palette: {
0: '#ffffff',
50: '#f1f3f4',
100: '#e3e5e6',
200: '#d2d4d6',
300: '#b8bbc0',
400: '#9ca0a6',
500: '#7d8288',
600: '#646a70',
700: '#4c5258',
800: '#353a40',
900: '#1a1d20',
950: '#0d0f11'
}
},
{
name: 'steel',
palette: {
0: '#ffffff',
50: '#f3f4f6',
100: '#e5e7eb',
200: '#d1d5db',
300: '#b0b7c3',
400: '#8b93a6',
500: '#6b7280',
600: '#545861',
700: '#3f4347',
800: '#2c2f33',
900: '#16181b',
950: '#0b0d0e'
}
},
{
name: 'carbon',
palette: {
0: '#ffffff',
50: '#eef0f2',
100: '#dde1e6',
200: '#c7cdd5',
300: '#a8b0bc',
400: '#8691a0',
500: '#697080',
600: '#545a66',
700: '#41464f',
800: '#303439',
900: '#181a1d',
950: '#0c0e10'
}
},
{
name: 'ash',
palette: {
0: '#ffffff',
50: '#f4f6f8',
100: '#e6e9ed',
200: '#d3d8de',
300: '#b4bcc7',
400: '#919ca9',
500: '#71808a',
600: '#5a666f',
700: '#464f56',
800: '#34393e',
900: '#1a1e21',
950: '#0d1012'
}
},
{
name: 'smoke',
palette: {
0: '#ffffff',
50: '#f6f6f7',
100: '#ebebed',
200: '#dadadd',
300: '#bbbcc1',
400: '#989aa1',
500: '#797c84',
600: '#63666d',
700: '#4f5257',
800: '#3a3d42',
900: '#1d2023',
950: '#0e1011'
}
},
{
name: 'midnight-blue',
palette: {
0: '#ffffff',
50: '#fcfcfd',
100: '#f7f8fb',
200: '#f0f2f7',
300: '#e5e8f0',
400: '#d3d8e3',
500: '#5c6b7a',
600: '#4a5866',
700: '#3b4651',
800: '#38424d',
900: '#1f252c',
950: '#121518'
}
},
{
name: 'charcoal',
palette: {
0: '#ffffff',
50: '#f0f0f0',
100: '#e5e5e5',
200: '#d1d1d1',
300: '#b8b8b8',
400: '#9a9a9a',
500: '#7d7d7d',
600: '#666666',
700: '#525252',
800: '#3d3d3d',
900: '#242424',
950: '#141414'
}
},
{
name: 'soho',
palette: {
0: '#ffffff',
50: '#ececec',
100: '#dedfdf',
200: '#c4c4c6',
300: '#adaeb0',
400: '#97979b',
500: '#7f8084',
600: '#6a6b70',
700: '#55565b',
800: '#3f4046',
900: '#252530',
950: '#16161d'
}
},
{
name: 'viva',
palette: {
0: '#ffffff',
50: '#f3f3f3',
100: '#e7e7e8',
200: '#cfd0d0',
300: '#b7b8b9',
400: '#9fa1a1',
500: '#87898a',
600: '#6e7173',
700: '#565a5b',
800: '#3e4244',
900: '#1e2324',
950: '#0e1315'
}
},
{
name: 'ocean',
palette: {
0: '#ffffff',
50: '#fbfcfc',
100: '#F7F9F8',
200: '#EFF3F2',
300: '#DADEDD',
400: '#B1B7B6',
500: '#828787',
600: '#5F7274',
700: '#415B61',
800: '#324f5a',
900: '#183240',
950: '#0c1920'
}
},
{
name: 'light-slate',
palette: {
0: '#ffffff',
50: '#fcfcfd',
100: '#f8fafc',
200: '#f1f5f9',
300: '#e2e8f0',
400: '#cbd5e1',
500: '#94a3b8',
600: '#64748b',
700: '#475569',
800: '#3d5068',
900: '#1e293b',
950: '#0f172a'
}
},
{
name: 'olive',
palette: {
0: '#ffffff',
50: '#fcfcfb',
100: '#f8f9f6',
200: '#f1f4ed',
300: '#e6eadc',
400: '#d4dfc5',
500: '#6a755e',
600: '#555d4c',
700: '#434a3d',
800: '#3d4438',
900: '#232824',
950: '#131614'
}
},
{
name: 'crimson',
palette: {
0: '#ffffff',
50: '#fcfbfb',
100: '#f8f5f5',
200: '#f1ebeb',
300: '#e6d9d9',
400: '#d4c3c3',
500: '#755e5e',
600: '#5d4c4c',
700: '#4a3d3d',
800: '#423838',
900: '#242020',
950: '#141212'
}
}
];
constructor() {
const initialState = this.loadAppState();
this.appState.set({ ...initialState });
this.document.documentElement.classList.add('p-dark');
if (isPlatformBrowser(this.platformId)) {
this.onPresetChange();
}
effect(() => {
const state = this.appState();
if (!this.initialized || !state) {
this.initialized = true;
return;
}
this.saveAppState(state);
this.onPresetChange();
});
}
private loadAppState(): AppState {
if (isPlatformBrowser(this.platformId)) {
const storedState = localStorage.getItem(this.STORAGE_KEY);
if (storedState) {
return JSON.parse(storedState);
}
}
return {
preset: 'Aura',
primary: 'green',
surface: 'ash',
};
}
private saveAppState(state: AppState): void {
if (isPlatformBrowser(this.platformId)) {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(state));
}
}
private getSurfacePalette(surface: string): ColorPalette {
return this.surfaces.find(s => s.name === surface)?.palette ?? {};
}
getPresetExt(): object {
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
const primaryName = this.appState().primary ?? 'green';
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
const color = presetPalette[primaryName] ?? {};
if (primaryName === 'noir') {
return {
semantic: {
primary: { ...surfacePalette },
colorScheme: {
dark: {
primary: {
color: '{primary.50}',
contrastColor: '{primary.950}',
hoverColor: '{primary.200}',
activeColor: '{primary.300}'
},
highlight: {
background: '{primary.50}',
focusBackground: '{primary.300}',
color: '{primary.950}',
focusColor: '{primary.950}'
}
}
}
}
};
}
return {
semantic: {
primary: color,
colorScheme: {
dark: {
primary: {
color: '{primary.400}',
contrastColor: '{surface.900}',
hoverColor: '{primary.300}',
activeColor: '{primary.200}'
},
highlight: {
background: 'color-mix(in srgb, {primary.400}, transparent 84%)',
focusBackground: 'color-mix(in srgb, {primary.400}, transparent 76%)',
color: 'rgba(255,255,255,.87)',
focusColor: 'rgba(255,255,255,.87)'
}
}
}
}
};
}
onPresetChange(): void {
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
const preset = this.getPresetExt();
$t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({ useDefaultOptions: true });
}
}
@@ -0,0 +1,2 @@
export const APP_SETTINGS_QUERY_KEY = ['appSettings'] as const;
export const PUBLIC_SETTINGS_QUERY_KEY = ['publicSettings'] as const;
@@ -0,0 +1,131 @@
import {computed, effect, inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {lastValueFrom, Observable, of} from 'rxjs';
import {catchError, map, switchMap} from 'rxjs/operators';
import {API_CONFIG} from '../../core/config/api-config';
import {AppSettings, OidcProviderDetails, OidcTestResult} from '../model/app-settings.model';
import {AuthService} from './auth.service';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {APP_SETTINGS_QUERY_KEY, PUBLIC_SETTINGS_QUERY_KEY} from './app-settings-query-keys';
export interface PublicAppSettings {
oidcEnabled: boolean;
remoteAuthEnabled: boolean;
oidcProviderDetails: OidcProviderDetails;
oidcForceOnlyMode: boolean;
}
@Injectable({providedIn: 'root'})
export class AppSettingsService {
private http = inject(HttpClient);
private queryClient = inject(QueryClient);
private authService = inject(AuthService);
private readonly token = this.authService.token;
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/settings`;
private readonly publicApiUrl = `${API_CONFIG.BASE_URL}/api/v1/public-settings`;
private publicSettingsQuery = injectQuery(() => ({
...this.getPublicSettingsQueryOptions(),
}));
private appSettingsQuery = injectQuery(() => ({
...this.getAppSettingsQueryOptions(),
enabled: !!this.token(),
}));
appSettings = computed(() => this.appSettingsQuery.data() ?? null);
publicAppSettings = computed(() => this.publicSettingsQuery.data() ?? null);
constructor() {
effect(() => {
const token = this.token();
if (token === null) {
this.queryClient.removeQueries({queryKey: APP_SETTINGS_QUERY_KEY});
}
});
// When authenticated settings load, keep public settings cache in sync
effect(() => {
const settings = this.appSettings();
if (settings) {
this.syncPublicSettings(settings);
}
});
}
getPublicSettingsQueryOptions() {
return queryOptions({
queryKey: PUBLIC_SETTINGS_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<PublicAppSettings>(this.publicApiUrl))
});
}
private getAppSettingsQueryOptions() {
return queryOptions({
queryKey: APP_SETTINGS_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<AppSettings>(this.apiUrl))
});
}
testOidcConnection(providerDetails: OidcProviderDetails): Observable<OidcTestResult> {
return this.http.post<OidcTestResult>(`${this.apiUrl}/oidc/test`, providerDetails);
}
private syncPublicSettings(appSettings: AppSettings): void {
const updatedPublicSettings: PublicAppSettings = {
oidcEnabled: appSettings.oidcEnabled,
remoteAuthEnabled: appSettings.remoteAuthEnabled,
oidcProviderDetails: appSettings.oidcProviderDetails,
oidcForceOnlyMode: appSettings.oidcForceOnlyMode
};
const current = this.publicAppSettings();
if (
!current ||
current.oidcEnabled !== updatedPublicSettings.oidcEnabled ||
current.remoteAuthEnabled !== updatedPublicSettings.remoteAuthEnabled ||
current.oidcForceOnlyMode !== updatedPublicSettings.oidcForceOnlyMode ||
JSON.stringify(current.oidcProviderDetails) !== JSON.stringify(updatedPublicSettings.oidcProviderDetails)
) {
this.queryClient.setQueryData(PUBLIC_SETTINGS_QUERY_KEY, updatedPublicSettings);
}
}
saveSettings(settings: { key: string; newValue: unknown }[]): Observable<void> {
const payload = settings.map(setting => ({
name: setting.key,
value: setting.newValue
}));
return this.http.put<void>(this.apiUrl, payload).pipe(
switchMap(() => {
void this.queryClient.invalidateQueries({queryKey: APP_SETTINGS_QUERY_KEY});
return of(void 0);
}),
map(() => void 0),
catchError(err => {
console.error('Error saving settings:', err);
return of();
})
);
}
toggleOidcEnabled(enabled: boolean): Observable<void> {
const payload = [{name: 'OIDC_ENABLED', value: enabled}];
return this.http.put<void>(this.apiUrl, payload).pipe(
map(() => {
const current = this.appSettings();
if (current) {
const updated = {...current, oidcEnabled: enabled};
this.queryClient.setQueryData(APP_SETTINGS_QUERY_KEY, updated);
this.syncPublicSettings(updated);
}
}),
catchError(err => {
console.error('Error toggling OIDC:', err);
return of();
})
);
}
}
@@ -0,0 +1,386 @@
import { inject, Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import {
ReadingSessionApiService,
CreateReadingSessionDto
} from './reading-session-api.service';
export interface AudiobookSession {
bookId: number;
bookFileId?: number;
sessionStartTime: Date;
totalListeningSeconds: number;
startPositionMs: number;
currentPositionMs: number;
trackIndex?: number;
playbackRate: number;
lastPlayStartTime?: Date;
}
@Injectable({
providedIn: 'root'
})
export class AudiobookSessionService {
private readonly apiService = inject(ReadingSessionApiService);
private currentSession: AudiobookSession | null = null;
private periodicSaveInterval: ReturnType<typeof setInterval> | null = null;
private readonly PERIODIC_SAVE_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
private readonly MIN_SESSION_DURATION_SECONDS = 30;
constructor() {
this.setupBrowserLifecycleListeners();
}
private setupBrowserLifecycleListeners(): void {
window.addEventListener('beforeunload', () => {
if (this.currentSession) {
this.endSessionSync();
}
});
// Note: We intentionally do NOT pause on visibility change
// Audiobooks play in the background
}
/**
* Start a new listening session when playback begins
*/
startSession(
bookId: number,
startPositionMs: number,
playbackRate: number = 1,
bookFileId?: number,
trackIndex?: number
): void {
// End any existing session first
if (this.currentSession) {
this.endSession();
}
this.currentSession = {
bookId,
bookFileId,
sessionStartTime: new Date(),
totalListeningSeconds: 0,
startPositionMs,
currentPositionMs: startPositionMs,
trackIndex,
playbackRate,
lastPlayStartTime: new Date()
};
this.log('Audiobook session started', {
bookId,
startPosition: this.formatMs(startPositionMs),
playbackRate
});
this.startPeriodicSave();
}
/**
* Called when playback is paused - accumulates listening time
*/
pauseSession(currentPositionMs: number): void {
if (!this.currentSession || !this.currentSession.lastPlayStartTime) {
return;
}
// Calculate listening time since last play
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
this.currentSession.currentPositionMs = currentPositionMs;
this.currentSession.lastPlayStartTime = undefined;
this.log('Audiobook session paused', {
addedSeconds: Math.round(adjustedDurationSeconds),
totalSeconds: Math.round(this.currentSession.totalListeningSeconds),
position: this.formatMs(currentPositionMs)
});
}
/**
* Called when playback resumes after pause
*/
resumeSession(currentPositionMs: number): void {
if (!this.currentSession) {
return;
}
this.currentSession.lastPlayStartTime = new Date();
this.currentSession.currentPositionMs = currentPositionMs;
this.log('Audiobook session resumed', {
position: this.formatMs(currentPositionMs)
});
}
/**
* Update current position (called during playback)
*/
updatePosition(currentPositionMs: number, trackIndex?: number): void {
if (!this.currentSession) {
return;
}
this.currentSession.currentPositionMs = currentPositionMs;
if (trackIndex !== undefined) {
this.currentSession.trackIndex = trackIndex;
}
}
/**
* Update playback rate
*/
updatePlaybackRate(rate: number): void {
if (!this.currentSession) {
return;
}
// If currently playing, accumulate time at old rate before changing
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
this.currentSession.lastPlayStartTime = now;
}
this.currentSession.playbackRate = rate;
this.log('Playback rate changed', { rate });
}
/**
* End the session and send to backend
*/
endSession(currentPositionMs?: number): void {
if (!this.currentSession) {
return;
}
this.stopPeriodicSave();
// If still playing, accumulate final listening time
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
}
if (currentPositionMs !== undefined) {
this.currentSession.currentPositionMs = currentPositionMs;
}
const totalSeconds = Math.round(this.currentSession.totalListeningSeconds);
if (totalSeconds >= this.MIN_SESSION_DURATION_SECONDS) {
this.sendSessionToBackend(this.currentSession);
} else {
this.log('Session too short, discarding', { totalSeconds });
}
this.currentSession = null;
}
/**
* Check if a session is currently active
*/
isSessionActive(): boolean {
return this.currentSession !== null;
}
/**
* Check if currently in playing state (not paused)
*/
isPlaying(): boolean {
return this.currentSession?.lastPlayStartTime !== undefined;
}
/**
* Get current accumulated listening time in seconds
*/
getCurrentListeningTime(): number {
if (!this.currentSession) {
return 0;
}
let total = this.currentSession.totalListeningSeconds;
// Add time since last play start if currently playing
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
total += (playDurationMs / 1000) * this.currentSession.playbackRate;
}
return Math.round(total);
}
private endSessionSync(): void {
if (!this.currentSession) {
return;
}
// Accumulate final listening time if playing
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
}
const totalSeconds = Math.round(this.currentSession.totalListeningSeconds);
if (totalSeconds < this.MIN_SESSION_DURATION_SECONDS) {
this.cleanup();
return;
}
const sessionData = this.buildSessionData(this.currentSession);
this.log('Audiobook session ended (sync)', sessionData);
const success = this.apiService.sendSessionBeacon(sessionData);
if (!success) {
this.logError('sendBeacon failed, request may not have been queued');
}
this.cleanup();
}
private startPeriodicSave(): void {
this.stopPeriodicSave();
this.periodicSaveInterval = setInterval(() => {
if (this.currentSession && this.currentSession.lastPlayStartTime) {
// Send intermediate session data
this.sendIntermediateSession();
}
}, this.PERIODIC_SAVE_INTERVAL_MS);
}
private stopPeriodicSave(): void {
if (this.periodicSaveInterval) {
clearInterval(this.periodicSaveInterval);
this.periodicSaveInterval = null;
}
}
private sendIntermediateSession(): void {
if (!this.currentSession) {
return;
}
// Calculate current total without modifying state
let totalSeconds = this.currentSession.totalListeningSeconds;
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
totalSeconds += (playDurationMs / 1000) * this.currentSession.playbackRate;
}
if (totalSeconds < this.MIN_SESSION_DURATION_SECONDS) {
return;
}
const sessionData = this.buildSessionData(this.currentSession, Math.round(totalSeconds));
this.log('Sending intermediate session', {
listeningSeconds: Math.round(totalSeconds)
});
this.apiService.createSession(sessionData).subscribe({
next: () => this.log('Intermediate session saved'),
error: (err: HttpErrorResponse) => this.logError('Failed to save intermediate session', err)
});
// Reset accumulated time after sending (to avoid double-counting)
// Keep lastPlayStartTime to continue tracking
this.currentSession.totalListeningSeconds = 0;
this.currentSession.lastPlayStartTime = new Date();
this.currentSession.startPositionMs = this.currentSession.currentPositionMs;
}
private sendSessionToBackend(session: AudiobookSession): void {
const sessionData = this.buildSessionData(session);
this.log('Audiobook session completed', sessionData);
this.apiService.createSession(sessionData).subscribe({
next: () => this.log('Session saved to backend'),
error: (err: HttpErrorResponse) => this.logError('Failed to save session', err)
});
}
private buildSessionData(session: AudiobookSession, overrideDuration?: number): CreateReadingSessionDto {
const durationSeconds = overrideDuration ?? Math.round(session.totalListeningSeconds);
const now = new Date();
// Calculate progress if we have position data
// Note: Progress calculation would need total duration from the component
// For now, we use position as location
return {
bookId: session.bookId,
bookType: 'AUDIOBOOK',
startTime: session.sessionStartTime.toISOString(),
endTime: now.toISOString(),
durationSeconds,
durationFormatted: this.formatDuration(durationSeconds),
startLocation: this.formatMs(session.startPositionMs),
endLocation: this.formatMs(session.currentPositionMs)
};
}
private formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours > 0) {
return `${hours}h ${minutes}m ${secs}s`;
} else if (minutes > 0) {
return `${minutes}m ${secs}s`;
}
return `${secs}s`;
}
private formatMs(ms: number): string {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
private cleanup(): void {
this.stopPeriodicSave();
this.currentSession = null;
}
private log(message: string, data?: unknown): void {
if (data) {
console.log(`[AudiobookSession] ${message}`, data);
} else {
console.log(`[AudiobookSession] ${message}`);
}
}
private logError(message: string, error?: unknown): void {
if (error) {
console.error(`[AudiobookSession] ${message}`, error);
} else {
console.error(`[AudiobookSession] ${message}`);
}
}
}
@@ -0,0 +1,143 @@
import {inject, Injectable, Injector, signal} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, tap} from 'rxjs';
import {RxStompService} from '../websocket/rx-stomp.service';
import {API_CONFIG} from '../../core/config/api-config';
import {createRxStompConfig} from '../websocket/rx-stomp.config';
import {Router} from '@angular/router';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`;
private rxStompService?: RxStompService;
private postLoginInitialized = false;
private http = inject(HttpClient);
private injector = inject(Injector);
private router = inject(Router);
private postLoginInitializer = inject(PostLoginInitializerService);
readonly token = signal<string | null>(this.getInternalAccessToken());
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
}
})
);
}
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
const refreshToken = this.getInternalRefreshToken();
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
}
})
);
}
remoteLogin(): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
return this.http.get<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/remote`).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
}
})
);
}
saveInternalTokens(accessToken: string, refreshToken: string): void {
localStorage.setItem('accessToken_Internal', accessToken);
localStorage.setItem('refreshToken_Internal', refreshToken);
this.token.set(accessToken);
}
getInternalAccessToken(): string | null {
return localStorage.getItem('accessToken_Internal');
}
getInternalRefreshToken(): string | null {
return localStorage.getItem('refreshToken_Internal');
}
logout(): void {
const refreshToken = this.getInternalRefreshToken();
this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, {refreshToken}).subscribe({
next: (response) => {
if (response.logoutUrl) {
window.location.href = response.logoutUrl;
} else {
this.clearSession();
this.router.navigate(['/login']).then(() => window.location.reload());
}
},
error: () => {
this.clearSession();
this.router.navigate(['/login']).then(() => window.location.reload());
}
});
}
forceLogout(reason: string): void {
this.clearSession();
this.router.navigate(['/login'], {queryParams: {reason}});
}
clearSessionOnLoginPage(): void {
this.clearSession();
}
private clearSession(): void {
localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('refreshToken_Internal');
this.token.set(null);
this.postLoginInitialized = false;
this.getRxStompService().deactivate();
}
getRxStompService(): RxStompService {
if (!this.rxStompService) {
this.rxStompService = this.injector.get(RxStompService);
}
return this.rxStompService;
}
initializeWebSocketConnection(): void {
const token = this.getInternalAccessToken();
if (!token) return;
const stompService = this.getRxStompService();
const config = createRxStompConfig(this);
stompService.updateConfig(config);
stompService.activate();
if (!this.postLoginInitialized) {
this.handleSuccessfulAuth();
}
}
private handleSuccessfulAuth() {
if (this.postLoginInitialized) return;
this.postLoginInitialized = true;
this.postLoginInitializer.initialize().subscribe({
next: () => console.log('AuthService: Post-login initialization completed'),
error: (err) => console.error('AuthService: Post-login initialization failed:', err)
});
}
}
export function websocketInitializer(authService: AuthService): () => void {
return () => authService.initializeWebSocketConnection();
}
@@ -0,0 +1,60 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface BookMark {
id: number;
userId?: number;
bookId: number;
cfi?: string; // For EPUB bookmarks
positionMs?: number; // For audiobook bookmarks
trackIndex?: number; // For folder-based audiobooks
title: string;
color?: string;
notes?: string;
priority?: number;
createdAt: string;
updatedAt?: string;
}
export interface CreateBookMarkRequest {
bookId: number;
cfi?: string; // For EPUB bookmarks
positionMs?: number; // For audiobook bookmarks
trackIndex?: number; // For folder-based audiobooks
title?: string;
}
export interface UpdateBookMarkRequest {
title?: string;
cfi?: string;
color?: string;
notes?: string;
priority?: number;
}
@Injectable({
providedIn: 'root'
})
export class BookMarkService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/bookmarks`;
private readonly http = inject(HttpClient);
getBookmarksForBook(bookId: number): Observable<BookMark[]> {
return this.http.get<BookMark[]>(`${this.url}/book/${bookId}`);
}
createBookmark(request: CreateBookMarkRequest): Observable<BookMark> {
return this.http.post<BookMark>(this.url, request);
}
deleteBookmark(bookmarkId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${bookmarkId}`);
}
updateBookmark(bookmarkId: number, request: UpdateBookMarkRequest): Observable<BookMark> {
return this.http.put<BookMark>(`${this.url}/${bookmarkId}`, request);
}
}
@@ -0,0 +1,19 @@
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
@Injectable({ providedIn: 'root' })
export class BookMetadataHostService {
private bookSwitchRequest$ = new Subject<number>();
requestBookSwitch(bookId: number) {
this.bookSwitchRequest$.next(bookId);
}
switchBook(bookId: number): void {
this.bookSwitchRequest$.next(bookId);
}
get bookSwitches$() {
return this.bookSwitchRequest$.asObservable();
}
}
@@ -0,0 +1,57 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface BookNoteV2 {
id: number;
userId?: number;
bookId: number;
cfi: string;
selectedText?: string;
noteContent: string;
color?: string;
chapterTitle?: string;
createdAt: string;
updatedAt?: string;
}
export interface CreateBookNoteV2Request {
bookId: number;
cfi: string;
selectedText?: string;
noteContent: string;
color?: string;
chapterTitle?: string;
}
export interface UpdateBookNoteV2Request {
noteContent?: string;
color?: string;
chapterTitle?: string;
}
@Injectable({
providedIn: 'root'
})
export class BookNoteV2Service {
private readonly url = `${API_CONFIG.BASE_URL}/api/v2/book-notes`;
private readonly http = inject(HttpClient);
getNotesForBook(bookId: number): Observable<BookNoteV2[]> {
return this.http.get<BookNoteV2[]>(`${this.url}/book/${bookId}`);
}
createNote(request: CreateBookNoteV2Request): Observable<BookNoteV2> {
return this.http.post<BookNoteV2>(this.url, request);
}
deleteNote(noteId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${noteId}`);
}
updateNote(noteId: number, request: UpdateBookNoteV2Request): Observable<BookNoteV2> {
return this.http.put<BookNoteV2>(`${this.url}/${noteId}`, request);
}
}
@@ -0,0 +1,42 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface BookNote {
id: number;
userId: number;
bookId: number;
title: string;
content: string;
createdAt: string;
updatedAt: string;
}
export interface CreateBookNoteRequest {
id?: number;
bookId: number;
title: string;
content: string;
}
@Injectable({
providedIn: 'root'
})
export class BookNoteService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/book-notes`;
private readonly http = inject(HttpClient);
getNotesForBook(bookId: number): Observable<BookNote[]> {
return this.http.get<BookNote[]>(`${this.url}/book/${bookId}`);
}
createOrUpdateNote(request: CreateBookNoteRequest): Observable<BookNote> {
return this.http.post<BookNote>(this.url, request);
}
deleteNote(noteId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${noteId}`);
}
}
@@ -0,0 +1,143 @@
import {computed, effect, inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {lastValueFrom, Observable, tap} from 'rxjs';
import {CustomFont} from '../model/custom-font.model';
import {API_CONFIG} from '../../core/config/api-config';
import {AuthService} from './auth.service';
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
const CUSTOM_FONTS_QUERY_KEY = ['customFonts'] as const;
@Injectable({
providedIn: 'root'
})
export class CustomFontService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`;
private loadedFonts = new Set<string>();
private http = inject(HttpClient);
private authService = inject(AuthService);
private queryClient = inject(QueryClient);
private readonly token = this.authService.token;
private fontsQuery = injectQuery(() => ({
...this.getFontsQueryOptions(),
enabled: !!this.token(),
}));
fonts = computed(() => this.fontsQuery.data() ?? []);
isFontsLoading = computed(() => !!this.token() && this.fontsQuery.isPending());
constructor() {
effect(() => {
const token = this.token();
if (token === null) {
this.queryClient.removeQueries({queryKey: CUSTOM_FONTS_QUERY_KEY});
}
});
}
private getFontsQueryOptions() {
return queryOptions({
queryKey: CUSTOM_FONTS_QUERY_KEY,
queryFn: () => lastValueFrom(this.http.get<CustomFont[]>(this.apiUrl))
});
}
ensureFonts(): Promise<CustomFont[]> {
return this.queryClient.ensureQueryData(this.getFontsQueryOptions());
}
uploadFont(file: File, fontName?: string): Observable<CustomFont> {
const formData = new FormData();
formData.append('file', file);
if (fontName) {
formData.append('fontName', fontName);
}
return this.http.post<CustomFont>(`${this.apiUrl}/upload`, formData).pipe(
tap(font => {
this.queryClient.setQueryData<CustomFont[]>(CUSTOM_FONTS_QUERY_KEY, current =>
[...(current ?? []), font]
);
this.loadFontFace(font).catch(err => {
console.error('Failed to load font after upload:', err);
});
})
);
}
deleteFont(fontId: number): Observable<void> {
return this.http.delete<void>(`${this.apiUrl}/${fontId}`).pipe(
tap(() => {
const currentFonts = this.fonts();
const deletedFont = currentFonts.find(f => f.id === fontId);
this.queryClient.setQueryData<CustomFont[]>(CUSTOM_FONTS_QUERY_KEY, current =>
(current ?? []).filter(f => f.id !== fontId)
);
if (deletedFont) {
this.removeFontFace(deletedFont.fontName);
this.loadedFonts.delete(deletedFont.fontName);
}
})
);
}
getFontUrl(fontId: number): string {
return `${this.apiUrl}/${fontId}/file`;
}
private getToken(): string | null {
return this.authService.getInternalAccessToken();
}
public appendToken(url: string): string {
const token = this.getToken();
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
async loadFontFace(font: CustomFont): Promise<void> {
if (this.loadedFonts.has(font.fontName)) {
return;
}
try {
const absoluteFontUrl = this.getFontUrl(font.id);
const fontUrlWithToken = this.appendToken(absoluteFontUrl);
const fontFace = new FontFace(
font.fontName,
`url(${fontUrlWithToken})`,
{
weight: 'normal',
style: 'normal'
}
);
await fontFace.load();
document.fonts.add(fontFace);
this.loadedFonts.add(font.fontName);
} catch (error) {
console.error(`Failed to load font ${font.fontName}:`, error);
throw error;
}
}
async loadAllFonts(fonts: CustomFont[]): Promise<void> {
const loadPromises = fonts.map(font => this.loadFontFace(font));
await Promise.allSettled(loadPromises);
}
isFontLoaded(fontName: string): boolean {
return this.loadedFonts.has(fontName);
}
private removeFontFace(fontName: string): void {
for (const font of document.fonts) {
if (font.family === fontName) {
document.fonts.delete(font);
}
}
}
}
@@ -0,0 +1,30 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class FileDownloadService {
private http = inject(HttpClient);
downloadFile(url: string, filename: string): void {
this.http.get(url, {responseType: 'blob', observe: 'response'}).subscribe(response => {
const blob = response.body;
if (!blob) return;
const resolvedFilename = this.extractFilename(response.headers.get('Content-Disposition')) ?? filename;
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = resolvedFilename;
link.click();
URL.revokeObjectURL(objectUrl);
});
}
private extractFilename(contentDisposition: string | null): string | null {
if (!contentDisposition) return null;
const match = contentDisposition.match(/filename\*=UTF-8''([\w%\-.]+)/i);
return match ? decodeURIComponent(match[1]) : null;
}
}
@@ -0,0 +1,26 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface FileMoveRequest {
bookIds: number[];
moves: {
bookId: number;
targetLibraryId: number | null;
targetLibraryPathId: number | null;
}[];
}
@Injectable({
providedIn: 'root'
})
export class FileOperationsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/files`;
private http = inject(HttpClient);
moveFiles(request: FileMoveRequest): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/move`, request);
}
}
@@ -0,0 +1,18 @@
import {inject, Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {DialogLauncherService} from '../services/dialog-launcher.service';
export interface IconSelection {
type: 'PRIME_NG' | 'CUSTOM_SVG';
value: string;
}
@Injectable({providedIn: 'root'})
export class IconPickerService {
private dialogLauncherService = inject(DialogLauncherService);
open(): Observable<IconSelection> {
const ref = this.dialogLauncherService.openIconPickerDialog();
return ref!.onClose as Observable<IconSelection>;
}
}

Some files were not shown because too many files have changed in this diff Show More