Introduce multi-format book support, including audiobooks (#2486)

* fix: support reading alternative book formats using bookType query param

* feat: add streaming reader support for alternative EPUB formats

* refactor: extract tabs section into MetadataTabsComponent

* feat: implement per-file reading progress tracking

* feat: add configurable format priority with cascading fallback

* refactor: redesign library creator with single-page layout

* refactor: unify reading progress into ReadingProgressService

* refactor: improve delete options with clearer file format and book deletion

* refactor: improve book format matching with normalization and fuzzy fallback

* feat: add folder-based audiobook support with ZIP downloads and preparing state

* fix: display unique format types in metadata viewer

* refactor: auto-attach files to single book in folder during rescan

* feat: implement folder-centric book file grouping with fuzzy matching

* refactor: consolidate book grouping with organization mode support

* fix: use folder hash for folder-based audiobooks in auto-attach

* fix: delete only BookFileEntity on file removal, not entire book

* fix: set folderBased flag and correct file size for auto-attached audiobook folders

* fix: use count query to avoid lazy initialization in file delete handler

* fix: preserve book metadata when file is moved by detecting hash match

* fix: skip books with no files in restoration to avoid NPE

* fix: round all progress percentages to one decimal place before sending to UI

* style: improve library creator dialog spacing and layout

* fix: migrate FOLDER_AS_BOOK to BOOK_PER_FOLDER for backwards compatibility

* fix: FileMoveService now handles multi-file BookEntity properly

* style: redesign metadata-picker and file-mover UI components

* style: redesign file-naming-pattern UI and improve theme contrast

* style: relax spacing in library-creator component

* style: tighten directory-picker layout for consistency

* fix: PathPatternResolver now respects folderBased flag for audiobooks

* style: move checkmark column to left side and add pending status in file-mover

* refactor: consolidate BookFileType into BookType and add audiobook styling

* feat: show 'Continue Reading' button for in-progress books

* fix: preserve dots in folder names during grouping and prevent duplicate attachments

* style: reduce gap between download-all button and primary file section

* style: shorten 'Continue Reading' button to 'Read' on mobile

* feat: add DISK_TYPE config to disable file moves on network storage

* style: standardize settings pages with shared styles and consistent spacing

* style: revamp settings pages with modern card-based layouts

* style: revamp OPDS, auth, and task management settings layouts

* fix: update FileMoveService tests to include AppProperties parameter

* fix: derive BookFileType from extension when uploading additional book files

* feat: show format type and size in download button with dropdown for alternatives

* feat: add audiobook streaming player with HTTP Range support

* feat: add M4B chapter extraction and chapter navigation

* feat: add audiobook bookmarks and sleep timer

* refactor: split AudiobookReaderService into focused services

* feat: add Media Session API for background audio playback

* feat: display file extensions in format tags with distinct colors and add audiobook upload support

* feat: require bookFileId for viewer settings API

* fix: show split button for audiobooks with readable alternatives

* feat: improve reading sessions table with book type badges and better formatting

* feat: add audiobook play button in files tab

* feat: use file extension for format display and meaningful tab values

* feat: add extension field to BookFile DTO

* feat: use extension field for book card format pill

* fix: use mixed orientation for format priority drag-drop to support multi-line layout

* feat: add attach book files feature to consolidate single-file books

* fix: increase drag handle size for format priority chips

* fix: add missing BookFileRepository mock to BookServiceDeleteTests

* feat: add delete buttons to files tab and move shelf to other items menu

* feat: add physical books support for cataloging books without digital files

* refactor: redesign icon-picker component with improved styling

* refactor: redesign metadata-picker component with improved layout and alignment

* refactor: move Add Physical Book to top of library menu

* refactor: use p-autoComplete for authors/categories in add-physical-book dialog

* feat: add square cover search and display support for audiobooks

* fix: navigate to first page when opening unread ebooks

* fix: exclude API requests from service worker interception

* feat: support fileless books with automatic file attachment

* fix: bypass service worker for audiobook streaming requests

* refactor: remove alphabetical filter sorting, default to count, limit filters to 100

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-27 10:12:50 -07:00
committed by GitHub
co-authored by acx10
parent c23e38b5a5
commit 3f334202b6
340 changed files with 23225 additions and 20727 deletions
@@ -88,7 +88,7 @@
name="file"
[customUpload]="true"
[multiple]="true"
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3"
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3,.m4b,.mp3"
(onSelect)="onFilesSelect($event)"
(uploadHandler)="uploadFiles($event)">
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
@@ -191,7 +191,7 @@
</div>
<h3 class="empty-title">Drag and Drop Files</h3>
<p class="empty-description">
Supported formats: <strong>.pdf</strong>, <strong>.epub</strong>, <strong>.cbz</strong>, <strong>.cbr</strong>, <strong>.cb7</strong>, <strong>.fb2</strong>
Supported formats: <strong>.pdf</strong>, <strong>.epub</strong>, <strong>.cbz</strong>, <strong>.cbr</strong>, <strong>.cb7</strong>, <strong>.fb2</strong>, <strong>.m4b</strong>, <strong>.mp3</strong>
<br/>
Maximum file size: {{ maxFileSizeDisplay }} per file
</p>
@@ -31,7 +31,7 @@
.picker-controls {
display: flex;
flex-direction: column;
gap: 0.75rem;
gap: 1rem;
padding: 1rem 2rem;
background: var(--card-background);
border: 1px solid var(--border-color);
@@ -259,7 +259,7 @@
.directories-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
gap: 0.625rem;
height: 100%;
overflow: hidden;
}
@@ -268,7 +268,7 @@
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.625rem 0.875rem;
padding: 0.5rem 0.875rem;
background: var(--overlay-background);
border-radius: 6px;
@@ -276,7 +276,7 @@
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.9rem;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-color);
@@ -289,7 +289,7 @@
padding: 0.5rem 0.625rem;
.folder-count {
font-size: 0.85rem;
font-size: 0.8rem;
}
}
}
@@ -297,7 +297,7 @@
.directories-grid {
display: flex;
flex-direction: column;
gap: 0.5rem;
gap: 0.625rem;
overflow-y: auto;
overflow-x: hidden;
flex: 1;
@@ -352,19 +352,17 @@
.directory-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.875rem 1rem;
gap: 0.5rem;
padding: 0.75rem 1rem;
background: var(--ground-background);
border: 1px solid var(--border-color);
border-radius: 8px;
border-radius: 6px;
transition: all 0.3s ease;
cursor: pointer;
opacity: 0;
animation: fadeInItem 0.3s ease-out forwards;
width: 100%;
max-width: 100%;
overflow: hidden;
min-height: 70px;
@for $i from 1 through 20 {
&:nth-child(#{$i}) {
@@ -409,7 +407,7 @@
flex: 1;
display: flex;
align-items: center;
gap: 0.75rem;
gap: 0.5rem;
cursor: pointer;
min-width: 0;
@@ -417,14 +415,14 @@
display: flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
width: 32px;
height: 32px;
background: var(--overlay-background);
border-radius: 8px;
border-radius: 6px;
flex-shrink: 0;
.directory-icon {
font-size: 1.125rem;
font-size: 1rem;
color: var(--text-secondary-color);
transition: all 0.3s ease;
}
@@ -434,12 +432,12 @@
flex: 1;
display: flex;
flex-direction: column;
gap: 0.375rem;
gap: 0.1875rem;
min-width: 0;
overflow: hidden;
.directory-name {
font-size: 0.9375rem;
font-size: 0.875rem;
color: var(--text-color);
font-weight: 500;
overflow: hidden;
@@ -457,7 +455,7 @@
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
line-height: 1.3;
line-height: 1.2;
}
}
@@ -470,24 +468,24 @@
}
@media (max-width: 480px) {
padding: 0.625rem;
gap: 0.5rem;
padding: 0.5rem 0.625rem;
gap: 0.375rem;
.directory-label {
gap: 0.5rem;
gap: 0.375rem;
.directory-icon-wrapper {
width: 32px;
height: 32px;
width: 26px;
height: 26px;
.directory-icon {
font-size: 1rem;
font-size: 0.8125rem;
}
}
.directory-info {
.directory-name {
font-size: 0.875rem;
font-size: 0.8125rem;
}
.directory-path {
@@ -1,102 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {UtilityService} from './utility.service';
describe('UtilityService', () => {
let service: UtilityService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UtilityService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(UtilityService)
);
});
it('should get folders for a given path', () => {
httpClientMock.get.mockReturnValue(of(['folder1', 'folder2']));
service.getFolders('/some/path').subscribe(folders => {
expect(folders).toEqual(['folder1', 'folder2']);
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringContaining('/api/v1/path'),
{params: expect.anything()}
);
});
});
it('should handle error when getting folders', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getFolders('/bad/path').subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('UtilityService - API Contract Tests', () => {
let service: UtilityService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UtilityService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(UtilityService)
);
});
it('should call correct endpoint and params for getFolders', () => {
httpClientMock.get.mockReturnValue(of(['a', 'b']));
service.getFolders('/root').subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/path$/),
{params: expect.objectContaining({get: expect.any(Function)})}
);
});
it('should expect string[] from getFolders', () => {
httpClientMock.get.mockReturnValue(of(['dirA', 'dirB']));
service.getFolders('/dir').subscribe(result => {
expect(Array.isArray(result)).toBe(true);
expect(typeof result[0]).toBe('string');
});
});
it('should send correct query param for path', () => {
httpClientMock.get.mockImplementation((url: string, opts: any) => {
expect(opts.params.get('path')).toBe('/my/path');
return of([]);
});
service.getFolders('/my/path').subscribe();
});
});
@@ -1,6 +1,6 @@
<p-dialog
[visible]="currentProgress.visible"
[header]="'Downloading File'"
[header]="currentProgress.preparing ? 'Preparing Download' : 'Downloading File'"
[modal]="true"
[closable]="false"
[draggable]="false"
@@ -10,16 +10,23 @@
<div class="download-content">
<div class="filename">{{ currentProgress.filename }}</div>
<div class="progress-bar-container">
<div class="progress-bar-background">
<div class="progress-bar-fill" [style.width.%]="currentProgress.progress"></div>
<div class="progress-bar-label">{{ currentProgress.progress }}%</div>
@if (currentProgress.preparing) {
<div class="preparing-container">
<i class="pi pi-spin pi-spinner" style="font-size: 1.5rem; margin-right: 0.5rem;"></i>
<span>Preparing download, please wait...</span>
</div>
} @else {
<div class="progress-bar-container">
<div class="progress-bar-background">
<div class="progress-bar-fill" [style.width.%]="currentProgress.progress"></div>
<div class="progress-bar-label">{{ currentProgress.progress }}%</div>
</div>
</div>
</div>
<div class="download-info">
<span>{{ formatBytes(currentProgress.loaded) }} / {{ formatBytes(currentProgress.total) }}</span>
</div>
<div class="download-info">
<span>{{ formatBytes(currentProgress.loaded) }} / {{ formatBytes(currentProgress.total) }}</span>
</div>
}
</div>
<ng-template pTemplate="footer">
@@ -51,3 +51,12 @@
font-size: 0.875rem;
color: var(--p-text-color);
}
.preparing-container {
display: flex;
align-items: center;
justify-content: center;
padding: 1.5rem 0;
color: var(--p-text-color);
font-size: 0.95rem;
}
@@ -23,7 +23,8 @@ export class DownloadProgressDialogComponent implements OnDestroy {
filename: '',
progress: 0,
loaded: 0,
total: 0
total: 0,
preparing: false
};
constructor() {
@@ -18,211 +18,233 @@
</div>
<div class="dialog-content">
<div class="preview-info-box">
<p class="preview-title">
File Organization Preview
</p>
<div class="preview-description">
<p>
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, select target libraries if needed, then click <span class="highlight-green">Move Files</span> to organize them.
</p>
<p>
<i class="pi pi-lightbulb icon-blue"></i>
<span class="text-blue">Want to change how files are named? Go to <strong>Settings → File Naming Pattern</strong>. Each library can have its own naming pattern!</span>
</p>
<p class="warning-text">
<i class="pi pi-exclamation-triangle icon-yellow"></i>
This will actually move and rename files on your computer across different library folders. Make sure you're happy with the preview first!
</p>
<div class="metadata-warning-box">
<p class="metadata-warning-title">
<i class="pi pi-exclamation-circle"></i>
Important: Metadata quality warning
</p>
<p>
This feature relies entirely on your books' metadata. If your metadata is missing, inconsistent, or of poor quality, the resulting file names and folder structures will be incorrect or "buggy".
</p>
<p class="metadata-warning-emphasis">
ONLY recommended for high-quality, curated libraries.
</p>
<!-- 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>
</div>
</div>
<div class="patterns-section">
<div class="patterns-content">
<div class="patterns-toggle" (click)="togglePatternsCollapsed()">
<p-button
outlined
[icon]="patternsCollapsed ? 'pi pi-chevron-right' : 'pi pi-chevron-down'"
iconPos="right"
size="small"
severity="info"
[label]="patternsCollapsed ? 'Show Naming Rules' : 'Hide Naming Rules'">
</p-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-card-content">
<div class="pattern-info">
<p class="pattern-label">Library: {{ pattern.libraryName }}</p>
<code class="pattern-code">{{ pattern.pattern || 'No pattern available' }}</code>
<p class="pattern-source">Source: {{ pattern.source }}</p>
</div>
<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>
}
</div>
</div>
</section>
<div class="bulk-select-section">
<div class="bulk-select-controls">
<label class="bulk-select-label">Set all files to:</label>
<p-select
[options]="availableLibraries"
[(ngModel)]="defaultTargetLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select default library"
(onChange)="onDefaultLibraryChange()"
styleClass="select-library"
size="small"
appendTo="body"
></p-select>
@if (defaultAvailableLibraryPaths.length > 0) {
<!-- 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]="defaultAvailableLibraryPaths"
[(ngModel)]="defaultTargetLibraryPathId"
optionLabel="path"
[options]="availableLibraries"
[(ngModel)]="defaultTargetLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select default path"
(onChange)="onDefaultLibraryPathChange()"
styleClass="select-path"
placeholder="Select library"
(onChange)="onDefaultLibraryChange()"
styleClass="select-library"
size="small"
appendTo="body"
></p-select>
}
</div>
</div>
<div class="table-container">
<p-table
[value]="filePreviews"
[scrollable]="true"
scrollHeight="500px"
[virtualScroll]="true"
[virtualScrollItemSize]="46"
[rows]="50"
>
<ng-template pTemplate="header">
<tr>
<th style="max-width:50px;">ID</th>
<th>Current Path</th>
<th style="max-width:150px;">Target Library</th>
<th style="max-width:150px;">Library Sub Path</th>
<th></th>
<th>New Path</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-preview>
<tr>
<td>{{ preview.bookId }}</td>
<td>
<div class="path-cell">
<span class="path-prefix">{{ preview.currentLibraryName }}/</span><span class="path-value">{{ preview.relativeOriginalPath }}</span>
</div>
</td>
<td style="max-width:150px;">
<p-select
[options]="availableLibraries"
[(ngModel)]="preview.targetLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select Library"
(onChange)="onLibraryChange(preview)"
[disabled]="preview.isMoved"
styleClass="select-full-width"
appendTo="body"
size="small"
></p-select>
</td>
<td style="max-width:150px;">
@if (preview.availableLibraryPaths.length > 0) {
<p-select
[options]="preview.availableLibraryPaths"
[(ngModel)]="preview.targetLibraryPathId"
optionLabel="path"
optionValue="id"
placeholder="Select Path"
(onChange)="onLibraryPathChange(preview)"
[disabled]="preview.isMoved"
styleClass="select-full-width"
appendTo="body"
size="small"
></p-select>
} @else {
<div class="no-paths-error">No paths configured</div>
}
</td>
<td class="arrow-cell">→</td>
<td>
<div class="path-cell">
<span class="path-prefix">{{ preview.targetLibraryName }}/</span><span class="path-value">{{ preview.relativeNewPath }}</span>
</div>
</td>
<td class="status-cell">
@if (preview.isMoved) {
<i class="pi pi-check-circle icon-success"></i>
}
</td>
</tr>
</ng-template>
</p-table>
</div>
@if (defaultAvailableLibraryPaths.length > 0) {
<p-select
[options]="defaultAvailableLibraryPaths"
[(ngModel)]="defaultTargetLibraryPathId"
optionLabel="path"
optionValue="id"
placeholder="Select path"
(onChange)="onDefaultLibraryPathChange()"
styleClass="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"
styleClass="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"
styleClass="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) {
<span class="success-message">
{{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved
<i
class="pi pi-check-circle success-icon-bounce"
style="animation-duration: 1.5s;"
aria-label="Success"
role="img"
></i>
</span>
}
@if (movedFileCount === 0) {
<p-button
[label]="loading ? 'Moving...' : 'Move Files'"
[icon]="loading ? 'pi pi-spin pi-spinner' : 'pi pi-arrows-h'"
severity="success"
(click)="saveChanges()"
[disabled]="loading || filePreviews.length === 0"
></p-button>
<p-button
label="Cancel"
icon="pi pi-times"
severity="secondary"
[text]="true"
(click)="cancel()"
></p-button>
} @else {
<p-button
label="Close"
icon="pi pi-times"
severity="success"
(click)="cancel()"
></p-button>
<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>
@@ -25,263 +25,502 @@
flex-direction: column;
overflow-y: auto;
min-height: 0;
padding: 1rem;
padding: 1.25rem;
gap: 1.25rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
border-bottom: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
&::-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;
}
:host ::ng-deep .p-datatable-tbody > tr > td {
padding: 0.5rem 1rem !important;
}
// Preview info box
.preview-info-box {
padding: 0.75rem 1rem;
margin: 0 0.5rem 1rem;
border-radius: 0.5rem;
// Compact Info Banner
.info-banner {
border: 1px solid var(--border-color);
transition: all 0.2s ease;
border-radius: 8px;
overflow: hidden;
}
.preview-title {
color: var(--primary-color);
font-weight: 600;
margin-bottom: 0.25rem;
.banner-main {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.875rem 1rem;
}
.preview-description {
font-size: 0.875rem;
color: #d1d5db;
.banner-icon {
display: flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
background: var(--primary-color);
border-radius: 6px;
flex-shrink: 0;
> * + * {
margin-top: 0.75rem;
i {
font-size: 1rem;
color: var(--primary-contrast-color);
}
}
.highlight-green {
font-weight: 600;
color: #4ade80;
.banner-content {
flex: 1;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.375rem 1rem;
min-width: 0;
}
.icon-blue {
color: #60a5fa;
margin-right: 0.25rem;
.banner-text {
font-size: 0.875rem;
color: var(--text-secondary-color);
line-height: 1.4;
strong {
color: var(--text-color);
}
}
.text-blue {
color: #93c5fd;
}
.warning-text {
color: #eab308;
.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.5rem;
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;
}
}
.icon-yellow {
color: #facc15;
}
.metadata-warning-box {
background: rgba(127, 29, 29, 0.3);
border: 1px solid rgba(239, 68, 68, 0.5);
border-radius: 0.375rem;
padding: 0.75rem;
color: #fecaca;
font-size: 0.75rem;
}
.metadata-warning-title {
font-weight: 700;
.banner-details {
display: flex;
align-items: center;
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;
margin-bottom: 0.25rem;
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);
}
}
}
.metadata-warning-emphasis {
margin-top: 0.25rem;
font-weight: 600;
}
// Patterns section
// Patterns Section
.patterns-section {
display: flex;
gap: 1rem;
margin-bottom: 1rem;
padding: 0 0.5rem;
align-items: center;
width: 100%;
}
.patterns-content {
flex: 1;
flex-direction: column;
gap: 0.75rem;
}
.patterns-toggle {
display: flex;
align-items: center;
justify-content: space-between;
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;
.patterns-list {
margin-top: 0.5rem;
&:hover {
border-color: var(--primary-color);
}
> * + * {
margin-top: 0.5rem;
.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);
}
}
.pattern-card {
padding: 0.75rem;
border: 1px solid #3f3f46;
border-radius: 0.5rem;
background: #27272a;
}
.pattern-card-content {
.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;
align-items: flex-start;
}
.pattern-info {
flex: 1;
}
.pattern-label {
font-size: 0.75rem;
color: #9ca3af;
margin-bottom: 0.25rem;
}
.pattern-code {
color: var(--primary-color);
font-family: monospace;
font-size: 0.875rem;
}
.pattern-source {
font-size: 0.75rem;
color: #9ca3af;
margin-top: 0.25rem;
.pattern-library {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-color);
}
.pattern-badge {
font-size: 0.75rem;
background: #2563eb;
color: white;
padding: 0.25rem 0.5rem;
border-radius: 0.25rem;
margin-left: 0.5rem;
}
// Bulk select section
.bulk-select-section {
display: flex;
gap: 1rem;
margin-bottom: 1rem;
padding: 0 0.5rem;
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;
}
.bulk-select-controls {
.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-select-label {
font-size: 0.875rem;
.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: #d1d5db;
color: var(--text-color);
i {
color: var(--primary-color);
}
}
// Table section
.table-container {
margin-bottom: 1rem;
height: 500px;
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-prefix {
color: #9ca3af;
.path-library {
color: var(--text-secondary-color);
}
.path-value {
color: #e5e7eb;
color: var(--text-color);
}
.no-paths-error {
.no-paths {
font-size: 0.75rem;
color: #f87171;
color: var(--p-red-400);
font-style: italic;
}
.arrow-cell {
color: var(--primary-color);
text-align: center;
i {
font-size: 0.75rem;
color: var(--primary-color);
}
}
.status-cell {
text-align: center;
}
.icon-success {
color: #16a34a;
.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-message {
color: #22c55e;
.success-indicator {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--p-green-500);
font-weight: 600;
filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.05));
user-select: none;
font-size: 0.9rem;
i {
font-size: 1.125rem;
animation: pulse 2s infinite;
}
}
.success-icon-bounce {
margin-left: 0.5rem;
color: #22c55e;
animation: bounce 1s infinite;
.footer-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
@keyframes bounce {
@keyframes pulse {
0%, 100% {
transform: translateY(-25%);
animation-timing-function: cubic-bezier(0.8, 0, 1, 1);
opacity: 1;
}
50% {
transform: translateY(0);
animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
opacity: 0.6;
}
}
// Select widths
:host ::ng-deep {
.select-library {
min-width: 200px;
min-width: 180px;
}
.select-path {
min-width: 250px;
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;
}
}
}
@@ -59,6 +59,7 @@ export class FileMoverComponent implements OnDestroy {
defaultMovePattern = '';
loading = false;
patternsCollapsed = true;
infoCollapsed = true;
bookIds = new Set<number>();
books: Book[] = [];
@@ -392,4 +393,8 @@ export class FileMoverComponent implements OnDestroy {
togglePatternsCollapsed(): void {
this.patternsCollapsed = !this.patternsCollapsed;
}
toggleInfoCollapsed(): void {
this.infoCollapsed = !this.infoCollapsed;
}
}
@@ -1,55 +1,96 @@
<div class="icon-picker-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-palette header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Choose an Icon</h2>
<p class="panel-description">Select or upload custom icons</p>
<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"
[rounded]="true"
[text]="true"
[rounded]="true"
severity="secondary"
(click)="ref.close()"
styleClass="close-button">
</p-button>
</div>
(onClick)="ref.close()"
/>
</header>
<div class="dialog-content">
<div class="dialog-body">
<p-tabs [(value)]="activeTabIndex">
<p-tablist>
<p-tab value="0">Prime Icons</p-tab>
<p-tab value="1">SVG Icons</p-tab>
<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">Add SVG Icon(s)</p-tab>
<p-tab value="2">
<i class="pi pi-plus-circle"></i>
<span>Add Custom</span>
</p-tab>
}
</p-tablist>
<p-tabpanels>
<p-tabpanel value="0">
<input type="text" placeholder="Search Prime icons..." [(ngModel)]="searchText" class="icon-search"/>
<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>
}
<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="svg-browse-container">
<div class="tab-content">
@if (isLoadingSvgIcons) {
<div class="loading-message">Loading icons...</div>
<div class="loading-state">
<i class="pi pi-spin pi-spinner"></i>
<span>Loading icons...</span>
</div>
} @else if (svgIconsError) {
<div class="error-message">{{ svgIconsError }}</div>
<div class="error-state">
<i class="pi pi-exclamation-triangle"></i>
<span>{{ svgIconsError }}</span>
</div>
} @else {
<input type="text" placeholder="Search SVG icons..." [(ngModel)]="svgSearchText" class="icon-search"/>
<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) {
@@ -62,122 +103,142 @@
(dragstart)="onSvgIconDragStart(iconName)"
(dragend)="onSvgIconDragEnd()"
>
<div
class="svg-icon-inline"
[innerHTML]="getSvgContent(iconName)"
></div>
<div class="svg-icon-inline" [innerHTML]="getSvgContent(iconName)"></div>
</div>
}
</div>
@if (canManageIcons) {
<div style="display: flex; align-items: center; position: fixed; right: 32px; bottom: 32px; z-index: 101;">
<div class="trash-zone-container">
<div
class="svg-trash-area"
[class.trash-hover]="isTrashHover"
class="trash-zone"
[class.active]="isTrashHover"
(dragover)="onTrashDragOver($event)"
(dragleave)="onTrashDragLeave($event)"
(drop)="onTrashDrop($event)">
(drop)="onTrashDrop($event)"
>
<i class="pi pi-trash"></i>
<span>Drag here to delete icon</span>
<span>Drop here to delete</span>
</div>
</div>
}
}
</div>
</p-tabpanel>
<!-- Add Custom SVG Tab -->
@if (canManageIcons) {
<p-tabpanel value="2">
<div class="svg-paste-container">
<div class="svg-input-section">
<input
type="text"
[(ngModel)]="svgName"
placeholder="Enter icon name for saving"
class="svg-name-input"
/>
<textarea
[(ngModel)]="svgContent"
(ngModelChange)="onSvgContentChange()"
placeholder="Paste your SVG code here..."
class="svg-textarea"
rows="8"></textarea>
@if (svgContent && svgPreview) {
<div class="svg-preview-section">
<h4 class="preview-title">Preview</h4>
<div class="svg-preview" [innerHTML]="svgPreview"></div>
</div>
}
@if (errorMessage) {
<div class="error-message">{{ errorMessage }}</div>
}
<div class="button-container">
<p-button
(onClick)="addSvgEntry()"
[disabled]="!svgContent || !svgName"
label="Add to Queue"
severity="primary"
outlined
icon="pi pi-plus">
</p-button>
<div class="tab-content">
<section class="form-section">
<div class="section-header">
<i class="pi pi-code"></i>
<span>SVG Input</span>
</div>
</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) {
<div class="svg-entries-section">
<div class="entries-header">
<h4 class="entries-title">
Queued Icons ({{ svgEntries.length }})
</h4>
<p-button
(onClick)="clearAllEntries()"
label="Clear All"
severity="danger"
[text]="true"
icon="pi pi-times">
</p-button>
<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="entries-grid">
<div class="queue-grid">
@for (entry of svgEntries; track entry.name; let i = $index) {
<div class="entry-card" [class.has-error]="entry.error">
<div class="entry-header">
<span class="entry-name">{{ entry.name }}</span>
<button
class="entry-remove"
(click)="removeSvgEntry(i)"
title="Remove">
<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="entry-preview" [innerHTML]="entry.preview"></div>
<div class="queue-item-preview" [innerHTML]="entry.preview"></div>
@if (entry.error) {
<div class="entry-error">{{ entry.error }}</div>
<div class="queue-item-error">{{ entry.error }}</div>
}
</div>
}
</div>
@if (batchErrorMessage) {
<div class="error-message">{{ batchErrorMessage }}</div>
<div class="error-message">
<i class="pi pi-exclamation-circle"></i>
<span>{{ batchErrorMessage }}</span>
</div>
}
<div class="batch-actions">
<div class="form-actions">
<p-button
(onClick)="saveAllSvgs()"
label="Save All Icons"
icon="pi pi-save"
severity="success"
[loading]="isSavingBatch"
[disabled]="svgEntries.length === 0"
label="Save All Icons"
severity="success"
icon="pi pi-save">
</p-button>
(onClick)="saveAllSvgs()"
/>
</div>
</div>
</section>
}
</div>
</p-tabpanel>
@@ -1,334 +1,550 @@
@use '../../styles/panel-shared' as panel;
.icon-picker-container {
.icon-picker {
display: flex;
flex-direction: column;
max-height: 85dvh;
}
.panel-header {
@include panel.panel-header;
flex-shrink: 0;
}
.dialog-content {
padding: 1rem;
height: 80dvh;
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;
min-height: 0;
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(25px, 1fr));
gap: 38px;
padding-top: 10px;
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;
justify-content: space-evenly;
align-items: flex-start;
transition: all 0.15s ease;
> i {
font-size: 1.25rem;
color: var(--text-color);
transition: color 0.15s ease;
}
}
.icon-search {
width: 100%;
padding: 8px 12px;
font-size: 16px;
border: 1px solid var(--text-secondary-color);
border-radius: 4px;
margin-bottom: 15px;
margin-top: 15px;
box-sizing: border-box;
&:hover {
border-color: var(--border-color);
background: var(--overlay-background);
&:focus {
> i {
color: var(--primary-color);
}
}
&.selected {
border-color: var(--primary-color);
outline: none;
}
background: rgba(var(--primary-color-rgb, 59, 130, 246), 0.1);
&::placeholder {
color: var(--text-secondary-color);
opacity: 1;
}
}
.svg-paste-container {
display: flex;
flex-direction: column;
gap: 20px;
}
.svg-input-section {
display: flex;
flex-direction: column;
gap: 15px;
padding-bottom: 20px;
border-bottom: 1px solid var(--border-color);
}
.svg-textarea {
width: 100%;
padding: 12px;
font-size: 14px;
font-family: monospace;
border: 1px solid var(--text-secondary-color);
border-radius: 4px;
resize: vertical;
box-sizing: border-box;
&:focus {
border-color: var(--primary-color);
outline: none;
}
}
.svg-preview-section {
display: flex;
flex-direction: column;
gap: 10px;
}
.preview-title {
margin: 0;
font-size: 14px;
font-weight: 600;
color: var(--text-primary-color);
}
.svg-preview {
border: 1px solid var(--text-secondary-color);
border-radius: 4px;
padding: 10px;
background-color: var(--ground-background);
display: flex;
justify-content: center;
align-items: center;
min-height: 200px;
max-height: 225px;
overflow: auto;
::ng-deep svg {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
}
.button-container {
display: flex;
justify-content: flex-end;
}
.error-message {
color: #e74c3c;
font-size: 14px;
font-weight: 500;
padding: 8px;
background-color: #ffe6e6;
border-radius: 4px;
}
.svg-name-input {
width: 100%;
padding: 8px 12px;
font-size: 15px;
border: 1px solid var(--text-secondary-color);
border-radius: 4px;
margin-bottom: 8px;
box-sizing: border-box;
&:focus {
border-color: var(--primary-color);
outline: none;
}
}
.svg-browse-container {
.loading-message {
text-align: center;
padding: 2rem;
color: #666;
}
}
.pagination-controls {
display: flex;
justify-content: center;
align-items: center;
gap: 1rem;
padding: 1rem;
margin-top: 1rem;
border-top: 1px solid var(--border-color);
.pagination-info {
color: #666;
font-size: 0.9rem;
font-weight: 500;
}
}
.svg-trash-area {
display: flex;
align-items: center;
gap: 10px;
background: var(--p-surface-800);
border: 2px dashed var(--border-color);
border-radius: 50px;
padding: 12px 22px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.30);
color: var(--text-secondary-color);
transition: border-color 0.2s, background 0.2s, color 0.2s;
i.pi-trash {
font-size: 22px;
color: #ff3b27;
margin-right: 8px;
transition: color 0.2s;
}
span {
font-size: 15px;
font-weight: 500;
color: #bbb;
transition: color 0.2s;
}
&.trash-hover {
border-color: #e74c3c;
background: #3a2323;
color: #e74c3c;
i.pi-trash {
color: #ff7675;
}
span {
color: #ff7675;
}
}
}
.svg-entries-section {
display: flex;
flex-direction: column;
gap: 15px;
.entries-header {
display: flex;
justify-content: space-between;
align-items: center;
.entries-title {
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--text-primary-color);
> i {
color: var(--primary-color);
}
}
.entries-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 15px;
max-height: 400px;
overflow-y: auto;
padding: 10px 0;
}
.entry-card {
border: 1px solid var(--border-color);
border-radius: 6px;
padding: 12px;
background-color: var(--surface-ground);
transition: box-shadow 0.2s;
&:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
&.has-error {
border-color: #e74c3c;
background-color: #fff5f5;
}
.entry-header {
&.svg-icon-item {
.svg-icon-inline {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
.entry-name {
font-size: 13px;
font-weight: 600;
color: var(--text-primary-color);
word-break: break-all;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.entry-remove {
background: none;
border: none;
cursor: pointer;
padding: 4px;
color: #e74c3c;
transition: color 0.2s;
&:hover {
color: #c0392b;
}
i {
font-size: 14px;
}
}
}
.entry-preview {
display: flex;
justify-content: center;
align-items: center;
min-height: 80px;
max-height: 100px;
background-color: var(--ground-background);
border-radius: 4px;
padding: 8px;
overflow: hidden;
width: 24px;
height: 24px;
::ng-deep svg {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
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.8125rem;
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;
}
}
.entry-error {
margin-top: 8px;
color: #e74c3c;
font-size: 12px;
font-weight: 500;
line-height: 1.4;
word-break: break-word;
.header-text h1 {
font-size: 1.125rem;
}
}
.batch-actions {
display: flex;
justify-content: flex-end;
padding-top: 10px;
border-top: 1px solid var(--border-color);
.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));
}
}
@@ -1,123 +0,0 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {Router} from '@angular/router';
import {of} from 'rxjs';
import {SetupComponent} from './setup.component';
import {SetupService} from './setup.service';
describe('SetupComponent confirm password', () => {
let fixture: ComponentFixture<SetupComponent>;
let component: SetupComponent;
let setupServiceMock: { createAdmin: ReturnType<typeof vi.fn> };
beforeEach(async () => {
setupServiceMock = {
createAdmin: vi.fn().mockReturnValue(of(void 0))
};
const routerMock = {
navigate: vi.fn()
};
await TestBed.configureTestingModule({
imports: [SetupComponent],
providers: [
{provide: SetupService, useValue: setupServiceMock},
{provide: Router, useValue: routerMock}
]
}).compileComponents();
fixture = TestBed.createComponent(SetupComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
const getErrorTexts = () =>
Array.from(
(fixture.nativeElement as HTMLElement).querySelectorAll('.field-error')
)
.map(el => el.textContent?.trim())
.filter((text): text is string => Boolean(text));
it('shows required error when confirm password is empty', () => {
const confirmControl = component.setupForm.get('confirmPassword');
confirmControl?.setValue('');
confirmControl?.markAsTouched();
fixture.detectChanges();
expect(getErrorTexts()).toContain('Password confirmation is required');
});
it('shows mismatch error when confirm password does not match', () => {
component.setupForm.get('password')?.setValue('abcdef');
const confirmControl = component.setupForm.get('confirmPassword');
confirmControl?.setValue('abcdeg');
confirmControl?.markAsTouched();
fixture.detectChanges();
expect(getErrorTexts()).toContain('Passwords do not match');
});
it('hides mismatch error when confirm password matches', () => {
component.setupForm.get('password')?.setValue('abcdef');
const confirmControl = component.setupForm.get('confirmPassword');
confirmControl?.setValue('abcdef');
confirmControl?.markAsTouched();
fixture.detectChanges();
expect(getErrorTexts()).not.toContain('Passwords do not match');
});
it('does not submit when confirm password is missing', () => {
component.setupForm.patchValue({
username: 'admin',
name: 'Admin User',
email: 'admin@example.com',
password: '123456',
confirmPassword: ''
});
component.onSubmit();
expect(component.setupForm.invalid).toBe(true);
expect(setupServiceMock.createAdmin).not.toHaveBeenCalled();
});
it('does not submit when confirm password does not match', () => {
component.setupForm.patchValue({
username: 'admin',
name: 'Admin User',
email: 'admin@example.com',
password: '123456',
confirmPassword: '123457'
});
component.onSubmit();
expect(component.setupForm.invalid).toBe(true);
expect(setupServiceMock.createAdmin).not.toHaveBeenCalled();
});
it('submits when form is valid and excludes confirmPassword from payload', () => {
component.setupForm.patchValue({
username: 'admin',
name: 'Admin User',
email: 'admin@example.com',
password: '123456',
confirmPassword: '123456'
});
component.onSubmit();
expect(component.setupForm.valid).toBe(true);
expect(setupServiceMock.createAdmin).toHaveBeenCalledWith({
username: 'admin',
name: 'Admin User',
email: 'admin@example.com',
password: '123456'
});
});
});
@@ -1,104 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {SetupPayload, SetupService} from './setup.service';
describe('SetupService', () => {
let service: SetupService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
SetupService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(SetupService)
);
});
it('should create admin with correct payload', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const payload: SetupPayload = {email: 'admin@test.com', password: 'pass'};
service.createAdmin(payload).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringContaining('/api/v1/setup'),
payload
);
});
});
it('should handle error when creating admin', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createAdmin({email: 'fail', password: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('SetupService - API Contract Tests', () => {
let service: SetupService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
SetupService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(SetupService)
);
});
it('should call correct endpoint for createAdmin', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const payload: SetupPayload = {email: 'a@b.com', password: 'pw'};
service.createAdmin(payload).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/setup$/),
payload
);
});
it('should expect void from createAdmin', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.createAdmin({email: 'x@y.com', password: 'pw'}).subscribe(result => {
expect(result).toBeUndefined();
});
});
it('should send correct payload structure', () => {
httpClientMock.post.mockImplementation((url: string, body: SetupPayload) => {
expect(body).toHaveProperty('email');
expect(body).toHaveProperty('password');
return of(void 0);
});
service.createAdmin({email: 'z@z.com', password: 'pw'}).subscribe();
});
});
@@ -161,6 +161,7 @@ export interface AppSettings {
metadataDownloadOnBookdrop: boolean;
telemetryEnabled: boolean;
metadataProviderSpecificFields: MetadataProviderSpecificFields;
diskType: string;
}
export interface MetadataProviderSpecificFields {
@@ -34,7 +34,7 @@ export class AppConfigService {
500: '#64748b',
600: '#475569',
700: '#334155',
800: '#1e293b',
800: '#283548',
900: '#0f172a',
950: '#020617'
}
@@ -51,7 +51,7 @@ export class AppConfigService {
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
800: '#313136',
900: '#18181b',
950: '#09090b'
}
@@ -68,7 +68,7 @@ export class AppConfigService {
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
800: '#303030',
900: '#171717',
950: '#0a0a0a'
}
@@ -85,7 +85,7 @@ export class AppConfigService {
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
800: '#313136',
900: '#18181b',
950: '#09090b'
}
@@ -102,7 +102,7 @@ export class AppConfigService {
500: '#78716c',
600: '#57534e',
700: '#44403c',
800: '#292524',
800: '#342f2b',
900: '#1c1917',
950: '#0c0a09'
}
@@ -204,7 +204,7 @@ export class AppConfigService {
500: '#5c6b7a',
600: '#4a5866',
700: '#3b4651',
800: '#2d353e',
800: '#38424d',
900: '#1f252c',
950: '#121518'
}
@@ -222,7 +222,7 @@ export class AppConfigService {
600: '#666666',
700: '#525252',
800: '#3d3d3d',
900: '#2a2a2a',
900: '#242424',
950: '#141414'
}
},
@@ -239,7 +239,7 @@ export class AppConfigService {
600: '#6a6b70',
700: '#55565b',
800: '#3f4046',
900: '#2c2c34',
900: '#252530',
950: '#16161d'
}
},
@@ -256,7 +256,7 @@ export class AppConfigService {
600: '#6e7173',
700: '#565a5b',
800: '#3e4244',
900: '#262b2c',
900: '#1e2324',
950: '#0e1315'
}
},
@@ -272,7 +272,7 @@ export class AppConfigService {
500: '#828787',
600: '#5F7274',
700: '#415B61',
800: '#29444E',
800: '#324f5a',
900: '#183240',
950: '#0c1920'
}
@@ -289,7 +289,7 @@ export class AppConfigService {
500: '#94a3b8',
600: '#64748b',
700: '#475569',
800: '#334155',
800: '#3d5068',
900: '#1e293b',
950: '#0f172a'
}
@@ -306,7 +306,7 @@ export class AppConfigService {
500: '#6a755e',
600: '#555d4c',
700: '#434a3d',
800: '#333930',
800: '#3d4438',
900: '#232824',
950: '#131614'
}
@@ -323,7 +323,7 @@ export class AppConfigService {
500: '#755e5e',
600: '#5d4c4c',
700: '#4a3d3d',
800: '#382f2f',
800: '#423838',
900: '#242020',
950: '#141212'
}
@@ -1,534 +0,0 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {AppSettingsService, PublicAppSettings} from './app-settings.service';
import {AppSettings} from '../model/app-settings.model';
import {AuthService} from './auth.service';
describe('AppSettingsService', () => {
let service: AppSettingsService;
let httpClientMock: any;
let authServiceMock: any;
let injectorMock: any;
const mockAppSettings: AppSettings = {
autoBookSearch: true,
similarBookRecommendation: false,
defaultMetadataRefreshOptions: {} as any,
libraryMetadataRefreshOptions: [],
uploadPattern: '',
opdsServerEnabled: false,
komgaApiEnabled: false,
komgaGroupUnknown: false,
remoteAuthEnabled: false,
oidcEnabled: true,
oidcProviderDetails: {
providerName: 'TestProvider',
clientId: 'clientid',
issuerUri: 'https://issuer.example.com',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
},
oidcAutoProvisionDetails: {
enableAutoProvisioning: false,
defaultPermissions: [],
defaultLibraryIds: []
},
maxFileUploadSizeInMb: 0,
metadataProviderSettings: {
amazon: {enabled: false, cookie: '', domain: ''},
google: {enabled: false, language: ''},
goodReads: {enabled: false},
hardcover: {enabled: false, apiKey: ''},
comicvine: {enabled: false, apiKey: ''},
douban: {enabled: false},
lubimyczytac: {enabled: false},
ranobedb: {enabled: false}
},
metadataMatchWeights: {
title: 0,
subtitle: 0,
description: 0,
authors: 0,
publisher: 0,
publishedDate: 0,
seriesName: 0,
seriesNumber: 0,
seriesTotal: 0,
isbn13: 0,
isbn10: 0,
language: 0,
pageCount: 0,
categories: 0,
amazonRating: 0,
amazonReviewCount: 0,
goodreadsRating: 0,
goodreadsReviewCount: 0,
hardcoverRating: 0,
hardcoverReviewCount: 0,
doubanRating: 0,
doubanReviewCount: 0,
lubimyczytacRating: 0,
ranobedbRating: 0,
coverImage: 0
},
metadataPersistenceSettings: {
moveFilesToLibraryPattern: false,
saveToOriginalFile: {
epub: {enabled: false, maxFileSizeInMb: 0},
pdf: {enabled: false, maxFileSizeInMb: 0},
cbx: {enabled: false, maxFileSizeInMb: 0}
},
convertCbrCb7ToCbz: false
},
metadataPublicReviewsSettings: {
downloadEnabled: false,
autoDownloadEnabled: false,
providers: []
},
koboSettings: {
convertToKepub: false,
conversionLimitInMb: 0,
conversionImageCompressionPercentage: 0,
convertCbxToEpub: false,
conversionLimitInMbForCbx: 0,
forceEnableHyphenation: false
},
coverCroppingSettings: {
verticalCroppingEnabled: false,
horizontalCroppingEnabled: false,
aspectRatioThreshold: 0,
smartCroppingEnabled: false
},
metadataDownloadOnBookdrop: false,
telemetryEnabled: false,
metadataProviderSpecificFields: {
asin: false,
amazonRating: false,
amazonReviewCount: false,
googleId: false,
goodreadsId: false,
goodreadsRating: false,
goodreadsReviewCount: false,
hardcoverId: false,
hardcoverBookId: false,
hardcoverRating: false,
hardcoverReviewCount: false,
comicvineId: false,
lubimyczytacId: false,
lubimyczytacRating: false,
ranobedbId: false,
ranobedbRating: false
}
};
const mockPublicSettings: PublicAppSettings = {
oidcEnabled: true,
remoteAuthEnabled: false,
oidcProviderDetails: mockAppSettings.oidcProviderDetails
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
put: vi.fn()
};
authServiceMock = {
clearOIDCTokens: vi.fn()
};
injectorMock = {
get: vi.fn().mockReturnValue(authServiceMock)
};
TestBed.configureTestingModule({
providers: [
AppSettingsService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock},
{provide: EnvironmentInjector, useValue: injectorMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService));
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should fetch app settings and update subject', () => {
httpClientMock.get.mockReturnValue(of(mockAppSettings));
service['fetchAppSettings']().subscribe(settings => {
expect(settings).toEqual(mockAppSettings);
expect(service['appSettingsSubject'].value).toEqual(mockAppSettings);
});
});
it('should handle error when fetching app settings', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['fetchAppSettings']().subscribe({
error: (err: any) => {
expect(service['appSettingsSubject'].value).toBeNull();
expect(err).toBeInstanceOf(Error);
}
});
});
it('should fetch public settings and update subject', () => {
httpClientMock.get.mockReturnValue(of(mockPublicSettings));
service['fetchPublicSettings']().subscribe(settings => {
expect(settings).toEqual(mockPublicSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
});
it('should handle error when fetching public settings', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['fetchPublicSettings']().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should sync public settings from app settings', () => {
service['publicAppSettingsSubject'].next(null);
service['syncPublicSettings'](mockAppSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
it('should not update public settings if unchanged', () => {
service['publicAppSettingsSubject'].next(mockPublicSettings);
service['syncPublicSettings'](mockAppSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
it('should save settings and update appSettingsSubject', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(() => {
expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false);
});
});
it('should fetch settings if current is null on save', () => {
httpClientMock.put.mockReturnValue(of(void 0));
httpClientMock.get.mockReturnValue(of(mockAppSettings));
service['appSettingsSubject'].next(null);
service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe(() => {
expect(httpClientMock.get).toHaveBeenCalled();
});
});
it('should handle error on saveSettings', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(result => {
expect(result).toBeUndefined();
});
});
it('should toggle OIDC enabled and update state', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
service.toggleOidcEnabled(false).subscribe(() => {
expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false);
});
});
it('should call clearOIDCTokens when disabling OIDC', async () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
await new Promise<void>(resolve => {
service.toggleOidcEnabled(false).subscribe(() => {
setTimeout(() => {
expect(authServiceMock.clearOIDCTokens).toHaveBeenCalled();
resolve();
}, 10);
});
});
});
it('should handle error on toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.toggleOidcEnabled(true).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
describe('AppSettingsService - API Contract Tests', () => {
let service: AppSettingsService;
let httpClientMock: any;
let authServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
put: vi.fn()
};
authServiceMock = {
clearOIDCTokens: vi.fn()
};
injectorMock = {
get: vi.fn().mockReturnValue(authServiceMock)
};
TestBed.configureTestingModule({
providers: [
AppSettingsService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock},
{provide: EnvironmentInjector, useValue: injectorMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService));
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('PublicAppSettings interface contract', () => {
it('should validate all required PublicAppSettings fields exist', () => {
const requiredFields: (keyof PublicAppSettings)[] = [
'oidcEnabled', 'remoteAuthEnabled', 'oidcProviderDetails'
];
const mockResponse: PublicAppSettings = {
oidcEnabled: true,
remoteAuthEnabled: false,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
}
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service['fetchPublicSettings']().subscribe(settings => {
requiredFields.forEach(field => {
expect(settings).toHaveProperty(field);
expect(settings[field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for fetchAppSettings', () => {
httpClientMock.get.mockReturnValue(of({}));
service['fetchAppSettings']().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/settings$/));
});
it('should call correct endpoint for fetchPublicSettings', () => {
httpClientMock.get.mockReturnValue(of({}));
service['fetchPublicSettings']().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/public-settings$/));
});
it('should call correct endpoint for saveSettings', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/settings$/),
[{name: 'oidcEnabled', value: true}]
);
});
it('should call correct endpoint for toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.toggleOidcEnabled(true).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/settings$/),
[{name: 'OIDC_ENABLED', value: true}]
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for saveSettings', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.saveSettings([{key: 'remoteAuthEnabled', newValue: false}]).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
[{name: 'remoteAuthEnabled', value: false}]
);
});
it('should send correct structure for toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.toggleOidcEnabled(false).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
[{name: 'OIDC_ENABLED', value: false}]
);
});
});
describe('Response type contract', () => {
it('should expect AppSettings from fetchAppSettings', () => {
const mockSettings: AppSettings = {
autoBookSearch: true,
similarBookRecommendation: false,
defaultMetadataRefreshOptions: {} as any,
libraryMetadataRefreshOptions: [],
uploadPattern: '',
opdsServerEnabled: false,
komgaApiEnabled: false,
komgaGroupUnknown: false,
remoteAuthEnabled: false,
oidcEnabled: true,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
},
oidcAutoProvisionDetails: {
enableAutoProvisioning: false,
defaultPermissions: [],
defaultLibraryIds: []
},
maxFileUploadSizeInMb: 0,
metadataProviderSettings: {
amazon: {enabled: false, cookie: '', domain: ''},
google: {enabled: false, language: ''},
goodReads: {enabled: false},
hardcover: {enabled: false, apiKey: ''},
comicvine: {enabled: false, apiKey: ''},
douban: {enabled: false},
lubimyczytac: {enabled: false},
ranobedb: {enabled: false}
},
metadataMatchWeights: {
title: 0,
subtitle: 0,
description: 0,
authors: 0,
publisher: 0,
publishedDate: 0,
seriesName: 0,
seriesNumber: 0,
seriesTotal: 0,
isbn13: 0,
isbn10: 0,
language: 0,
pageCount: 0,
categories: 0,
amazonRating: 0,
amazonReviewCount: 0,
goodreadsRating: 0,
goodreadsReviewCount: 0,
hardcoverRating: 0,
hardcoverReviewCount: 0,
doubanRating: 0,
doubanReviewCount: 0,
lubimyczytacRating: 0,
ranobedbRating: 0,
coverImage: 0
},
metadataPersistenceSettings: {
moveFilesToLibraryPattern: false,
saveToOriginalFile: {
epub: {enabled: false, maxFileSizeInMb: 0},
pdf: {enabled: false, maxFileSizeInMb: 0},
cbx: {enabled: false, maxFileSizeInMb: 0}
},
convertCbrCb7ToCbz: false
},
metadataPublicReviewsSettings: {
downloadEnabled: false,
autoDownloadEnabled: false,
providers: []
},
koboSettings: {
convertToKepub: false,
conversionLimitInMb: 0,
conversionImageCompressionPercentage: 0,
convertCbxToEpub: false,
conversionLimitInMbForCbx: 0,
forceEnableHyphenation: false
},
coverCroppingSettings: {
verticalCroppingEnabled: false,
horizontalCroppingEnabled: false,
aspectRatioThreshold: 0,
smartCroppingEnabled: false
},
metadataDownloadOnBookdrop: false,
telemetryEnabled: false,
metadataProviderSpecificFields: {
asin: false,
amazonRating: false,
amazonReviewCount: false,
googleId: false,
goodreadsId: false,
goodreadsRating: false,
goodreadsReviewCount: false,
hardcoverId: false,
hardcoverBookId: false,
hardcoverRating: false,
hardcoverReviewCount: false,
comicvineId: false,
lubimyczytacId: false,
lubimyczytacRating: false,
ranobedbId: false,
ranobedbRating: false
}
};
httpClientMock.get.mockReturnValue(of(mockSettings));
service['fetchAppSettings']().subscribe(settings => {
expect(settings).toHaveProperty('oidcEnabled');
expect(settings).toHaveProperty('remoteAuthEnabled');
expect(settings).toHaveProperty('oidcProviderDetails');
});
});
it('should expect PublicAppSettings from fetchPublicSettings', () => {
const mockSettings: PublicAppSettings = {
oidcEnabled: false,
remoteAuthEnabled: true,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
}
};
httpClientMock.get.mockReturnValue(of(mockSettings));
service['fetchPublicSettings']().subscribe(settings => {
expect(settings).toHaveProperty('oidcEnabled');
expect(settings).toHaveProperty('remoteAuthEnabled');
expect(settings).toHaveProperty('oidcProviderDetails');
});
});
});
});
@@ -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}`);
}
}
}
@@ -1,310 +0,0 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of} from 'rxjs';
import {AuthService} from './auth.service';
import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc';
import {Router} from '@angular/router';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
import {RxStompService} from '../websocket/rx-stomp.service';
describe('AuthService', () => {
let service: AuthService;
let httpClientMock: any;
let oAuthServiceMock: any;
let oAuthStorageMock: any;
let routerMock: any;
let postLoginInitializerMock: any;
let rxStompServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
oAuthServiceMock = {
getIdToken: vi.fn().mockReturnValue('oidc-token')
};
oAuthStorageMock = {
removeItem: vi.fn()
};
routerMock = {
navigate: vi.fn()
};
postLoginInitializerMock = {
initialize: vi.fn().mockReturnValue(of(void 0))
};
rxStompServiceMock = {
updateConfig: vi.fn(),
activate: vi.fn(),
deactivate: vi.fn()
};
injectorMock = {
get: vi.fn((token: any) => {
if (token === RxStompService) return rxStompServiceMock;
return undefined;
})
};
vi.stubGlobal('localStorage', {
getItem: vi.fn().mockReturnValue(null),
setItem: vi.fn(),
removeItem: vi.fn()
});
TestBed.configureTestingModule({
providers: [
AuthService,
{provide: HttpClient, useValue: httpClientMock},
{provide: OAuthService, useValue: oAuthServiceMock},
{provide: OAuthStorage, useValue: oAuthStorageMock},
{provide: Router, useValue: routerMock},
{provide: PostLoginInitializerService, useValue: postLoginInitializerMock},
{provide: RxStompService, useValue: rxStompServiceMock},
{provide: 'Injector', useValue: injectorMock}
]
});
// Patch inject() for Injector
(AuthService.prototype as any).injector = injectorMock;
service = TestBed.inject(AuthService);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should save and get internal tokens', () => {
service.saveInternalTokens('access', 'refresh');
expect(localStorage.setItem).toHaveBeenCalledWith('accessToken_Internal', 'access');
expect(localStorage.setItem).toHaveBeenCalledWith('refreshToken_Internal', 'refresh');
expect(service.tokenSubject.value).toBe('access');
});
it('should get internal access and refresh tokens', () => {
(localStorage.getItem as any).mockImplementation((key: string) => key === 'accessToken_Internal' ? 'access' : 'refresh');
expect(service.getInternalAccessToken()).toBe('access');
expect(service.getInternalRefreshToken()).toBe('refresh');
});
it('should get OIDC access token', () => {
expect(service.getOidcAccessToken()).toBe('oidc-token');
});
it('should call internalLogin and save tokens', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.internalLogin({username: 'u', password: 'p'}).subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should call internalRefreshToken and save tokens', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.internalRefreshToken().subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should call remoteLogin and save tokens', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.remoteLogin().subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should clear OIDC tokens and navigate if no internal tokens', () => {
(localStorage.getItem as any).mockReturnValue(null);
service.clearOIDCTokens();
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token');
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
});
it('should not clear OIDC tokens if internal tokens exist', () => {
(localStorage.getItem as any).mockReturnValue('access');
service.clearOIDCTokens();
expect(oAuthStorageMock.removeItem).not.toHaveBeenCalled();
expect(routerMock.navigate).not.toHaveBeenCalled();
});
it('should logout and clear all tokens', () => {
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
routerMock.navigate.mockReturnValue(Promise.resolve(true));
service.logout();
expect(localStorage.removeItem).toHaveBeenCalledWith('accessToken_Internal');
expect(localStorage.removeItem).toHaveBeenCalledWith('refreshToken_Internal');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token');
expect(rxStompServiceMock.deactivate).toHaveBeenCalled();
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
});
it('should initialize websocket connection if token exists', () => {
vi.spyOn(service, 'getOidcAccessToken').mockReturnValue('token');
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
service['postLoginInitialized'] = false;
service.initializeWebSocketConnection();
expect(rxStompServiceMock.updateConfig).toHaveBeenCalled();
expect(rxStompServiceMock.activate).toHaveBeenCalled();
});
it('should not initialize websocket connection if no token', () => {
vi.spyOn(service, 'getOidcAccessToken').mockReturnValue(null);
vi.spyOn(service, 'getInternalAccessToken').mockReturnValue(null);
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
service.initializeWebSocketConnection();
expect(rxStompServiceMock.updateConfig).not.toHaveBeenCalled();
expect(rxStompServiceMock.activate).not.toHaveBeenCalled();
});
it('should call postLoginInitializer only once', () => {
service['postLoginInitialized'] = false;
service['handleSuccessfulAuth']();
expect(postLoginInitializerMock.initialize).toHaveBeenCalled();
service['handleSuccessfulAuth']();
expect(postLoginInitializerMock.initialize).toHaveBeenCalledTimes(1);
});
it('should get RxStompService from injector', () => {
service['rxStompService'] = undefined;
expect(service.getRxStompService()).toBe(rxStompServiceMock);
expect(service.getRxStompService()).toBe(rxStompServiceMock); // cached
});
});
describe('AuthService - API Contract Tests', () => {
let service: AuthService;
let httpClientMock: any;
let oAuthServiceMock: any;
let oAuthStorageMock: any;
let routerMock: any;
let postLoginInitializerMock: any;
let rxStompServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
oAuthServiceMock = {getIdToken: vi.fn()};
oAuthStorageMock = {removeItem: vi.fn()};
routerMock = {navigate: vi.fn()};
postLoginInitializerMock = {initialize: vi.fn().mockReturnValue(of(void 0))};
rxStompServiceMock = {updateConfig: vi.fn(), activate: vi.fn(), deactivate: vi.fn()};
injectorMock = {get: vi.fn((token: any) => rxStompServiceMock)};
vi.stubGlobal('localStorage', {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn()
});
TestBed.configureTestingModule({
providers: [
AuthService,
{provide: HttpClient, useValue: httpClientMock},
{provide: OAuthService, useValue: oAuthServiceMock},
{provide: OAuthStorage, useValue: oAuthStorageMock},
{provide: Router, useValue: routerMock},
{provide: PostLoginInitializerService, useValue: postLoginInitializerMock},
{provide: RxStompService, useValue: rxStompServiceMock},
{provide: 'Injector', useValue: injectorMock}
]
});
(AuthService.prototype as any).injector = injectorMock;
service = TestBed.inject(AuthService);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.internalLogin({username: 'u', password: 'p'}).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/login$/),
{username: 'u', password: 'p'}
);
});
it('should call correct endpoint for internalRefreshToken', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/refresh$/),
{refreshToken: 'refresh'}
);
});
it('should call correct endpoint for remoteLogin', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.remoteLogin().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/remote$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const payload = {username: 'user', password: 'pass'};
service.internalLogin(payload).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), payload);
});
it('should send correct structure for internalRefreshToken', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), {refreshToken: 'refresh'});
});
});
describe('Response type contract', () => {
it('should expect token object from internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.internalLogin({username: 'u', password: 'p'}).subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
expect(res).toHaveProperty('isDefaultPassword');
});
});
it('should expect token object from remoteLogin', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.remoteLogin().subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
expect(res).toHaveProperty('isDefaultPassword');
});
});
it('should expect token object from internalRefreshToken', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
});
});
});
});
@@ -1,264 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {BookMarkService, BookMark, CreateBookMarkRequest, UpdateBookMarkRequest} from './book-mark.service';
describe('BookMarkService', () => {
let service: BookMarkService;
let httpClientMock: any;
const mockBookmark: BookMark = {
id: 1,
userId: 2,
bookId: 3,
cfi: 'epubcfi(/6/2[cover]!/6)',
title: 'Bookmark 1',
color: 'yellow',
notes: 'note',
priority: 1,
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookMarkService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookMarkService);
});
it('should get bookmarks for a book', () => {
httpClientMock.get.mockReturnValue(of([mockBookmark]));
service.getBookmarksForBook(3).subscribe(bookmarks => {
expect(bookmarks).toEqual([mockBookmark]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3'));
});
});
it('should create a bookmark', () => {
httpClientMock.post.mockReturnValue(of(mockBookmark));
const req: CreateBookMarkRequest = {bookId: 3, cfi: 'epubcfi(/6/2[cover]!/6)', title: 'Bookmark 1'};
service.createBookmark(req).subscribe(bm => {
expect(bm).toEqual(mockBookmark);
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
it('should update a bookmark', () => {
httpClientMock.put.mockReturnValue(of(mockBookmark));
const req: UpdateBookMarkRequest = {title: 'Updated', notes: 'Updated note'};
service.updateBookmark(1, req).subscribe(bm => {
expect(bm).toEqual(mockBookmark);
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), req);
});
});
it('should delete a bookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(1).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
});
});
it('should handle getBookmarksForBook error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getBookmarksForBook(3).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle createBookmark error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createBookmark({bookId: 3, cfi: 'cfi'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle updateBookmark error', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.updateBookmark(1, {title: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle deleteBookmark error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
service.deleteBookmark(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
});
describe('BookMarkService - API Contract Tests', () => {
let service: BookMarkService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookMarkService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookMarkService);
});
describe('BookMark interface contract', () => {
it('should validate all required BookMark fields exist', () => {
const requiredFields: (keyof BookMark)[] = [
'id', 'bookId', 'cfi', 'title', 'createdAt'
];
const mockResponse: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getBookmarksForBook(2).subscribe(bookmarks => {
requiredFields.forEach(field => {
expect(bookmarks[0]).toHaveProperty(field);
expect(bookmarks[0][field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getBookmarksForBook', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getBookmarksForBook(5).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/bookmarks\/book\/5$/));
});
it('should call correct endpoint for createBookmark', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'};
service.createBookmark(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks$/),
req
);
});
it('should call correct endpoint for updateBookmark', () => {
httpClientMock.put.mockReturnValue(of({}));
const req: UpdateBookMarkRequest = {title: 't'};
service.updateBookmark(7, req).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks\/7$/),
req
);
});
it('should call correct endpoint for deleteBookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(8).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks\/8$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for createBookmark', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'};
service.createBookmark(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
it('should send correct structure for updateBookmark', () => {
httpClientMock.put.mockReturnValue(of({}));
const req: UpdateBookMarkRequest = {title: 't', notes: 'n'};
service.updateBookmark(9, req).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(expect.any(String), req);
});
});
describe('Response type contract', () => {
it('should expect BookMark[] from getBookmarksForBook', () => {
const mockBookmarks: BookMark[] = [{
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockBookmarks));
service.getBookmarksForBook(2).subscribe(bookmarks => {
expect(Array.isArray(bookmarks)).toBe(true);
expect(bookmarks[0]).toHaveProperty('id');
expect(bookmarks[0]).toHaveProperty('bookId');
});
});
it('should expect BookMark from createBookmark', () => {
const mockBookmark: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockBookmark));
service.createBookmark({bookId: 2, cfi: 'cfi', title: 't'}).subscribe(bm => {
expect(bm).toHaveProperty('id');
expect(bm).toHaveProperty('bookId');
});
});
it('should expect BookMark from updateBookmark', () => {
const mockBookmark: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.put.mockReturnValue(of(mockBookmark));
service.updateBookmark(1, {title: 't'}).subscribe(bm => {
expect(bm).toHaveProperty('id');
expect(bm).toHaveProperty('bookId');
});
});
it('should expect void from deleteBookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -7,7 +7,9 @@ export interface BookMark {
id: number;
userId?: number;
bookId: number;
cfi: string;
cfi?: string; // For EPUB bookmarks
positionMs?: number; // For audiobook bookmarks
trackIndex?: number; // For folder-based audiobooks
title: string;
color?: string;
notes?: string;
@@ -18,7 +20,9 @@ export interface BookMark {
export interface CreateBookMarkRequest {
bookId: number;
cfi: string;
cfi?: string; // For EPUB bookmarks
positionMs?: number; // For audiobook bookmarks
trackIndex?: number; // For folder-based audiobooks
title?: string;
}
@@ -1,215 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {BookNote, BookNoteService, CreateBookNoteRequest} from './book-note.service';
describe('BookNoteService', () => {
let service: BookNoteService;
let httpClientMock: any;
const mockNote: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 'Note Title',
content: 'Note content',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookNoteService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookNoteService);
});
it('should get notes for a book', () => {
httpClientMock.get.mockReturnValue(of([mockNote]));
service.getNotesForBook(3).subscribe(notes => {
expect(notes).toEqual([mockNote]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3'));
});
});
it('should create or update a note', () => {
httpClientMock.post.mockReturnValue(of(mockNote));
const req: CreateBookNoteRequest = {bookId: 3, title: 'Note Title', content: 'Note content'};
service.createOrUpdateNote(req).subscribe(note => {
expect(note).toEqual(mockNote);
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
it('should delete a note', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(1).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
});
});
it('should handle getNotesForBook error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getNotesForBook(3).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle createOrUpdateNote error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createOrUpdateNote({bookId: 3, title: 'fail', content: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle deleteNote error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
service.deleteNote(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
});
describe('BookNoteService - API Contract Tests', () => {
let service: BookNoteService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookNoteService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookNoteService);
});
describe('BookNote interface contract', () => {
it('should validate all required BookNote fields exist', () => {
const requiredFields: (keyof BookNote)[] = [
'id', 'userId', 'bookId', 'title', 'content', 'createdAt', 'updatedAt'
];
const mockResponse: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getNotesForBook(3).subscribe(notes => {
requiredFields.forEach(field => {
expect(notes[0]).toHaveProperty(field);
expect(notes[0][field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getNotesForBook', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getNotesForBook(5).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/book-notes\/book\/5$/));
});
it('should call correct endpoint for createOrUpdateNote', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'};
service.createOrUpdateNote(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/book-notes$/),
req
);
});
it('should call correct endpoint for deleteNote', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(8).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/book-notes\/8$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for createOrUpdateNote', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'};
service.createOrUpdateNote(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
describe('Response type contract', () => {
it('should expect BookNote[] from getNotesForBook', () => {
const mockNotes: BookNote[] = [{
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockNotes));
service.getNotesForBook(3).subscribe(notes => {
expect(Array.isArray(notes)).toBe(true);
expect(notes[0]).toHaveProperty('id');
expect(notes[0]).toHaveProperty('title');
});
});
it('should expect BookNote from createOrUpdateNote', () => {
const mockNote: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockNote));
service.createOrUpdateNote({bookId: 2, title: 't', content: 'c'}).subscribe(note => {
expect(note).toHaveProperty('id');
expect(note).toHaveProperty('title');
});
});
it('should expect void from deleteNote', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,317 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of} from 'rxjs';
import {CustomFontService} from './custom-font.service';
import {CustomFont, FontFormat} from '../model/custom-font.model';
import {AuthService} from './auth.service';
describe('CustomFontService', () => {
let service: CustomFontService;
let httpClientMock: any;
let authServiceMock: any;
let fontsSet: any[];
let originalDocumentFonts: any;
const mockFont: CustomFont = {
id: 1,
fontName: 'TestFont',
originalFileName: 'testfont.ttf',
format: FontFormat.TTF,
fileSize: 1024,
uploadedAt: '2024-01-01T00:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
getOidcAccessToken: vi.fn().mockReturnValue('token'),
getInternalAccessToken: vi.fn().mockReturnValue(null)
};
(globalThis as any).FontFace = function (family: string, source: string, descriptors?: any) {
this.family = family;
this.source = source;
this.descriptors = descriptors;
this.load = vi.fn().mockResolvedValue(this);
};
// Store original and create mock fonts set
originalDocumentFonts = document.fonts;
fontsSet = [];
// Mock document.fonts
Object.defineProperty(document, 'fonts', {
value: {
add: vi.fn((font: any) => fontsSet.push(font)),
delete: vi.fn((font: any) => {
const idx = fontsSet.indexOf(font);
if (idx !== -1) fontsSet.splice(idx, 1);
}),
[Symbol.iterator]: function* () {
yield* fontsSet;
}
},
writable: true,
configurable: true
});
TestBed.configureTestingModule({
providers: [
CustomFontService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService));
});
it('should initialize with empty fontsSubject', () => {
expect(service['fontsSubject'].value).toEqual([]);
});
it('should upload font and update cache', () => {
httpClientMock.post.mockReturnValue(of(mockFont));
const file = new File(['dummy'], 'testfont.ttf');
service.uploadFont(file, 'TestFont').subscribe(font => {
expect(font).toEqual(mockFont);
expect(service['fontsSubject'].value).toContainEqual(mockFont);
});
});
it('should get user fonts and update cache', () => {
httpClientMock.get.mockReturnValue(of([mockFont]));
service.getUserFonts().subscribe(fonts => {
expect(fonts).toEqual([mockFont]);
expect(service['fontsSubject'].value).toEqual([mockFont]);
});
});
it('should delete font and update cache', () => {
service['fontsSubject'].next([mockFont]);
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(1).subscribe(result => {
expect(result).toBeUndefined();
expect(service['fontsSubject'].value).toEqual([]);
});
});
it('should get font URL', () => {
expect(service.getFontUrl(123)).toMatch(/\/api\/v1\/custom-fonts\/123\/file$/);
});
it('should append token to URL', () => {
const url = 'http://test.com/font.ttf';
expect(service.appendToken(url)).toContain('token=');
});
it('should mark font as loaded after loadFontFace', async () => {
await service.loadFontFace(mockFont);
expect(service.isFontLoaded(mockFont.fontName)).toBe(true);
const fontsArr = Array.from(document.fonts);
expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(true);
});
it('should call removeFontFace on delete', () => {
const fontObj = new (globalThis as any).FontFace(mockFont.fontName, 'url(test.ttf)');
document.fonts.add(fontObj);
service['fontsSubject'].next([mockFont]);
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(mockFont.id).subscribe(() => {
const fontsArr = Array.from(document.fonts);
expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(false);
});
});
it('should handle loadAllFonts', async () => {
vi.spyOn(service, 'loadFontFace').mockResolvedValue(undefined);
await service.loadAllFonts([mockFont]);
expect(service.loadFontFace).toHaveBeenCalledWith(mockFont);
});
it('should return false for isFontLoaded if not loaded', () => {
expect(service.isFontLoaded('NotLoaded')).toBe(false);
});
});
describe('CustomFontService - API Contract Tests', () => {
let service: CustomFontService;
let httpClientMock: any;
let authServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
getOidcAccessToken: vi.fn().mockReturnValue('token'),
getInternalAccessToken: vi.fn().mockReturnValue(null)
};
TestBed.configureTestingModule({
providers: [
CustomFontService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService));
});
describe('CustomFont interface contract', () => {
it('should validate all required CustomFont fields exist', () => {
const requiredFields: (keyof CustomFont)[] = [
'id', 'fontName', 'originalFileName', 'format', 'fileSize', 'uploadedAt'
];
const mockResponse: CustomFont = {
id: 1,
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getUserFonts().subscribe(fonts => {
requiredFields.forEach(field => {
expect(fonts[0]).toHaveProperty(field);
expect(fonts[0][field]).toBeDefined();
});
});
});
it('should fail if API returns CustomFont without required id field', () => {
const invalidResponse = [{
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(invalidResponse));
service.getUserFonts().subscribe(fonts => {
expect(fonts[0]).not.toHaveProperty('id');
});
});
});
describe('Enum value contract', () => {
it('should validate FontFormat enum values from API', () => {
const validValues = [FontFormat.TTF, FontFormat.OTF, FontFormat.WOFF, FontFormat.WOFF2];
validValues.forEach(value => {
expect(Object.values(FontFormat)).toContain(value);
});
expect(Object.keys(FontFormat)).toHaveLength(4);
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getUserFonts', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getUserFonts().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts$/));
});
it('should call correct endpoint for uploadFont', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file, 'Font').subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/custom-fonts\/upload$/),
expect.any(FormData)
);
});
it('should call correct endpoint for deleteFont', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(123).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts\/123$/));
});
it('should call getFontUrl with correct format', () => {
expect(service.getFontUrl(42)).toMatch(/\/api\/v1\/custom-fonts\/42\/file$/);
});
});
describe('Request payload contract', () => {
it('should send FormData with file and fontName for uploadFont', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file, 'Font').subscribe();
const formData = httpClientMock.post.mock.calls[0][1];
expect(formData instanceof FormData).toBe(true);
expect(formData.has('file')).toBe(true);
expect(formData.has('fontName')).toBe(true);
});
it('should send FormData with only file if fontName not provided', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file).subscribe();
const formData = httpClientMock.post.mock.calls[0][1];
expect(formData instanceof FormData).toBe(true);
expect(formData.has('file')).toBe(true);
expect(formData.has('fontName')).toBe(false);
});
});
describe('Response type contract', () => {
it('should expect CustomFont array from getUserFonts', () => {
const mockFonts: CustomFont[] = [{
id: 1,
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockFonts));
service.getUserFonts().subscribe(fonts => {
expect(Array.isArray(fonts)).toBe(true);
expect(fonts[0]).toHaveProperty('id');
expect(fonts[0]).toHaveProperty('fontName');
});
});
it('should expect CustomFont from uploadFont', () => {
const mockFont: CustomFont = {
id: 2,
fontName: 'Font2',
originalFileName: 'font2.ttf',
format: FontFormat.OTF,
fileSize: 2048,
uploadedAt: '2024-01-02T00:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockFont));
const file = new File(['dummy'], 'font2.ttf');
service.uploadFont(file, 'Font2').subscribe(font => {
expect(font).toHaveProperty('id');
expect(font).toHaveProperty('fontName');
expect(font).toHaveProperty('format');
});
});
it('should expect void from deleteFont', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,174 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {DownloadProgressService} from './download-progress.service';
import {Subject, take} from 'rxjs';
describe('DownloadProgressService', () => {
let service: DownloadProgressService;
beforeEach(() => {
service = new DownloadProgressService();
});
it('should initialize with default state', () => {
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress).toEqual({
visible: false,
filename: '',
progress: 0,
loaded: 0,
total: 0
});
});
expect(service.isDownloadInProgress()).toBe(false);
});
it('should start a download and set state', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.visible).toBe(true);
expect(progress.filename).toBe('file.pdf');
expect(progress.progress).toBe(0);
expect(progress.cancelSubject).toBe(cancelSubject);
});
expect(service.isDownloadInProgress()).toBe(true);
});
it('should update progress and throttle updates', async () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
// First update should be immediate
service.updateProgress(50, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(50);
expect(progress.loaded).toBe(50);
expect(progress.total).toBe(100);
});
// Throttled update (simulate time)
vi.useFakeTimers();
service.updateProgress(60, 100);
// Should not emit immediately
let emitted = false;
service.downloadProgress$.subscribe(progress => {
if (progress.loaded === 60) emitted = true;
});
vi.advanceTimersByTime(100);
expect(emitted).toBe(true);
vi.useRealTimers();
});
it('should immediately update when progress is 100', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(100, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(100);
expect(progress.loaded).toBe(100);
expect(progress.total).toBe(100);
});
});
it('should complete download and reset state', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.completeDownload();
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.visible).toBe(false);
expect(progress.filename).toBe('');
expect(progress.progress).toBe(0);
});
expect(service.isDownloadInProgress()).toBe(false);
});
it('should cancel download and call cancelSubject', () => {
const cancelSubject = new Subject<void>();
const nextSpy = vi.fn();
const completeSpy = vi.fn();
cancelSubject.subscribe({next: nextSpy, complete: completeSpy});
service.startDownload('file.pdf', cancelSubject);
service.cancelDownload();
expect(nextSpy).toHaveBeenCalled();
expect(completeSpy).toHaveBeenCalled();
expect(service.isDownloadInProgress()).toBe(false);
});
});
describe('DownloadProgressService - API Contract Tests', () => {
let service: DownloadProgressService;
beforeEach(() => {
service = new DownloadProgressService();
});
describe('DownloadProgress interface contract', () => {
it('should have all required fields', () => {
const cancelSubject = new Subject<void>();
service.startDownload('test.txt', cancelSubject);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress).toHaveProperty('visible');
expect(progress).toHaveProperty('filename');
expect(progress).toHaveProperty('progress');
expect(progress).toHaveProperty('loaded');
expect(progress).toHaveProperty('total');
expect(progress).toHaveProperty('cancelSubject');
});
});
it('should allow cancelSubject to be undefined after complete', () => {
service.completeDownload();
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.cancelSubject).toBeUndefined();
});
});
});
describe('Behavior contract', () => {
it('should emit correct progress values', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(25, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(25);
expect(progress.loaded).toBe(25);
expect(progress.total).toBe(100);
});
});
it('should not exceed 100% progress', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(150, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(100);
});
});
it('should set progress to 0 if total is 0', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(50, 0);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(0);
});
});
});
describe('API contract', () => {
it('should expose downloadProgress$ as observable', () => {
expect(typeof service.downloadProgress$.subscribe).toBe('function');
});
it('should expose isDownloadInProgress as boolean', () => {
expect(typeof service.isDownloadInProgress()).toBe('boolean');
});
it('should expose startDownload, updateProgress, completeDownload, cancelDownload', () => {
expect(typeof service.startDownload).toBe('function');
expect(typeof service.updateProgress).toBe('function');
expect(typeof service.completeDownload).toBe('function');
expect(typeof service.cancelDownload).toBe('function');
});
});
});
@@ -7,6 +7,7 @@ export interface DownloadProgress {
progress: number;
loaded: number;
total: number;
preparing: boolean;
cancelSubject?: Subject<void>;
}
@@ -19,7 +20,8 @@ export class DownloadProgressService {
filename: '',
progress: 0,
loaded: 0,
total: 0
total: 0,
preparing: false
});
private lastUpdateTime = 0;
@@ -33,7 +35,7 @@ export class DownloadProgressService {
return this.downloadProgressSubject.value.visible;
}
startDownload(filename: string, cancelSubject: Subject<void>): void {
startDownload(filename: string, cancelSubject: Subject<void>, preparing: boolean = false): void {
this.lastUpdateTime = 0;
this.pendingUpdate = null;
if (this.throttleTimer) {
@@ -47,6 +49,7 @@ export class DownloadProgressService {
progress: 0,
loaded: 0,
total: 0,
preparing,
cancelSubject
});
}
@@ -62,6 +65,7 @@ export class DownloadProgressService {
progress,
loaded,
total,
preparing: false, // No longer preparing once we have progress
cancelSubject: current.cancelSubject
};
@@ -114,7 +118,8 @@ export class DownloadProgressService {
filename: '',
progress: 0,
loaded: 0,
total: 0
total: 0,
preparing: false
});
}
@@ -1,197 +0,0 @@
import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient, HttpEventType, HttpHeaders, HttpResponse} from '@angular/common/http';
import {of, Subject} from 'rxjs';
import {FileDownloadService} from './file-download.service';
import {DownloadProgressService} from './download-progress.service';
import {MessageService} from 'primeng/api';
describe('FileDownloadService', () => {
let service: FileDownloadService;
let httpClientMock: any;
let downloadProgressServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
downloadProgressServiceMock = {
isDownloadInProgress: vi.fn().mockReturnValue(false),
startDownload: vi.fn(),
updateProgress: vi.fn(),
completeDownload: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileDownloadService,
{provide: HttpClient, useValue: httpClientMock},
{provide: DownloadProgressService, useValue: downloadProgressServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
vi.useFakeTimers();
});
afterEach(() => {
vi.runAllTimers();
vi.useRealTimers();
});
it('should trigger download and handle progress and completion', () => {
const events = [
{type: HttpEventType.DownloadProgress, loaded: 50, total: 100},
{
type: HttpEventType.Response,
body: new Blob(['test']),
headers: new HttpHeaders(),
clone: () => this,
status: 200,
statusText: 'OK',
url: '',
ok: true
}
];
httpClientMock.get.mockReturnValue(of(...events));
// Mock DOM for download
const link = document.createElement('a');
vi.spyOn(link, 'click').mockImplementation(() => {});
vi.spyOn(document, 'createElement').mockReturnValue(link);
vi.spyOn(document.body, 'appendChild').mockImplementation(() => link);
vi.spyOn(document.body, 'removeChild').mockImplementation(() => link);
vi.spyOn(document.body, 'contains').mockReturnValue(true);
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:url');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
service.downloadFile('/api/file', 'file.txt');
expect(httpClientMock.get).toHaveBeenCalledWith('/api/file', expect.objectContaining({observe: 'events'}));
expect(downloadProgressServiceMock.startDownload).toHaveBeenCalledWith('file.txt', expect.any(Subject));
expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(50, 100);
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
it('should extract filename from Content-Disposition header', () => {
const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''test%20file.txt"});
const response = new HttpResponse({body: new Blob(['test']), headers});
const filename = (service as any).extractFilenameFromResponse(response, 'default.txt');
expect(filename).toBe('test file.txt');
});
it('should fallback to default filename if Content-Disposition is missing', () => {
const headers = new HttpHeaders();
const response = new HttpResponse({body: new Blob(['test']), headers});
const filename = (service as any).extractFilenameFromResponse(response, 'default.txt');
expect(filename).toBe('default.txt');
});
it('should throw if no file content received', () => {
const response = new HttpResponse({body: undefined, headers: new HttpHeaders()});
expect(() => (service as any).handleDownloadComplete(response, 'file.txt')).toThrow('No file content received');
});
});
describe('FileDownloadService - API Contract Tests', () => {
let service: FileDownloadService;
let httpClientMock: any;
let downloadProgressServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
downloadProgressServiceMock = {
isDownloadInProgress: vi.fn().mockReturnValue(false),
startDownload: vi.fn(),
updateProgress: vi.fn(),
completeDownload: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileDownloadService,
{provide: HttpClient, useValue: httpClientMock},
{provide: DownloadProgressService, useValue: downloadProgressServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
vi.useFakeTimers();
});
afterEach(() => {
vi.runAllTimers();
vi.useRealTimers();
});
describe('API contract', () => {
it('should expose downloadFile as a function', () => {
expect(typeof service.downloadFile).toBe('function');
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint and options for downloadFile', () => {
httpClientMock.get.mockReturnValue(of());
service.downloadFile('/api/file', 'file.txt');
expect(httpClientMock.get).toHaveBeenCalledWith(
'/api/file',
expect.objectContaining({
responseType: 'blob',
observe: 'events',
reportProgress: true
})
);
});
});
describe('Request/Response contract', () => {
it('should expect Blob in HttpResponse', () => {
const headers = new HttpHeaders();
const response = new HttpResponse({body: new Blob(['test']), headers});
expect((service as any).extractFilenameFromResponse(response, 'file.txt')).toBe('file.txt');
});
it('should handle Content-Disposition with encoded filename', () => {
const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''encoded%20file.pdf"});
const response = new HttpResponse({body: new Blob(['test']), headers});
expect((service as any).extractFilenameFromResponse(response, 'fallback.pdf')).toBe('encoded file.pdf');
});
});
describe('Behavior contract', () => {
it('should call startDownload and updateProgress on DownloadProgressService', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.DownloadProgress, loaded: 10, total: 20}));
service.downloadFile('/api/file', 'file.txt');
expect(downloadProgressServiceMock.startDownload).toHaveBeenCalled();
expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(10, 20);
});
it('should call completeDownload on finalize', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true}));
service.downloadFile('/api/file', 'file.txt');
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
});
it('should show success message on download complete', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true}));
service.downloadFile('/api/file', 'file.txt');
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
});
});
@@ -16,6 +16,9 @@ export class FileDownloadService {
downloadFile(url: string, defaultFilename: string): void {
const cancelSubject = new Subject<void>();
// Show preparing state immediately
this.downloadProgressService.startDownload(defaultFilename, cancelSubject, true);
this.initiateDownload(url)
.pipe(
takeUntil(cancelSubject),
@@ -55,9 +58,7 @@ export class FileDownloadService {
cancelSubject: Subject<void>
): void {
if (event.total) {
if (!this.downloadProgressService.isDownloadInProgress()) {
this.downloadProgressService.startDownload(defaultFilename, cancelSubject);
}
// Download already started with preparing state, just update progress
this.downloadProgressService.updateProgress(event.loaded, event.total);
}
}
@@ -1,139 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {FileMoveRequest, FileOperationsService} from './file-operations.service';
describe('FileOperationsService', () => {
let service: FileOperationsService;
let httpClientMock: any;
const mockRequest: FileMoveRequest = {
bookIds: [1, 2],
moves: [
{bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100},
{bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200}
]
};
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileOperationsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService));
});
it('should move files and return void', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.moveFiles(mockRequest).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/files\/move$/),
mockRequest
);
});
});
it('should handle move files error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.moveFiles(mockRequest).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('FileOperationsService - API Contract Tests', () => {
let service: FileOperationsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileOperationsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService));
});
describe('FileMoveRequest interface contract', () => {
it('should have required fields', () => {
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
expect(req).toHaveProperty('bookIds');
expect(req).toHaveProperty('moves');
expect(Array.isArray(req.bookIds)).toBe(true);
expect(Array.isArray(req.moves)).toBe(true);
expect(req.moves[0]).toHaveProperty('bookId');
expect(req.moves[0]).toHaveProperty('targetLibraryId');
expect(req.moves[0]).toHaveProperty('targetLibraryPathId');
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for moveFiles', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
service.moveFiles(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/files\/move$/),
req
);
});
});
describe('Request payload contract', () => {
it('should send FileMoveRequest with correct structure', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1, 2],
moves: [
{bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100},
{bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200}
]
};
service.moveFiles(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.any(String),
req
);
});
});
describe('Response type contract', () => {
it('should expect void from moveFiles', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
service.moveFiles(req).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,98 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of, Subject, take} from 'rxjs';
import {IconPickerService, IconSelection} from './icon-picker.service';
import {DialogLauncherService} from '../services/dialog-launcher.service';
describe('IconPickerService', () => {
let service: IconPickerService;
let dialogLauncherServiceMock: any;
beforeEach(() => {
dialogLauncherServiceMock = {
openIconPickerDialog: vi.fn()
};
TestBed.configureTestingModule({
providers: [
IconPickerService,
{provide: DialogLauncherService, useValue: dialogLauncherServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService));
});
it('should open icon picker dialog and return selection observable', () => {
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-book'};
const subject = new Subject<IconSelection>();
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: subject.asObservable()});
let result: IconSelection | undefined;
service.open().pipe(take(1)).subscribe(sel => {
result = sel;
});
subject.next(selection);
expect(result).toEqual(selection);
});
it('should call openIconPickerDialog on open()', () => {
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of({type: 'CUSTOM_SVG', value: '<svg></svg>'})});
service.open().pipe(take(1)).subscribe();
expect(dialogLauncherServiceMock.openIconPickerDialog).toHaveBeenCalled();
});
});
describe('IconPickerService - API Contract Tests', () => {
let service: IconPickerService;
let dialogLauncherServiceMock: any;
beforeEach(() => {
dialogLauncherServiceMock = {
openIconPickerDialog: vi.fn()
};
TestBed.configureTestingModule({
providers: [
IconPickerService,
{provide: DialogLauncherService, useValue: dialogLauncherServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService));
});
describe('IconSelection interface contract', () => {
it('should have required fields', () => {
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'};
expect(selection).toHaveProperty('type');
expect(selection).toHaveProperty('value');
expect(typeof selection.type).toBe('string');
expect(typeof selection.value).toBe('string');
});
it('should only allow valid type values', () => {
const validTypes = ['PRIME_NG', 'CUSTOM_SVG'];
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'};
expect(validTypes).toContain(selection.type);
});
});
describe('API contract', () => {
it('should expose open as a function', () => {
expect(typeof service.open).toBe('function');
});
it('should return Observable<IconSelection> from open()', () => {
const selection: IconSelection = {type: 'CUSTOM_SVG', value: '<svg></svg>'};
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of(selection)});
let result: IconSelection | undefined;
service.open().pipe(take(1)).subscribe(sel => {
result = sel;
});
expect(result).toEqual(selection);
});
});
});
@@ -1,111 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {MetadataMatchWeightsService} from './metadata-match-weights.service';
import {API_CONFIG} from '../../core/config/api-config';
describe('MetadataMatchWeightsService', () => {
let service: MetadataMatchWeightsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
MetadataMatchWeightsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataMatchWeightsService)
);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should call recalculateAll and return void', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`,
{}
);
});
});
it('should handle error from recalculateAll', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.recalculateAll().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('MetadataMatchWeightsService - API Contract Tests', () => {
let service: MetadataMatchWeightsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
MetadataMatchWeightsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(MetadataMatchWeightsService));
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`,
{}
);
});
});
describe('Request payload contract', () => {
it('should send empty object as payload for recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.any(String),
{}
);
});
});
describe('Response type contract', () => {
it('should expect void from recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,241 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of} from 'rxjs';
import {MetadataProgressService} from './metadata-progress.service';
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../model/metadata-batch-progress.model';
import {MetadataTaskService} from '../../features/book/service/metadata-task';
import {UserService} from '../../features/settings/user-management/user.service';
describe('MetadataProgressService', () => {
let service: MetadataProgressService;
let metadataTaskServiceMock: any;
let userServiceMock: any;
const mockUserState = {
user: {
permissions: {
admin: true,
canEditMetadata: true
}
}
};
const mockTasks: MetadataBatchProgressNotification[] = [
{taskId: '1', completed: 10, total: 100, message: '', status: MetadataBatchStatus.IN_PROGRESS, review: false},
{taskId: '2', completed: 100, total: 100, message: '', status: MetadataBatchStatus.COMPLETED, review: false}
];
beforeEach(() => {
metadataTaskServiceMock = {
getActiveTasks: vi.fn().mockReturnValue(of(mockTasks))
};
userServiceMock = {
userState$: of(mockUserState)
};
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataProgressService)
);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should initialize and fetch active tasks if user has permissions', () => {
expect(metadataTaskServiceMock.getActiveTasks).toHaveBeenCalled();
});
it('should not fetch active tasks if user has no permissions', () => {
userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}});
metadataTaskServiceMock.getActiveTasks.mockClear();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
TestBed.inject(MetadataProgressService);
expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled();
});
it('should handle incoming progress and update state', () => {
const progress: MetadataBatchProgressNotification = {
taskId: '3',
completed: 50,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let update: MetadataBatchProgressNotification | undefined;
const sub = service.progressUpdates$.subscribe(val => update = val);
service.handleIncomingProgress(progress);
expect(update).toEqual(progress);
expect(service.getActiveTasks()['3']).toEqual(progress);
sub.unsubscribe();
});
it('should clear task from active tasks', () => {
const progress: MetadataBatchProgressNotification = {
taskId: '4',
completed: 20,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
service.handleIncomingProgress(progress);
expect(service.getActiveTasks()['4']).toBeDefined();
service.clearTask('4');
expect(service.getActiveTasks()['4']).toBeUndefined();
});
it('should complete all subjects on destroy', () => {
const spy = vi.spyOn(service['progressUpdatesSubject'], 'complete');
service.ngOnDestroy();
expect(spy).toHaveBeenCalled();
});
});
describe('MetadataProgressService - API Contract Tests', () => {
let service: MetadataProgressService;
let metadataTaskServiceMock: any;
let userServiceMock: any;
beforeEach(() => {
metadataTaskServiceMock = {
getActiveTasks: vi.fn().mockReturnValue(of([]))
};
userServiceMock = {
userState$: of({
user: {
permissions: {
admin: true,
canEditMetadata: true
}
}
})
};
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataProgressService)
);
});
describe('MetadataBatchProgressNotification contract', () => {
it('should require taskId, completed, total, message, status, and review fields', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'abc',
completed: 42,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
expect(progress).toHaveProperty('taskId');
expect(progress).toHaveProperty('completed');
expect(progress).toHaveProperty('total');
expect(progress).toHaveProperty('message');
expect(progress).toHaveProperty('status');
expect(progress).toHaveProperty('review');
});
});
describe('Active tasks structure', () => {
it('should return an object with taskId keys and progress notification values', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'xyz',
completed: 99,
total: 100,
message: '',
status: MetadataBatchStatus.COMPLETED,
review: false
};
service.handleIncomingProgress(progress);
const active = service.getActiveTasks();
expect(active).toHaveProperty('xyz');
expect(active['xyz']).toEqual(progress);
});
});
describe('Observable contract', () => {
it('should emit progress updates on progressUpdates$', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'emit',
completed: 1,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let emitted: MetadataBatchProgressNotification | undefined;
const sub = service.progressUpdates$.subscribe(val => {
emitted = val;
});
service.handleIncomingProgress(progress);
expect(emitted).toEqual(progress);
sub.unsubscribe();
});
it('should emit active tasks on activeTasks$', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'active',
completed: 2,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let emitted: { [taskId: string]: MetadataBatchProgressNotification } | undefined;
const sub = service.activeTasks$.subscribe(val => {
emitted = val;
});
service.handleIncomingProgress(progress);
expect(emitted && emitted['active']).toEqual(progress);
sub.unsubscribe();
});
});
describe('Permissions contract', () => {
it('should only fetch tasks if user has admin or canEditMetadata', () => {
userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}});
metadataTaskServiceMock.getActiveTasks.mockClear();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
TestBed.inject(MetadataProgressService);
expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled();
});
});
});
@@ -1,84 +0,0 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {Title} from '@angular/platform-browser';
import {PageTitleService} from './page-title.service';
import {Book, BookType} from '../../features/book/model/book.model';
describe('PageTitleService', () => {
let service: PageTitleService;
let titleService: Title;
let setTitleMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
setTitleMock = vi.fn();
TestBed.configureTestingModule({
providers: [
PageTitleService,
{ provide: Title, useValue: { setTitle: setTitleMock } }
]
});
service = TestBed.inject(PageTitleService);
titleService = TestBed.inject(Title);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should set page title with setPageTitle', () => {
service.setPageTitle('Dashboard');
expect(setTitleMock).toHaveBeenCalledWith('Dashboard - BookLore');
});
it('should set book page title with all fields', () => {
const book: Book = {
id: 1,
bookType: 'PDF' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.pdf',
metadata: {
bookId: 1,
title: 'Book Title',
seriesName: 'Series',
authors: ['Author1', 'Author2']
}
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/Book Title (Series series) - by Author1 and Author2 (PDF) - BookLore'
);
});
it('should set book page title without series and authors', () => {
const book: Book = {
id: 1,
bookType: 'EPUB' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.epub',
metadata: {
bookId: 1,
title: 'Book Title'
}
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/Book Title (EPUB) - BookLore'
);
});
it('should set book page title with fallback to fileName', () => {
const book: Book = {
id: 1,
bookType: 'CBX' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.cbx'
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/file.cbx (CBX) - BookLore'
);
});
});
@@ -13,7 +13,7 @@ export class PageTitleService {
`${book.libraryName}/${book.metadata?.title || book.fileName}`,
book.metadata?.seriesName ? `(${book.metadata.seriesName} series)` : false,
book.metadata?.authors?.length ? `- by ${new Intl.ListFormat('en').format(book.metadata?.authors)}` : false,
`(${book.bookType})`
`(${book.primaryFile?.bookType})`
].filter(part => part);
this.setPageTitle(title.join(' '));
@@ -1,252 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {CreateReadingSessionDto, PageableResponse, ReadingSessionApiService, ReadingSessionResponse} from './reading-session-api.service';
import {BookType} from '../../features/book/model/book.model';
describe('ReadingSessionApiService', () => {
let service: ReadingSessionApiService;
let httpClientMock: any;
const BASE_URL = '/api/v1/reading-sessions';
const mockSessionDto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF' as BookType,
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s',
startProgress: 0,
endProgress: 10,
progressDelta: 10,
startLocation: 'start',
endLocation: 'end'
};
const mockPageableResponse: PageableResponse<ReadingSessionResponse> = {
content: [{
id: 1,
bookId: 1,
bookTitle: 'Book',
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
startProgress: 0,
endProgress: 10,
progressDelta: 10,
startLocation: 'start',
endLocation: 'end',
createdAt: '2024-01-01T00:10:01Z'
}],
pageable: {
pageNumber: 0,
pageSize: 5,
sort: {empty: true, sorted: false, unsorted: true},
offset: 0,
paged: true,
unpaged: false
},
totalElements: 1,
last: true,
totalPages: 1,
numberOfElements: 1,
first: true,
size: 5,
number: 0,
sort: {empty: true, sorted: false, unsorted: true},
empty: false
};
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
ReadingSessionApiService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService));
});
it('should call POST to createSession', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.createSession(mockSessionDto).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringContaining(BASE_URL),
mockSessionDto
);
});
});
it('should call GET to getSessionsByBookId with correct params', () => {
httpClientMock.get.mockReturnValue(of(mockPageableResponse));
service.getSessionsByBookId(1, 2, 10).subscribe(resp => {
expect(resp).toEqual(mockPageableResponse);
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringContaining(`${BASE_URL}/book/1`),
expect.objectContaining({
params: expect.any(HttpParams)
})
);
const params = httpClientMock.get.mock.calls[0][1].params;
expect(params.get('page')).toBe('2');
expect(params.get('size')).toBe('10');
});
});
it('should default to page=0 and size=5 if not provided', () => {
httpClientMock.get.mockReturnValue(of(mockPageableResponse));
service.getSessionsByBookId(2).subscribe();
const params = httpClientMock.get.mock.calls[0][1].params;
expect(params.get('page')).toBe('0');
expect(params.get('size')).toBe('5');
});
it('should handle error in createSession', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createSession(mockSessionDto).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should handle error in getSessionsByBookId', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getSessionsByBookId(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should send beacon successfully', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
vi.stubGlobal('navigator', {sendBeacon: sendBeaconMock});
const result = service.sendSessionBeacon(mockSessionDto);
expect(sendBeaconMock).toHaveBeenCalledWith(
expect.stringContaining(BASE_URL),
expect.any(Blob)
);
expect(result).toBe(true);
});
it('should return false if sendBeacon throws', () => {
vi.stubGlobal('navigator', {
sendBeacon: vi.fn().mockImplementation(() => {
throw new Error('fail');
})
});
const result = service.sendSessionBeacon(mockSessionDto);
expect(result).toBe(false);
});
});
describe('ReadingSessionApiService - API Contract Tests', () => {
let service: ReadingSessionApiService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
ReadingSessionApiService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService));
});
it('should call correct endpoint for createSession', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const dto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s'
};
service.createSession(dto).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions$/),
dto
);
});
it('should call correct endpoint for getSessionsByBookId', () => {
httpClientMock.get.mockReturnValue(of({content: []}));
service.getSessionsByBookId(123).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions\/book\/123$/),
expect.objectContaining({params: expect.any(HttpParams)})
);
});
it('should send beacon to correct endpoint', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
vi.stubGlobal('navigator', {sendBeacon: sendBeaconMock});
const dto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s'
};
service.sendSessionBeacon(dto);
expect(sendBeaconMock).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions$/),
expect.any(Blob)
);
});
it('should expect PageableResponse<ReadingSessionResponse> from getSessionsByBookId', () => {
const mockResponse: PageableResponse<ReadingSessionResponse> = {
content: [],
pageable: {
pageNumber: 0,
pageSize: 5,
sort: {empty: true, sorted: false, unsorted: true},
offset: 0,
paged: true,
unpaged: false
},
totalElements: 0,
last: true,
totalPages: 1,
numberOfElements: 0,
first: true,
size: 5,
number: 0,
sort: {empty: true, sorted: false, unsorted: true},
empty: true
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service.getSessionsByBookId(1).subscribe(resp => {
expect(resp).toHaveProperty('content');
expect(Array.isArray(resp.content)).toBe(true);
expect(resp).toHaveProperty('totalElements');
});
});
});
@@ -1,70 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of, throwError} from 'rxjs';
import {SettingsHelperService} from './settings-helper.service';
import {AppSettingsService} from './app-settings.service';
import {MessageService} from 'primeng/api';
describe('SettingsHelperService', () => {
let service: SettingsHelperService;
let appSettingsServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
appSettingsServiceMock = {
saveSettings: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
SettingsHelperService,
{provide: AppSettingsService, useValue: appSettingsServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(SettingsHelperService));
});
it('should call saveSettings and show success message on success', () => {
appSettingsServiceMock.saveSettings.mockReturnValue(of(void 0));
service.saveSetting('theme', 'dark').subscribe(result => {
expect(result).toBeUndefined();
expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'dark'}]);
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Settings Saved',
detail: 'The settings were successfully saved!'
});
});
});
it('should call saveSettings and show error message on error', () => {
appSettingsServiceMock.saveSettings.mockReturnValue(throwError(() => new Error('fail')));
service.saveSetting('theme', 'light').subscribe({
error: (err: any) => {
expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'light'}]);
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Error',
detail: 'There was an error saving the settings.'
});
expect(err).toBeInstanceOf(Error);
}
});
});
it('should show custom message via showMessage', () => {
service.showMessage('success', 'Yay', 'It worked!');
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Yay',
detail: 'It worked!'
});
});
});
@@ -1,362 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {UrlHelperService} from './url-helper.service';
import {AuthService} from './auth.service';
import {BookService} from '../../features/book/service/book.service';
import {Router, UrlTree} from '@angular/router';
import {Book} from '../../features/book/model/book.model';
import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component';
describe('UrlHelperService', () => {
let service: UrlHelperService;
let authServiceMock: any;
let bookServiceMock: any;
let routerMock: any;
beforeEach(() => {
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
bookServiceMock = {
getBookByIdFromState: vi.fn()
};
routerMock = {
createUrlTree: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UrlHelperService,
{provide: AuthService, useValue: authServiceMock},
{provide: BookService, useValue: bookServiceMock},
{provide: Router, useValue: routerMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService));
});
describe('Token handling', () => {
it('should append token from OIDC', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token');
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = (service as any).appendToken('http://test');
expect(url).toContain('token=oidc-token');
});
it('should append token from internal', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue('internal-token');
const url = (service as any).appendToken('http://test');
expect(url).toContain('token=internal-token');
});
it('should not append token if none present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = (service as any).appendToken('http://test');
expect(url).toBe('http://test');
});
it('should append token with correct separator', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect((service as any).appendToken('http://a')).toBe('http://a?token=tok');
expect((service as any).appendToken('http://a?x=1')).toBe('http://a?x=1&token=tok');
});
it('should handle empty string token gracefully', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('');
authServiceMock.getInternalAccessToken.mockReturnValue('');
const url = (service as any).appendToken('http://test');
expect(url).toBe('http://test');
});
it('should handle undefined url in appendToken', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect(() => (service as any).appendToken(undefined)).toThrow();
});
});
describe('getThumbnailUrl', () => {
it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => {
const book: Book = {id: 1, metadata: {title: 'T', authors: ['A']}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url');
const url = service.getThumbnailUrl(1);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url');
genSpy.mockRestore();
});
it('should use API url if coverUpdatedOn present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(2, 'v123');
expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?v123.*token=tok/);
});
it('should use API url if no book in state', () => {
bookServiceMock.getBookByIdFromState.mockReturnValue(undefined);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(3);
expect(url).toMatch(/\/api\/v1\/media\/book\/3\/thumbnail\?token=tok/);
});
it('should handle book with no metadata', () => {
const book: Book = {id: 1} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(1);
expect(url).toMatch(/\/api\/v1\/media\/book\/1\/thumbnail\?token=tok/);
});
it('should handle book with empty metadata', () => {
const book: Book = {id: 1, metadata: {}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url');
const url = service.getThumbnailUrl(1);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url');
genSpy.mockRestore();
});
it('should handle coverUpdatedOn with empty string', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(2, '');
expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?token=tok/);
});
});
describe('getThumbnailUrl1', () => {
it('should always use API url and append token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl1(4, 'v456');
expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?v456.*token=tok/);
});
it('should handle undefined coverUpdatedOn', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl1(4);
expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?token=tok/);
});
});
describe('getCoverUrl', () => {
it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => {
const book: Book = {id: 5, metadata: {title: 'T', authors: ['A']}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2');
const url = service.getCoverUrl(5);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url2');
genSpy.mockRestore();
});
it('should use API url if coverUpdatedOn present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(6, 'v789');
expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?v789.*token=tok/);
});
it('should use API url if no book in state', () => {
bookServiceMock.getBookByIdFromState.mockReturnValue(undefined);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(7);
expect(url).toMatch(/\/api\/v1\/media\/book\/7\/cover\?token=tok/);
});
it('should handle book with no metadata', () => {
const book: Book = {id: 5} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(5);
expect(url).toMatch(/\/api\/v1\/media\/book\/5\/cover\?token=tok/);
});
it('should handle book with empty metadata', () => {
const book: Book = {id: 5, metadata: {}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2');
const url = service.getCoverUrl(5);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url2');
genSpy.mockRestore();
});
it('should handle coverUpdatedOn with empty string', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(6, '');
expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?token=tok/);
});
});
describe('getBackupCoverUrl', () => {
it('should return backup cover url with token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getBackupCoverUrl(8);
expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover\?token=tok/);
});
it('should handle missing token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getBackupCoverUrl(8);
expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover$/);
});
});
describe('getBookdropCoverUrl', () => {
it('should return bookdrop cover url with token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getBookdropCoverUrl(9);
expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover\?token=tok/);
});
it('should handle missing token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getBookdropCoverUrl(9);
expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover$/);
});
});
describe('getBookUrl', () => {
it('should call router.createUrlTree with correct args', () => {
const book: Book = {id: 10} as any;
routerMock.createUrlTree.mockReturnValue('url-tree');
const urlTree = service.getBookUrl(book);
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', 10], {queryParams: {tab: 'view'}});
expect(urlTree).toBe('url-tree');
});
it('should handle book with undefined id', () => {
routerMock.createUrlTree.mockReturnValue('url-tree');
const minimalBook = {
id: undefined,
bookType: undefined,
libraryId: undefined,
libraryName: undefined
} as any;
const urlTree = service.getBookUrl(minimalBook);
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', undefined], {queryParams: {tab: 'view'}});
expect(urlTree).toBe('url-tree');
});
});
describe('filterBooksBy', () => {
it('should route to /series if filterKey is series', () => {
routerMock.createUrlTree.mockReturnValue('series-url');
const urlTree = service.filterBooksBy('series', 'My Series');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/series', encodeURIComponent('My Series')]);
expect(urlTree).toBe('series-url');
});
it('should route to /all-books with correct queryParams for other filters', () => {
routerMock.createUrlTree.mockReturnValue('all-books-url');
const urlTree = service.filterBooksBy('author', 'Author Name');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
{
queryParams: {
view: 'grid',
sort: 'title',
direction: 'asc',
sidebar: true,
filter: 'author:' + encodeURIComponent('Author Name')
}
}
);
expect(urlTree).toBe('all-books-url');
});
it('should handle empty filterValue', () => {
routerMock.createUrlTree.mockReturnValue('empty-filter-url');
const urlTree = service.filterBooksBy('author', '');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: 'author:'
})
})
);
expect(urlTree).toBe('empty-filter-url');
});
it('should handle empty filterKey', () => {
routerMock.createUrlTree.mockReturnValue('empty-key-url');
const urlTree = service.filterBooksBy('', 'SomeValue');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: ':' + encodeURIComponent('SomeValue')
})
})
);
expect(urlTree).toBe('empty-key-url');
});
});
});
describe('UrlHelperService - API Contract Tests', () => {
let service: UrlHelperService;
let authServiceMock: any;
let bookServiceMock: any;
let routerMock: any;
beforeEach(() => {
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
bookServiceMock = {
getBookByIdFromState: vi.fn()
};
routerMock = {
createUrlTree: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UrlHelperService,
{provide: AuthService, useValue: authServiceMock},
{provide: BookService, useValue: bookServiceMock},
{provide: Router, useValue: routerMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService));
});
it('should generate correct API endpoints for covers and thumbnails', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect(service.getThumbnailUrl1(11)).toMatch(/\/api\/v1\/media\/book\/11\/thumbnail\?token=tok/);
expect(service.getCoverUrl(12, 'v1')).toMatch(/\/api\/v1\/media\/book\/12\/cover\?v1.*token=tok/);
expect(service.getBackupCoverUrl(13)).toMatch(/\/api\/v1\/media\/book\/13\/backup-cover\?token=tok/);
expect(service.getBookdropCoverUrl(14)).toMatch(/\/api\/v1\/media\/bookdrop\/14\/cover\?token=tok/);
});
it('should encode filter values in filterBooksBy', () => {
routerMock.createUrlTree.mockReturnValue('tree');
service.filterBooksBy('author', 'A&B');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: 'author:' + encodeURIComponent('A&B')
})
})
);
});
it('should always return a string or UrlTree from getBookUrl/filterBooksBy', () => {
routerMock.createUrlTree.mockReturnValueOnce('tree1').mockReturnValueOnce({} as UrlTree);
expect(typeof service.getBookUrl({id: 1} as any)).toMatch(/string|object/);
expect(typeof service.filterBooksBy('series', 'X')).toMatch(/string|object/);
});
});
@@ -1,133 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {AppVersion, ReleaseNote, VersionService} from './version.service';
describe('VersionService', () => {
let service: VersionService;
let httpClientMock: any;
const mockVersion: AppVersion = {
current: '1.0.0',
latest: '1.2.0'
};
const mockChangelog: ReleaseNote[] = [
{
version: '1.2.0',
name: 'Release 1.2.0',
changelog: 'Bug fixes and improvements',
url: 'https://example.com/release/1.2.0',
publishedAt: '2024-01-01T00:00:00Z'
}
];
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(VersionService);
});
it('should get version', () => {
httpClientMock.get.mockReturnValue(of(mockVersion));
service.getVersion().subscribe(version => {
expect(version).toEqual(mockVersion);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/));
});
});
it('should get changelog', () => {
httpClientMock.get.mockReturnValue(of(mockChangelog));
service.getChangelog().subscribe(changelog => {
expect(changelog).toEqual(mockChangelog);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/));
});
});
it('should handle getVersion error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getVersion().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should handle getChangelog error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getChangelog().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('VersionService - API Contract Tests', () => {
let service: VersionService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(VersionService);
});
it('should expect AppVersion from getVersion', () => {
const response: AppVersion = {current: '1.0.0', latest: '1.2.0'};
httpClientMock.get.mockReturnValue(of(response));
service.getVersion().subscribe(version => {
expect(typeof version.current).toBe('string');
expect(typeof version.latest).toBe('string');
});
});
it('should expect ReleaseNote[] from getChangelog', () => {
const response: ReleaseNote[] = [
{
version: '1.2.0',
name: 'Release 1.2.0',
changelog: 'Bug fixes and improvements',
url: 'https://example.com/release/1.2.0',
publishedAt: '2024-01-01T00:00:00Z'
}
];
httpClientMock.get.mockReturnValue(of(response));
service.getChangelog().subscribe(notes => {
expect(Array.isArray(notes)).toBe(true);
expect(notes[0]).toHaveProperty('version');
expect(notes[0]).toHaveProperty('name');
expect(notes[0]).toHaveProperty('changelog');
expect(notes[0]).toHaveProperty('url');
expect(notes[0]).toHaveProperty('publishedAt');
});
});
it('should call correct endpoints', () => {
httpClientMock.get.mockReturnValue(of({}));
service.getVersion().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/));
service.getChangelog().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/));
});
});
@@ -14,6 +14,7 @@ export interface CoverImage {
export interface CoverFetchRequest {
title?: string;
author?: string;
squareCover?: boolean;
}
@Injectable({
@@ -0,0 +1,497 @@
// Shared Settings Component Styles
// This file provides consistent styling for all settings pages
// Benchmark: file-naming-pattern and metadata-persistence-settings components
// ============================================================================
// TYPOGRAPHY VARIABLES
// ============================================================================
$settings-page-title-size: 1.375rem;
$settings-page-title-weight: 700;
$settings-page-description-size: 0.875rem;
$settings-section-title-size: 1.25rem;
$settings-section-title-weight: 600;
$settings-section-title-icon-size: 1.125rem;
$settings-section-description-size: 0.875rem;
$settings-label-size: 0.9375rem;
$settings-label-weight: 500;
$settings-description-size: 0.8125rem;
// ============================================================================
// SPACING VARIABLES
// ============================================================================
$settings-card-padding: 1.5rem;
$settings-card-padding-mobile: 1rem;
$settings-card-gap: 1.25rem;
$settings-card-gap-mobile: 1rem;
$settings-card-border-radius: 8px;
$settings-section-body-padding-left: 1rem;
$settings-section-body-padding-left-mobile: 0.5rem;
$settings-section-body-gap: 1rem;
$settings-item-padding: 0.875rem 1rem;
$settings-item-padding-mobile: 0.75rem;
$settings-item-border-radius: 6px;
$settings-item-border-left-width: 3px;
// ============================================================================
// PAGE CONTAINER MIXIN
// For standalone pages with their own scrolling area
// ============================================================================
@mixin settings-page-container {
display: flex;
flex-direction: column;
gap: 1.5rem;
width: 100%;
height: calc(100dvh - 10.5rem);
overflow-y: auto;
padding: 0.5rem;
@media (min-width: 768px) {
height: calc(100dvh - 11.65rem);
padding: 0.5rem;
}
}
// ============================================================================
// PAGE HEADER
// Include this mixin at root level to get the .settings-header class
// ============================================================================
@mixin settings-page-header {
.settings-header {
margin-top: 1rem;
margin-bottom: 1.5rem;
border-bottom: 1px solid var(--p-content-border-color);
}
}
@mixin settings-page-title {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: $settings-page-title-size;
font-weight: $settings-page-title-weight;
color: var(--text-color);
margin: 0 0 0.5rem 0;
.pi {
color: var(--primary-color);
font-size: 1.25rem;
}
}
@mixin settings-page-description {
font-size: $settings-page-description-size;
line-height: 1.5;
color: var(--p-text-muted-color);
margin-bottom: 0.5rem;
}
// ============================================================================
// SETTINGS CARD MIXIN
// The main card container for a group of related settings
// ============================================================================
@mixin settings-card {
display: flex;
flex-direction: column;
gap: $settings-card-gap;
background: var(--card-background);
border: 1px solid var(--p-content-border-color);
border-radius: $settings-card-border-radius;
padding: $settings-card-padding;
@media (max-width: 768px) {
padding: $settings-card-padding-mobile;
gap: $settings-card-gap-mobile;
}
}
// ============================================================================
// SECTION HEADER MIXIN
// For section headers inside cards (with icon and description)
// ============================================================================
@mixin settings-section-header {
margin-bottom: 0.25rem;
}
@mixin settings-section-title {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: $settings-section-title-size;
font-weight: $settings-section-title-weight;
color: var(--text-color);
margin: 0 0 0.5rem 0;
.pi {
color: var(--primary-color);
font-size: $settings-section-title-icon-size;
}
}
@mixin settings-section-description {
font-size: $settings-section-description-size;
line-height: 1.5;
color: var(--p-text-muted-color);
margin: 0;
}
// ============================================================================
// SECTION BODY MIXIN
// Container for setting items within a card
// ============================================================================
@mixin settings-section-body {
display: flex;
flex-direction: column;
gap: $settings-section-body-gap;
padding-left: $settings-section-body-padding-left;
@media (max-width: 768px) {
padding-left: $settings-section-body-padding-left-mobile;
}
}
// ============================================================================
// SETTING ITEM MIXIN
// Individual setting row with left border accent
// ============================================================================
@mixin settings-item {
padding: $settings-item-padding;
border-radius: $settings-item-border-radius;
border-left: $settings-item-border-left-width solid var(--primary-color);
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
transition: border-color 0.2s ease, background 0.2s ease;
&:hover {
background: color-mix(in srgb, var(--ground-background) 40%, var(--p-surface-800) 60%);
}
@media (max-width: 768px) {
padding: $settings-item-padding-mobile;
}
}
// ============================================================================
// SETTING HEADER MIXIN
// Header row for a setting (toggle + label)
// ============================================================================
@mixin settings-item-header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 0.25rem;
.pi {
color: var(--primary-color);
font-size: 1rem;
}
}
@mixin settings-item-header-standalone {
margin-bottom: 0.25rem;
}
// ============================================================================
// SETTING LABEL MIXIN
// ============================================================================
@mixin settings-label {
font-weight: $settings-label-weight;
color: var(--text-color);
font-size: $settings-label-size;
}
// ============================================================================
// SETTING DESCRIPTION MIXIN
// ============================================================================
@mixin settings-item-description {
color: var(--p-text-muted-color);
font-size: $settings-description-size;
line-height: 1.4;
margin: 0;
}
// ============================================================================
// SETTING NOTE MIXIN
// ============================================================================
@mixin settings-note {
display: block;
margin-top: 0.25rem;
font-style: italic;
opacity: 0.85;
}
// ============================================================================
// SETTING OPTIONS MIXIN
// Expandable options section below a setting
// ============================================================================
@mixin settings-options {
margin-top: 0.75rem;
padding-top: 0.75rem;
border-top: 1px dashed var(--p-content-border-color);
}
// ============================================================================
// NOTICE MIXINS
// Warning and info notices
// ============================================================================
@mixin settings-notice-base {
display: flex;
align-items: flex-start;
gap: 0.75rem;
font-size: $settings-section-description-size;
line-height: 1.5;
padding: 0.75rem 1rem;
border-radius: 6px;
color: var(--text-color);
strong {
font-weight: 600;
}
@media (max-width: 768px) {
padding: 0.625rem 0.75rem;
font-size: $settings-description-size;
}
}
@mixin settings-warning-notice {
@include settings-notice-base;
background: color-mix(in srgb, var(--ground-background) 85%, var(--p-red-600) 15%);
border-left: 3px solid var(--p-red-500);
.pi-exclamation-triangle {
color: var(--p-red-400);
margin-top: 0.125rem;
flex-shrink: 0;
}
strong {
color: var(--p-red-300);
}
}
@mixin settings-info-notice {
@include settings-notice-base;
background: color-mix(in srgb, var(--ground-background) 90%, var(--p-blue-600) 10%);
border-left: 3px solid var(--p-blue-400);
.pi-info-circle {
color: var(--p-blue-400);
margin-top: 0.125rem;
flex-shrink: 0;
}
strong {
color: var(--p-blue-300);
}
}
// ============================================================================
// SECTION DIVIDER
// Include this mixin at root level to get the .section-divider class
// ============================================================================
@mixin settings-section-divider {
.section-divider {
padding-top: 1.5rem;
padding-bottom: 0.5rem;
hr {
border: none;
border-top: 1px solid var(--p-content-border-color);
margin: 0;
}
}
}
// ============================================================================
// ACTIONS ROW MIXIN
// For save/cancel buttons at the bottom of a section
// ============================================================================
@mixin settings-actions-row {
display: flex;
justify-content: flex-end;
padding-top: 0.5rem;
@media (max-width: 768px) {
p-button {
width: 100%;
}
}
}
// ============================================================================
// INPUT GROUP MIXINS
// Common input patterns
// ============================================================================
@mixin settings-filesize-input {
display: flex;
align-items: center;
gap: 0.5rem;
label {
font-size: $settings-description-size;
color: var(--p-text-muted-color);
white-space: nowrap;
}
.filesize-field {
width: 70px;
padding: 0.375rem 0.5rem;
border: 1px solid var(--p-content-border-color);
border-radius: 4px;
background: var(--ground-background);
color: var(--text-color);
font-size: $settings-section-description-size;
text-align: center;
transition: border-color 0.2s ease;
&:hover {
border-color: var(--primary-color);
}
&:focus {
outline: none;
border-color: var(--primary-color);
}
}
.filesize-unit {
font-size: $settings-description-size;
color: var(--p-text-muted-color);
}
.pi-info-circle {
color: var(--p-text-muted-color);
font-size: $settings-section-description-size;
cursor: help;
opacity: 0.7;
transition: opacity 0.2s ease;
&:hover {
opacity: 1;
}
}
}
@mixin settings-select-group {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
p-select {
min-width: 140px;
}
@media (max-width: 768px) {
flex-direction: column;
align-items: stretch;
p-select {
min-width: 100%;
}
}
}
// ============================================================================
// TABLE STYLES MIXIN
// For tables within settings cards
// ============================================================================
@mixin settings-table {
width: 100%;
border-radius: 6px;
overflow: hidden;
::ng-deep {
.p-datatable {
border: 1px solid var(--p-content-border-color);
border-radius: 6px;
overflow: hidden;
.p-datatable-thead > tr > th {
font-weight: 600;
padding: 0.75rem;
background: color-mix(in srgb, var(--text-color) 3%, transparent);
border-bottom: 1px solid var(--p-content-border-color);
font-size: $settings-description-size;
}
.p-datatable-tbody > tr {
&:hover {
background: color-mix(in srgb, var(--text-color) 3%, transparent);
}
> td {
padding: 0.625rem;
border-bottom: 1px solid color-mix(in srgb, var(--p-content-border-color) 50%, transparent);
}
&:last-child > td {
border-bottom: none;
}
}
}
}
}
// ============================================================================
// ERROR TEXT MIXIN
// ============================================================================
@mixin settings-error-text {
color: var(--p-red-400);
font-size: $settings-section-description-size;
}
// ============================================================================
// BUTTON GROUP MIXIN
// For toggle button selections
// ============================================================================
@mixin settings-button-group {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
.option-button {
display: flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
padding: 0.5rem 0.75rem;
border-radius: 0.375rem;
border: 1.5px solid color-mix(in srgb, var(--text-color) 20%, transparent);
background: color-mix(in srgb, var(--text-color) 5%, transparent);
color: var(--text-color);
cursor: pointer;
transition: all 0.2s ease;
font-size: $settings-description-size;
font-weight: $settings-label-weight;
min-width: 4.5rem;
i {
font-size: $settings-section-description-size;
}
.option-text {
white-space: nowrap;
}
&:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
border-color: color-mix(in srgb, var(--primary-color) 40%, transparent);
}
&.selected {
border-color: var(--primary-color);
background: color-mix(in srgb, var(--primary-color) 10%, transparent);
color: var(--primary-color);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 15%, transparent);
&:hover {
transform: translateY(-2px);
}
}
}
}