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:
@@ -25,6 +25,7 @@ import {UserStatsGuard} from './core/security/guards/user-stats.guard';
|
||||
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
|
||||
import {EbookReaderComponent} from './features/readers/ebook-reader';
|
||||
import {LibraryStatsComponent} from './features/stats/component/library-stats/library-stats.component';
|
||||
import {AudiobookReaderComponent} from './features/readers/audiobook-reader/audiobook-reader.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
@@ -73,6 +74,11 @@ export const routes: Routes = [
|
||||
component: CbxReaderComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'audiobook-reader/book/:bookId',
|
||||
component: AudiobookReaderComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'login',
|
||||
component: LoginComponent,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
describe('App', () => {
|
||||
it('should pass', () => {
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
});
|
||||
+236
-207
@@ -1,4 +1,4 @@
|
||||
<div class="main-container enclosing-container">
|
||||
<div class="main-container">
|
||||
<div class="settings-header">
|
||||
<h2 class="settings-title">
|
||||
<i class="pi pi-lock"></i>
|
||||
@@ -10,233 +10,262 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="settings-content">
|
||||
<div class="preferences-section">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-shield"></i>
|
||||
Internal Authentication
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Internal authentication is always enabled and cannot be disabled. However, OIDC can be used alongside internal authentication if OIDC is enabled.
|
||||
</p>
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-shield"></i>
|
||||
Authentication Methods
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Choose which authentication methods are available for users to sign in.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="auth-methods-list">
|
||||
<div class="auth-method-item is-active is-locked">
|
||||
<div class="auth-method-content">
|
||||
<div class="auth-method-header">
|
||||
<div class="auth-method-icon">
|
||||
<i class="pi pi-user"></i>
|
||||
</div>
|
||||
<div class="auth-method-info">
|
||||
<span class="auth-method-label">Internal Authentication</span>
|
||||
<span class="auth-method-status active">Always Enabled</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="auth-method-description">
|
||||
Built-in username and password authentication. This is the default method and cannot be disabled.
|
||||
</p>
|
||||
</div>
|
||||
<p-checkbox
|
||||
[(ngModel)]="internalAuthEnabled"
|
||||
[binary]="true"
|
||||
[disabled]="true">
|
||||
</p-checkbox>
|
||||
</div>
|
||||
|
||||
<div class="auth-method-item" [class.is-active]="oidcEnabled">
|
||||
<div class="auth-method-content">
|
||||
<div class="auth-method-header">
|
||||
<div class="auth-method-icon oidc">
|
||||
<i class="pi pi-key"></i>
|
||||
</div>
|
||||
<div class="auth-method-info">
|
||||
<span class="auth-method-label">
|
||||
OIDC Authentication
|
||||
<span class="experimental-badge">Experimental</span>
|
||||
</span>
|
||||
<span class="auth-method-status" [class.active]="oidcEnabled">
|
||||
{{ oidcEnabled ? 'Enabled' : 'Disabled' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="auth-method-description">
|
||||
OpenID Connect for single sign-on with external providers (Authentik, Keycloak, etc.).
|
||||
<app-external-doc-link docType="authentication"></app-external-doc-link>
|
||||
@if (!isOidcFormComplete() && !oidcEnabled) {
|
||||
<span class="config-hint">Configure settings below to enable.</span>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="oidcEnabled"
|
||||
[disabled]="!isOidcFormComplete()"
|
||||
(onChange)="toggleOidcEnabled()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-cog"></i>
|
||||
OIDC Provider Configuration
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Configure your OIDC provider settings. All fields are required to enable OIDC authentication.
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
label="Save"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcProvider()"
|
||||
[disabled]="!isOidcFormComplete()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-body">
|
||||
<div class="config-grid">
|
||||
<div class="config-item">
|
||||
<label for="providerName">Provider Name</label>
|
||||
<input
|
||||
pInputText
|
||||
id="providerName"
|
||||
[(ngModel)]="oidcProvider.providerName"
|
||||
placeholder="e.g. Authentik, Keycloak"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item">
|
||||
<label for="clientId">Client ID</label>
|
||||
<input
|
||||
pInputText
|
||||
id="clientId"
|
||||
[(ngModel)]="oidcProvider.clientId"
|
||||
placeholder="Your OIDC client ID"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item full-width">
|
||||
<label for="issuerUri">Issuer URI</label>
|
||||
<input
|
||||
pInputText
|
||||
id="issuerUri"
|
||||
[(ngModel)]="oidcProvider.issuerUri"
|
||||
placeholder="e.g. https://auth.example.com/realms/booklore"/>
|
||||
</div>
|
||||
|
||||
<div class="config-item full-width">
|
||||
<label for="scope">Scope</label>
|
||||
<input
|
||||
pInputText
|
||||
id="scope"
|
||||
[readonly]="true"
|
||||
disabled="disabled"
|
||||
value="openid profile email offline_access"/>
|
||||
<span class="field-hint">Required scopes for OIDC login. Must be supported by your provider.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="auth-option">
|
||||
<div class="auth-control">
|
||||
<label class="auth-label">Internal Authentication Enabled</label>
|
||||
<p-checkbox
|
||||
[(ngModel)]="internalAuthEnabled"
|
||||
[binary]="true"
|
||||
[disabled]="true">
|
||||
</p-checkbox>
|
||||
<div class="claims-section">
|
||||
<h4 class="subsection-title">Claim Mappings</h4>
|
||||
<p class="subsection-description">
|
||||
Map OIDC token claims to Booklore user fields. These must match your provider's token claims.
|
||||
</p>
|
||||
<div class="claims-grid">
|
||||
<div class="config-item">
|
||||
<label for="claimUsername">Username Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimUsername"
|
||||
[(ngModel)]="oidcProvider.claimMapping.username"
|
||||
placeholder="e.g. preferred_username"/>
|
||||
</div>
|
||||
<div class="config-item">
|
||||
<label for="claimEmail">Email Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimEmail"
|
||||
[(ngModel)]="oidcProvider.claimMapping.email"
|
||||
placeholder="e.g. email"/>
|
||||
</div>
|
||||
<div class="config-item">
|
||||
<label for="claimName">Display Name Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimName"
|
||||
[(ngModel)]="oidcProvider.claimMapping.name"
|
||||
placeholder="e.g. name"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="preferences-section">
|
||||
@if (oidcEnabled) {
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-key"></i>
|
||||
OIDC Authentication (Experimental)
|
||||
<app-external-doc-link docType="authentication"></app-external-doc-link>
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Configure external authentication providers using OpenID Connect (OIDC) protocol for seamless single sign-on integration.
|
||||
</p>
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-users"></i>
|
||||
User Provisioning
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Configure how new OIDC users are created and what permissions they receive.
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
label="Save"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
size="small"
|
||||
(click)="saveOidcAutoProvisionSettings()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<div class="auth-option">
|
||||
<div class="auth-control">
|
||||
<label class="auth-label">OIDC Enabled</label>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="oidcEnabled"
|
||||
[disabled]="!isOidcFormComplete()"
|
||||
(onChange)="toggleOidcEnabled()">
|
||||
</p-toggleswitch>
|
||||
@if (!isOidcFormComplete()) {
|
||||
<div class="auth-status">
|
||||
(Fill all required fields to enable)
|
||||
</div>
|
||||
}
|
||||
<div class="section-body">
|
||||
<div class="provisioning-toggle">
|
||||
<div class="toggle-content">
|
||||
<div class="toggle-info">
|
||||
<span class="toggle-label">Automatic User Provisioning</span>
|
||||
<span class="toggle-status" [class.active]="autoUserProvisioningEnabled">
|
||||
{{ autoUserProvisioningEnabled ? 'Enabled' : 'Disabled' }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="toggle-description">
|
||||
When enabled, new users are automatically created on first OIDC login with the permissions below.
|
||||
When disabled, users must be manually created in Booklore before they can log in via OIDC.
|
||||
</p>
|
||||
</div>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="autoUserProvisioningEnabled"
|
||||
inputId="autoProvision"
|
||||
(onChange)="saveOidcAutoProvisionSettings()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
|
||||
<div class="provider-section">
|
||||
<h4 class="subsection-title">OIDC Provider Settings</h4>
|
||||
<div class="provider-form">
|
||||
<div class="form-grid">
|
||||
<div class="form-field">
|
||||
<label for="providerName">Provider Name</label>
|
||||
<input
|
||||
pInputText
|
||||
id="providerName"
|
||||
[(ngModel)]="oidcProvider.providerName"
|
||||
placeholder="e.g. Authentik"
|
||||
class="full-width"/>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label for="clientId">Client ID</label>
|
||||
<input
|
||||
pInputText
|
||||
id="clientId"
|
||||
[(ngModel)]="oidcProvider.clientId"
|
||||
placeholder="e.g. my-client-id"
|
||||
class="full-width"/>
|
||||
</div>
|
||||
<div class="form-field form-field-full">
|
||||
<label for="scope">Scope</label>
|
||||
<input
|
||||
pInputText
|
||||
id="scope"
|
||||
class="full-width"
|
||||
[readonly]="true"
|
||||
disabled="disabled"
|
||||
value="openid profile email offline_access"/>
|
||||
<div class="field-info">
|
||||
<i class="pi pi-info-circle info-icon"></i>
|
||||
<span>
|
||||
Required scopes for OIDC login and token exchange. Must be supported and advertised in the provider's discovery metadata.
|
||||
</span>
|
||||
@if (autoUserProvisioningEnabled) {
|
||||
<div class="default-settings">
|
||||
<div class="permissions-group">
|
||||
<h4 class="group-title">Default Permissions</h4>
|
||||
<div class="permissions-grid">
|
||||
<div class="permission-item">
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
[disabled]="true"
|
||||
[ngModel]="true"
|
||||
inputId="permissionRead">
|
||||
</p-checkbox>
|
||||
<label for="permissionRead">Read Books</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-field form-field-full">
|
||||
<label for="issuerUri">Issuer URI</label>
|
||||
<input
|
||||
pInputText
|
||||
id="issuerUri"
|
||||
[(ngModel)]="oidcProvider.issuerUri"
|
||||
placeholder="e.g. https://authentik.domain.com/application/o/booklore/ or https://pocket-id.domain.com"
|
||||
class="full-width"/>
|
||||
</div>
|
||||
<div class="form-field form-field-full">
|
||||
<div class="claims-grid">
|
||||
<div class="form-field">
|
||||
<label for="claimUsername">Username Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimUsername"
|
||||
[(ngModel)]="oidcProvider.claimMapping.username"
|
||||
placeholder="e.g. preferred_username"
|
||||
class="full-width"/>
|
||||
@for (perm of availablePermissions; track perm) {
|
||||
<div class="permission-item">
|
||||
<p-checkbox
|
||||
[(ngModel)]="perm.selected"
|
||||
[binary]="true"
|
||||
[inputId]="perm.value">
|
||||
</p-checkbox>
|
||||
<label [for]="perm.value">{{ perm.label }}</label>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label for="claimEmail">Email Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimEmail"
|
||||
[(ngModel)]="oidcProvider.claimMapping.email"
|
||||
placeholder="e.g. email"
|
||||
class="full-width"/>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label for="claimName">Display Name Claim</label>
|
||||
<input
|
||||
pInputText
|
||||
id="claimName"
|
||||
[(ngModel)]="oidcProvider.claimMapping.name"
|
||||
placeholder="e.g. name or given_name"
|
||||
class="full-width"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field-info">
|
||||
<i class="pi pi-info-circle info-icon"></i>
|
||||
<span>
|
||||
These claims are used by Booklore to provision new OIDC users with their name, username, and email. Ensure they match the claims provided by your OIDC provider.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<p-button
|
||||
[outlined]="true"
|
||||
type="button"
|
||||
label="Save Settings"
|
||||
icon="pi pi-save"
|
||||
severity="success"
|
||||
(click)="saveOidcProvider()"
|
||||
[disabled]="!isOidcFormComplete()">
|
||||
</p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (oidcEnabled) {
|
||||
<div class="provisioning-section">
|
||||
<h4 class="subsection-title">OIDC User Provisioning</h4>
|
||||
<div class="provisioning-form">
|
||||
<div class="auth-option">
|
||||
<div class="auth-control">
|
||||
<label class="auth-label">Automatic user provisioning</label>
|
||||
<p-toggleswitch
|
||||
[(ngModel)]="autoUserProvisioningEnabled"
|
||||
inputId="autoProvision"
|
||||
(onChange)="saveOidcAutoProvisionSettings()">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
<div class="auth-info">
|
||||
<i class="pi pi-info-circle info-icon"></i>
|
||||
<span>
|
||||
Enabling auto-provisioning ensures that new users are automatically created with the selected default permissions. If turned off, users must be manually created in Booklore before they can log in.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (autoUserProvisioningEnabled) {
|
||||
<div class="permissions-section">
|
||||
<h5 class="permissions-title">Default permissions for auto-provisioned users</h5>
|
||||
<div class="permissions-list">
|
||||
<div class="permission-item">
|
||||
<p-checkbox
|
||||
[binary]="true"
|
||||
[disabled]="true"
|
||||
[ngModel]="true"
|
||||
inputId="permissionRead">
|
||||
</p-checkbox>
|
||||
<label for="permissionRead">Read Books</label>
|
||||
</div>
|
||||
@for (perm of availablePermissions; track perm) {
|
||||
<div class="permission-item">
|
||||
<p-checkbox
|
||||
[(ngModel)]="perm.selected"
|
||||
[binary]="true"
|
||||
[inputId]="perm.value">
|
||||
</p-checkbox>
|
||||
<label [for]="perm.value">{{ perm.label }}</label>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<h5 class="permissions-title">Default libraries for auto-provisioned users</h5>
|
||||
<div class="libraries-section">
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingLibraryIds"
|
||||
placeholder="Select Libraries"
|
||||
appendTo="body">
|
||||
</p-multiSelect>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
label="Save Settings"
|
||||
[outlined]="true"
|
||||
severity="success"
|
||||
(click)="saveOidcAutoProvisionSettings()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<div class="libraries-group">
|
||||
<h4 class="group-title">Default Library Access</h4>
|
||||
<p-multiSelect
|
||||
[options]="allLibraries"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
[(ngModel)]="editingLibraryIds"
|
||||
placeholder="Select libraries new users can access"
|
||||
appendTo="body"
|
||||
styleClass="libraries-select">
|
||||
</p-multiSelect>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
+270
-175
@@ -1,179 +1,204 @@
|
||||
@use '../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.main-container {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
height: calc(100dvh - 10.5rem);
|
||||
overflow-y: auto;
|
||||
border-width: 1px;
|
||||
border-radius: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
height: calc(100dvh - 11.65rem);
|
||||
}
|
||||
@include settings.settings-page-container;
|
||||
}
|
||||
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
|
||||
.settings-header {
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
@include settings.settings-page-header;
|
||||
|
||||
.settings-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.75rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
@include settings.settings-page-title;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.settings-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3rem;
|
||||
}
|
||||
|
||||
.preferences-section {
|
||||
@media (min-width: 768px) {
|
||||
padding: 0 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.5rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.section-description {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
margin-top: 0.125rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@include settings.settings-page-description;
|
||||
}
|
||||
|
||||
.settings-card {
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
background: var(--p-content-background);
|
||||
padding: 1.5rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
@include settings.settings-card;
|
||||
}
|
||||
|
||||
.auth-option {
|
||||
.section-header {
|
||||
@include settings.settings-section-header;
|
||||
}
|
||||
|
||||
.section-header-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.section-header-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
@include settings.settings-section-title;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.section-body {
|
||||
@include settings.settings-section-body;
|
||||
}
|
||||
|
||||
// Authentication Methods List
|
||||
.auth-methods-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.auth-label {
|
||||
font-weight: 500;
|
||||
color: var(--p-text-color);
|
||||
min-width: 6rem;
|
||||
}
|
||||
|
||||
.auth-info {
|
||||
.auth-method-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
padding-left: 1rem;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-left: 3px solid var(--p-content-border-color);
|
||||
border-radius: 6px;
|
||||
padding: 1rem;
|
||||
transition: border-color 0.2s ease, background 0.2s ease;
|
||||
|
||||
&:hover:not(.is-locked) {
|
||||
background: color-mix(in srgb, var(--ground-background) 40%, var(--p-surface-800) 60%);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
border-left-color: var(--p-green-500);
|
||||
}
|
||||
|
||||
&.is-locked {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.auth-method-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.auth-method-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.auth-method-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
|
||||
color: var(--p-primary-color);
|
||||
border-radius: 8px;
|
||||
flex-shrink: 0;
|
||||
|
||||
.pi {
|
||||
margin-top: 0.125rem;
|
||||
flex-shrink: 0;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
&.oidc {
|
||||
background: color-mix(in srgb, var(--p-orange-500) 15%, transparent);
|
||||
color: var(--p-orange-500);
|
||||
}
|
||||
}
|
||||
|
||||
.auth-status {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
|
||||
.provider-section,
|
||||
.provisioning-section {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.subsection-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.provider-form,
|
||||
.provisioning-form {
|
||||
.auth-method-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
gap: 0.125rem;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 1rem;
|
||||
.auth-method-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-weight: 600;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
.experimental-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.125rem 0.5rem;
|
||||
background: color-mix(in srgb, var(--p-orange-500) 15%, transparent);
|
||||
color: var(--p-orange-500);
|
||||
border-radius: 12px;
|
||||
font-size: 0.625rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.auth-method-status {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
&.active {
|
||||
color: var(--p-green-400);
|
||||
}
|
||||
}
|
||||
|
||||
.form-field {
|
||||
.auth-method-description {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
padding-left: calc(36px + 0.75rem);
|
||||
|
||||
@media (max-width: 600px) {
|
||||
padding-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.config-hint {
|
||||
display: block;
|
||||
color: var(--p-orange-400);
|
||||
font-weight: 500;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
// Configuration Grid
|
||||
.config-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.config-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
|
||||
&.form-field-full {
|
||||
@media (min-width: 768px) {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
&.full-width {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
label {
|
||||
@@ -181,57 +206,135 @@
|
||||
color: var(--p-text-color);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
// Claims Section
|
||||
.claims-section {
|
||||
margin-top: 1.5rem;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.subsection-title {
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.5rem 0;
|
||||
}
|
||||
|
||||
.subsection-description {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.5;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.claims-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 1rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
@media (max-width: 900px) {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.field-info {
|
||||
// Provisioning Toggle
|
||||
.provisioning-toggle {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
margin-top: 0.5rem;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-left: 3px solid var(--p-primary-color);
|
||||
border-radius: 6px;
|
||||
padding: 1rem;
|
||||
|
||||
.pi {
|
||||
margin-top: 0.125rem;
|
||||
flex-shrink: 0;
|
||||
@media (max-width: 600px) {
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
margin-top: 1rem;
|
||||
.toggle-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.permissions-section {
|
||||
.toggle-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.permissions-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
gap: 0.125rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.permissions-list {
|
||||
.toggle-label {
|
||||
font-weight: 600;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
.toggle-status {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
&.active {
|
||||
color: var(--p-green-400);
|
||||
}
|
||||
}
|
||||
|
||||
.toggle-description {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-text-muted-color);
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
// Default Settings (Permissions & Libraries)
|
||||
.default-settings {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.permissions-group,
|
||||
.libraries-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
padding-left: 1rem;
|
||||
}
|
||||
|
||||
.group-title {
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.permissions-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 0.625rem;
|
||||
padding-left: 0.5rem;
|
||||
}
|
||||
|
||||
.permission-item {
|
||||
@@ -246,15 +349,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
.libraries-section {
|
||||
padding-left: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.full-width {
|
||||
.libraries-select {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.info-icon {
|
||||
color: #3b82f6;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
<div class="add-physical-book">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-book header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">Add Physical Book</h2>
|
||||
<p class="panel-description">Catalog a physical book without a digital file</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
(click)="cancel()"
|
||||
severity="secondary"
|
||||
[text]="true"
|
||||
[rounded]="true"
|
||||
class="close-button"
|
||||
pTooltip="Close"
|
||||
tooltipPosition="left"/>
|
||||
</div>
|
||||
|
||||
<div class="form-container">
|
||||
<div class="form-group highlight-group">
|
||||
<label for="library" class="form-label">
|
||||
<i class="pi pi-folder label-icon"></i>
|
||||
Library
|
||||
<span class="required-indicator">*</span>
|
||||
</label>
|
||||
<p-select
|
||||
id="library"
|
||||
[options]="libraries"
|
||||
[(ngModel)]="selectedLibraryId"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
placeholder="Select a library"
|
||||
[style]="{'width': '100%'}"/>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-2">
|
||||
<label for="title" class="form-label">
|
||||
<i class="pi pi-tag label-icon"></i>
|
||||
Title
|
||||
</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="title"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="title"
|
||||
class="input-full"
|
||||
placeholder="e.g., The Great Gatsby"
|
||||
[class.filled]="title.trim()"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="isbn" class="form-label">
|
||||
<i class="pi pi-barcode label-icon"></i>
|
||||
ISBN
|
||||
</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
id="isbn"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="isbn"
|
||||
class="input-full"
|
||||
placeholder="e.g., 9780134685991"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label for="authors" class="form-label">
|
||||
<i class="pi pi-user label-icon"></i>
|
||||
Authors
|
||||
</label>
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete
|
||||
appendTo="body"
|
||||
[(ngModel)]="authors"
|
||||
[multiple]="true"
|
||||
[fluid]="true"
|
||||
[dropdown]="false"
|
||||
[suggestions]="filteredAuthors"
|
||||
[forceSelection]="false"
|
||||
[showClear]="false"
|
||||
placeholder="Type author name and press Enter"
|
||||
(completeMethod)="filterAuthors($event)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)"
|
||||
(onSelect)="onAutoCompleteSelect('authors', $event)">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label for="description" class="form-label">
|
||||
<i class="pi pi-align-left label-icon"></i>
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
id="description"
|
||||
pTextarea
|
||||
[(ngModel)]="description"
|
||||
rows="3"
|
||||
placeholder="Brief description of the book..."
|
||||
class="input-full"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="publisher" class="form-label">
|
||||
<i class="pi pi-building label-icon"></i>
|
||||
Publisher
|
||||
</label>
|
||||
<input
|
||||
id="publisher"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="publisher"
|
||||
class="input-full"
|
||||
placeholder="Publisher name"/>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="publishedDate" class="form-label">
|
||||
<i class="pi pi-calendar label-icon"></i>
|
||||
Published Date
|
||||
</label>
|
||||
<input
|
||||
id="publishedDate"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="publishedDate"
|
||||
class="input-full"
|
||||
placeholder="e.g., 2020 or 2020-05-15"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="language" class="form-label">
|
||||
<i class="pi pi-globe label-icon"></i>
|
||||
Language
|
||||
</label>
|
||||
<input
|
||||
id="language"
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="language"
|
||||
class="input-full"
|
||||
placeholder="e.g., English"/>
|
||||
</div>
|
||||
|
||||
<div class="form-group highlight-group flex-1">
|
||||
<label for="pageCount" class="form-label">
|
||||
<i class="pi pi-file label-icon"></i>
|
||||
Page Count
|
||||
</label>
|
||||
<p-inputnumber
|
||||
id="pageCount"
|
||||
[(ngModel)]="pageCount"
|
||||
[useGrouping]="false"
|
||||
placeholder="Number of pages"
|
||||
class="input-full">
|
||||
</p-inputnumber>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label for="categories" class="form-label">
|
||||
<i class="pi pi-tags label-icon"></i>
|
||||
Categories/Genres
|
||||
</label>
|
||||
<div class="autocomplete-wrapper">
|
||||
<p-autoComplete
|
||||
appendTo="body"
|
||||
[(ngModel)]="categories"
|
||||
[multiple]="true"
|
||||
[fluid]="true"
|
||||
[dropdown]="false"
|
||||
[suggestions]="filteredCategories"
|
||||
[forceSelection]="false"
|
||||
[showClear]="true"
|
||||
placeholder="Type category and press Enter"
|
||||
(completeMethod)="filterCategories($event)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp('categories', $event)"
|
||||
(onSelect)="onAutoCompleteSelect('categories', $event)">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dialog-footer">
|
||||
<div class="validation-status">
|
||||
@if (!selectedLibraryId) {
|
||||
<div class="validation-message error">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<span>Library is required</span>
|
||||
</div>
|
||||
} @else if (!title.trim() && !isbn.trim()) {
|
||||
<div class="validation-message error">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<span>Title or ISBN is required</span>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="validation-message success">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<span>Ready to create</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="footer-actions">
|
||||
<p-button
|
||||
label="Cancel"
|
||||
severity="secondary"
|
||||
[outlined]="true"
|
||||
(onClick)="cancel()"/>
|
||||
<p-button
|
||||
label="Add Physical Book"
|
||||
icon="pi pi-plus"
|
||||
severity="success"
|
||||
(onClick)="createBook()"
|
||||
[disabled]="!canCreate() || isLoading"
|
||||
[loading]="isLoading"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
@use '../../../../shared/styles/panel-shared' as panel;
|
||||
|
||||
.add-physical-book {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 700px;
|
||||
max-height: 90vh;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
min-width: auto;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
@include panel.panel-header;
|
||||
}
|
||||
|
||||
.form-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 1.25rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-top: none;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
|
||||
overflow-y: auto;
|
||||
max-height: calc(90vh - 200px);
|
||||
|
||||
@media (max-width: 480px) {
|
||||
padding: 0.75rem;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
|
||||
@media (max-width: 640px) {
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.flex-1 {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.flex-2 {
|
||||
flex: 2;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
|
||||
&.highlight-group {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
gap: 0.25rem;
|
||||
|
||||
&.highlight-group {
|
||||
padding: 0.375rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.form-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
|
||||
.label-icon {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.required-indicator {
|
||||
color: var(--p-red-500);
|
||||
margin-left: 0.125rem;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
.input-wrapper {
|
||||
position: relative;
|
||||
|
||||
.input-full {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
|
||||
.input-full {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.autocomplete-wrapper {
|
||||
width: 100%;
|
||||
|
||||
p-autocomplete {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
@include panel.dialog-footer;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.validation-message {
|
||||
@include panel.validation-message;
|
||||
}
|
||||
|
||||
::ng-deep {
|
||||
.p-inputnumber {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.p-inputnumber-input {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.p-autocomplete .p-chip .p-chip-label {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.p-autocomplete-input-chip {
|
||||
width: 2rem;
|
||||
}
|
||||
|
||||
.p-autocomplete-clearable ul {
|
||||
padding-inline-end: 2rem !important;
|
||||
}
|
||||
|
||||
.p-autocomplete-clearable .p-autocomplete-clear-icon {
|
||||
right: 0px;
|
||||
margin-top: -1rem;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Textarea} from 'primeng/textarea';
|
||||
import {InputNumber} from 'primeng/inputnumber';
|
||||
import {AutoComplete, AutoCompleteCompleteEvent} from 'primeng/autocomplete';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {Library} from '../../model/library.model';
|
||||
import {CreatePhysicalBookRequest} from '../../model/book.model';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
|
||||
@Component({
|
||||
selector: 'app-add-physical-book-dialog',
|
||||
standalone: true,
|
||||
templateUrl: './add-physical-book-dialog.component.html',
|
||||
imports: [
|
||||
FormsModule,
|
||||
Button,
|
||||
InputText,
|
||||
Tooltip,
|
||||
Select,
|
||||
Textarea,
|
||||
InputNumber,
|
||||
AutoComplete
|
||||
],
|
||||
styleUrl: './add-physical-book-dialog.component.scss',
|
||||
})
|
||||
export class AddPhysicalBookDialogComponent implements OnInit {
|
||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private dialogConfig = inject(DynamicDialogConfig);
|
||||
private bookService = inject(BookService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
|
||||
libraries: Library[] = [];
|
||||
selectedLibraryId: number | null = null;
|
||||
title: string = '';
|
||||
isbn: string = '';
|
||||
authors: string[] = [];
|
||||
description: string = '';
|
||||
publisher: string = '';
|
||||
publishedDate: string = '';
|
||||
language: string = '';
|
||||
pageCount: number | null = null;
|
||||
categories: string[] = [];
|
||||
|
||||
allAuthors: string[] = [];
|
||||
allCategories: string[] = [];
|
||||
filteredAuthors: string[] = [];
|
||||
filteredCategories: string[] = [];
|
||||
|
||||
isLoading: boolean = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.libraryService.libraryState$
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(state => {
|
||||
if (state.loaded && state.libraries) {
|
||||
this.libraries = state.libraries;
|
||||
if (this.dialogConfig.data?.libraryId) {
|
||||
this.selectedLibraryId = this.dialogConfig.data.libraryId;
|
||||
} else if (this.libraries.length > 0 && this.libraries[0].id !== undefined) {
|
||||
this.selectedLibraryId = this.libraries[0].id;
|
||||
}
|
||||
}
|
||||
});
|
||||
this.prepareAutoComplete();
|
||||
}
|
||||
|
||||
private prepareAutoComplete(): void {
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter((bookState) => bookState.loaded),
|
||||
take(1)
|
||||
)
|
||||
.subscribe((bookState) => {
|
||||
const authors = new Set<string>();
|
||||
const categories = new Set<string>();
|
||||
|
||||
(bookState.books ?? []).forEach((book) => {
|
||||
book.metadata?.authors?.forEach((author) => authors.add(author));
|
||||
book.metadata?.categories?.forEach((category) => categories.add(category));
|
||||
});
|
||||
|
||||
this.allAuthors = Array.from(authors);
|
||||
this.allCategories = Array.from(categories);
|
||||
});
|
||||
}
|
||||
|
||||
filterAuthors(event: AutoCompleteCompleteEvent): void {
|
||||
const query = event.query.toLowerCase();
|
||||
this.filteredAuthors = this.allAuthors.filter((author) =>
|
||||
author.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
filterCategories(event: AutoCompleteCompleteEvent): void {
|
||||
const query = event.query.toLowerCase();
|
||||
this.filteredCategories = this.allCategories.filter((category) =>
|
||||
category.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
onAutoCompleteKeyUp(fieldName: 'authors' | 'categories', event: KeyboardEvent): void {
|
||||
if (event.key === 'Enter') {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const value = input.value?.trim();
|
||||
if (value) {
|
||||
const values = this[fieldName];
|
||||
if (!values.includes(value)) {
|
||||
this[fieldName] = [...values, value];
|
||||
}
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onAutoCompleteSelect(fieldName: 'authors' | 'categories', event: { value: string, originalEvent: Event }): void {
|
||||
const values = this[fieldName];
|
||||
if (!values.includes(event.value)) {
|
||||
this[fieldName] = [...values, event.value];
|
||||
}
|
||||
(event.originalEvent.target as HTMLInputElement).value = '';
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.dynamicDialogRef.close();
|
||||
}
|
||||
|
||||
canCreate(): boolean {
|
||||
return !!this.selectedLibraryId && (!!this.title.trim() || !!this.isbn.trim());
|
||||
}
|
||||
|
||||
createBook(): void {
|
||||
if (!this.canCreate() || this.isLoading) return;
|
||||
|
||||
this.isLoading = true;
|
||||
|
||||
const request: CreatePhysicalBookRequest = {
|
||||
libraryId: this.selectedLibraryId!,
|
||||
title: this.title.trim() || undefined,
|
||||
isbn: this.isbn.trim() || undefined,
|
||||
authors: this.authors.length > 0 ? this.authors : undefined,
|
||||
description: this.description.trim() || undefined,
|
||||
publisher: this.publisher.trim() || undefined,
|
||||
publishedDate: this.publishedDate.trim() || undefined,
|
||||
language: this.language.trim() || undefined,
|
||||
pageCount: this.pageCount ?? undefined,
|
||||
categories: this.categories.length > 0 ? this.categories : undefined
|
||||
};
|
||||
|
||||
this.bookService.createPhysicalBook(request).subscribe({
|
||||
next: (book) => {
|
||||
this.isLoading = false;
|
||||
this.dynamicDialogRef.close(book);
|
||||
},
|
||||
error: () => {
|
||||
this.isLoading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -370,7 +370,7 @@
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (userState.user!.permissions.canMoveOrganizeFiles) {
|
||||
@if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-arrows-h"
|
||||
@@ -380,6 +380,17 @@
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (userState.user!.permissions.canManageLibrary || userState.user!.permissions.admin) {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-link"
|
||||
severity="info"
|
||||
(click)="attachFilesToBook()"
|
||||
[disabled]="!canAttachFiles()"
|
||||
pTooltip="Attach to Another Book"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (hasBulkReadActionsItems) {
|
||||
<div class="more-actions-wrapper">
|
||||
<p-button
|
||||
|
||||
@@ -53,6 +53,7 @@ import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-pa
|
||||
import {BookBrowserEntityService} from './book-browser-entity.service';
|
||||
import {BookFilterOrchestrationService} from './book-filter-orchestration.service';
|
||||
import {BookBrowserScrollService} from './book-browser-scroll.service';
|
||||
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
|
||||
|
||||
export enum EntityType {
|
||||
LIBRARY = 'Library',
|
||||
@@ -97,6 +98,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
protected taskHelperService = inject(TaskHelperService);
|
||||
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
|
||||
protected bookSelectionService = inject(BookSelectionService);
|
||||
protected appSettingsService = inject(AppSettingsService);
|
||||
|
||||
private activatedRoute = inject(ActivatedRoute);
|
||||
private router = inject(Router);
|
||||
@@ -730,6 +732,60 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
||||
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
|
||||
}
|
||||
|
||||
attachFilesToBook(): void {
|
||||
// Get selected books that are single-file books (no alternative formats)
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedBookIds = Array.from(this.selectedBooks);
|
||||
const sourceBooks = (currentState.books || []).filter(book =>
|
||||
selectedBookIds.includes(book.id) && !book.alternativeFormats?.length
|
||||
);
|
||||
|
||||
if (sourceBooks.length === 0) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'No Eligible Books',
|
||||
detail: 'Selected books must be single-file books (no alternative formats).'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if all books are from the same library
|
||||
const libraryIds = new Set(sourceBooks.map(b => b.libraryId));
|
||||
if (libraryIds.size > 1) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'Multiple Libraries',
|
||||
detail: 'All selected books must be from the same library.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.dynamicDialogRef = this.dialogHelperService.openBulkBookFileAttacherDialog(sourceBooks);
|
||||
if (this.dynamicDialogRef) {
|
||||
this.dynamicDialogRef.onClose.subscribe(result => {
|
||||
if (result?.success) {
|
||||
this.bookSelectionService.deselectAll();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
canAttachFiles(): boolean {
|
||||
if (this.selectedBooks.size === 0) return false;
|
||||
|
||||
const currentState = this.bookService.getCurrentBookState();
|
||||
const selectedBookIds = Array.from(this.selectedBooks);
|
||||
const eligibleBooks = (currentState.books || []).filter(book =>
|
||||
selectedBookIds.includes(book.id) && !book.alternativeFormats?.length
|
||||
);
|
||||
|
||||
if (eligibleBooks.length === 0) return false;
|
||||
|
||||
// Check if all eligible books are from the same library
|
||||
const libraryIds = new Set(eligibleBooks.map(b => b.libraryId));
|
||||
return libraryIds.size === 1;
|
||||
}
|
||||
|
||||
user() {
|
||||
return this.userService.getCurrentUser();
|
||||
}
|
||||
|
||||
+6
-5
@@ -2,20 +2,21 @@
|
||||
[class.selected]="isSelected"
|
||||
(click)="onCardClick($event)">
|
||||
|
||||
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive, 'loaded': isImageLoaded }">
|
||||
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive, 'loaded': isImageLoaded, 'audiobook-cover': _isAudiobook }">
|
||||
<img
|
||||
[src]="coverImageUrl"
|
||||
class="book-cover"
|
||||
[class.loaded]="isImageLoaded"
|
||||
[class.square-cover]="_isAudiobook"
|
||||
[alt]="'Cover of ' + displayTitle"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
(load)="onImageLoad()"/>
|
||||
|
||||
<div class="top-left-overlay-stack">
|
||||
@if (showBookTypePill && book.bookType) {
|
||||
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + book.bookType.toLowerCase()">
|
||||
{{ book.bookType }}
|
||||
@if (showBookTypePill && getDisplayFormat(); as displayFormat) {
|
||||
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + displayFormat.toLowerCase()">
|
||||
{{ displayFormat }}
|
||||
</div>
|
||||
}
|
||||
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
|
||||
@@ -36,7 +37,7 @@
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)"></p-button>
|
||||
}
|
||||
|
||||
@if (!_isSeriesViewActive) {
|
||||
@if (!_isSeriesViewActive && hasDigitalFile()) {
|
||||
<p-button [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
|
||||
}
|
||||
|
||||
|
||||
+48
-1
@@ -24,7 +24,6 @@
|
||||
.book-cover {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
border-radius: 8px 8px 0 0;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease-in;
|
||||
@@ -34,6 +33,14 @@
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.book-cover.square-cover {
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.cover-container.audiobook-cover {
|
||||
background-color: var(--surface-ground);
|
||||
}
|
||||
|
||||
.cover-container::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
@@ -288,6 +295,46 @@
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-audiobook {
|
||||
background: var(--book-type-audiobook-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-m4b {
|
||||
background: var(--book-type-m4b-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-mp3 {
|
||||
background: var(--book-type-mp3-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-m4a {
|
||||
background: var(--book-type-m4a-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cbz {
|
||||
background: var(--book-type-cbz-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cbr {
|
||||
background: var(--book-type-cbr-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-cb7 {
|
||||
background: var(--book-type-cb7-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.book-type-physical {
|
||||
background: var(--book-type-physical-color);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.read-status-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+37
-2
@@ -24,6 +24,7 @@ import {BookDialogHelperService} from '../book-dialog-helper.service';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {BookNavigationService} from '../../../service/book-navigation.service';
|
||||
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card',
|
||||
@@ -66,6 +67,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
private bookDialogHelperService = inject(BookDialogHelperService);
|
||||
private bookNavigationService = inject(BookNavigationService);
|
||||
private cdr = inject(ChangeDetectorRef);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
|
||||
protected _progressPercentage: number | null = null;
|
||||
protected _koProgressPercentage: number | null = null;
|
||||
@@ -80,11 +82,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
protected _seriesCountTooltip: string = '';
|
||||
protected _titleTooltip: string = '';
|
||||
protected _hasProgress: boolean = false;
|
||||
protected _isAudiobook: boolean = false;
|
||||
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
private destroy$ = new Subject<void>();
|
||||
protected readStatusHelper = inject(ReadStatusHelper);
|
||||
private user: User | null = null;
|
||||
private diskType: string = 'LOCAL';
|
||||
private menuInitialized = false;
|
||||
|
||||
showBookTypePill = true;
|
||||
@@ -104,6 +108,16 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route';
|
||||
});
|
||||
|
||||
this.appSettingsService.appSettings$
|
||||
.pipe(
|
||||
filter(settings => !!settings),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(settings => {
|
||||
this.diskType = settings?.diskType ?? 'LOCAL';
|
||||
});
|
||||
|
||||
if (this.overlayPreferenceService) {
|
||||
this.overlayPrefSub = this.overlayPreferenceService.showBookTypePill$.subscribe(val => {
|
||||
this.showBookTypePill = val;
|
||||
@@ -152,6 +166,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
|
||||
this._seriesCountTooltip = 'Series collapsed: ' + this.book.seriesCount + ' books';
|
||||
this._titleTooltip = 'Title: ' + this._displayTitle;
|
||||
this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK';
|
||||
}
|
||||
|
||||
get hasProgress(): boolean {
|
||||
@@ -446,7 +461,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
const items: MenuItem[] = [];
|
||||
const moreActions: MenuItem[] = [];
|
||||
|
||||
if (this.user?.permissions.canMoveOrganizeFiles) {
|
||||
if (this.user?.permissions.canMoveOrganizeFiles && this.diskType === 'LOCAL') {
|
||||
moreActions.push({
|
||||
label: 'Organize File',
|
||||
icon: 'pi pi-arrows-h',
|
||||
@@ -713,13 +728,28 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private getFileExtension(filePath?: string): string | null {
|
||||
getFileExtension(filePath?: string): string | null {
|
||||
if (!filePath) return null;
|
||||
const parts = filePath.split('.');
|
||||
if (parts.length < 2) return null;
|
||||
return parts.pop()?.toUpperCase() || null;
|
||||
}
|
||||
|
||||
getDisplayFormat(): string | null {
|
||||
if (!this.book?.primaryFile) {
|
||||
return 'PHYSICAL';
|
||||
}
|
||||
const ext = this.book?.primaryFile?.extension;
|
||||
if (ext) {
|
||||
return ext.toUpperCase();
|
||||
}
|
||||
return this.getFileExtension(this.book?.primaryFile?.filePath);
|
||||
}
|
||||
|
||||
hasDigitalFile(): boolean {
|
||||
return !!this.book?.primaryFile;
|
||||
}
|
||||
|
||||
private getFileIcon(fileType: string | null): string {
|
||||
if (!fileType) return 'pi pi-file';
|
||||
switch (fileType.toLowerCase()) {
|
||||
@@ -734,6 +764,11 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
|
||||
case 'cbr':
|
||||
case 'cbx':
|
||||
return 'pi pi-image';
|
||||
case 'audiobook':
|
||||
case 'm4b':
|
||||
case 'm4a':
|
||||
case 'mp3':
|
||||
return 'pi pi-headphones';
|
||||
default:
|
||||
return 'pi pi-file';
|
||||
}
|
||||
|
||||
+32
@@ -15,6 +15,8 @@ import {BookMetadataCenterComponent} from '../../../metadata/component/book-meta
|
||||
import {CoverSearchComponent} from '../../../metadata/component/cover-search/cover-search.component';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {AdditionalFileUploaderComponent} from '../additional-file-uploader/additional-file-uploader.component';
|
||||
import {BookFileAttacherComponent} from '../book-file-attacher/book-file-attacher.component';
|
||||
import {AddPhysicalBookDialogComponent} from '../add-physical-book-dialog/add-physical-book-dialog.component';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookDialogHelperService {
|
||||
@@ -152,4 +154,34 @@ export class BookDialogHelperService {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openBookFileAttacherDialog(sourceBook: Book): DynamicDialogRef | null {
|
||||
return this.openDialog(BookFileAttacherComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
sourceBook: sourceBook,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openBulkBookFileAttacherDialog(sourceBooks: Book[]): DynamicDialogRef | null {
|
||||
return this.openDialog(BookFileAttacherComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
sourceBooks: sourceBooks,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openAddPhysicalBookDialog(libraryId?: number): DynamicDialogRef | null {
|
||||
return this.openDialog(AddPhysicalBookDialogComponent, {
|
||||
showHeader: false,
|
||||
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
|
||||
data: {
|
||||
libraryId: libraryId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -48,7 +48,7 @@
|
||||
</cdk-virtual-scroll-viewport>
|
||||
@if (truncatedFilters[filterType]) {
|
||||
<div class="truncation-notice">
|
||||
Showing first 500 items
|
||||
Showing first 100 items
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@
|
||||
</p-accordion>
|
||||
|
||||
<div class="footer-notice">
|
||||
Note: Top 500 items are displayed per filter category
|
||||
Note: Top 100 items are displayed per filter category
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+5
-5
@@ -142,7 +142,7 @@ function getMatchScoreRangeFilters(score?: number | null): { id: string; name: s
|
||||
}
|
||||
|
||||
function getBookTypeFilter(book: Book): { id: string; name: string }[] {
|
||||
return book.bookType ? [{id: book.bookType, name: book.bookType}] : [];
|
||||
return book.primaryFile?.bookType ? [{id: book.primaryFile.bookType, name: book.primaryFile.bookType}] : [];
|
||||
}
|
||||
|
||||
export const readStatusLabels: Record<ReadStatus, string> = {
|
||||
@@ -230,14 +230,14 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
||||
userService = inject(UserService);
|
||||
bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
userData$: Observable<UserState> = this.userService.userState$;
|
||||
filterSortingMode: FilterSortingMode = 'alphabetical';
|
||||
filterSortingMode: FilterSortingMode = 'count';
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userData$.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(userState => {
|
||||
this.filterSortingMode = userState.user!.userSettings.filterSortingMode ?? 'alphabetical';
|
||||
this.filterSortingMode = userState.user!.userSettings.filterSortingMode ?? 'count';
|
||||
});
|
||||
|
||||
combineLatest([
|
||||
@@ -344,8 +344,8 @@ export class BookFilterComponent implements OnInit, OnDestroy {
|
||||
return aKey.localeCompare(bKey);
|
||||
});
|
||||
|
||||
const isTruncated = sorted.length > 500;
|
||||
const truncated = sorted.slice(0, 500);
|
||||
const isTruncated = sorted.length > 100;
|
||||
const truncated = sorted.slice(0, 100);
|
||||
|
||||
return {items: truncated, isTruncated};
|
||||
}),
|
||||
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {CoverScalePreferenceService} from './cover-scale-preference.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
|
||||
import {take} from 'rxjs/operators';
|
||||
|
||||
describe('CoverScalePreferenceService', () => {
|
||||
let messageServiceMock: any;
|
||||
let localStorageServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
messageServiceMock = {add: vi.fn()};
|
||||
localStorageServiceMock = {
|
||||
set: vi.fn(),
|
||||
get: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CoverScalePreferenceService,
|
||||
{provide: MessageService, useValue: messageServiceMock},
|
||||
{provide: LocalStorageService, useValue: localStorageServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should initialize with default scale if nothing in storage', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
expect(service.scaleFactor).toBe(1.0);
|
||||
});
|
||||
|
||||
it('should initialize with saved scale from storage', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(1.5);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
expect(service.scaleFactor).toBe(1.5);
|
||||
});
|
||||
|
||||
it('should ignore NaN value from storage', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(NaN);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
expect(service.scaleFactor).toBe(1.0);
|
||||
});
|
||||
|
||||
it('initScaleValue sets scaleFactor', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
service.initScaleValue(2.2);
|
||||
expect(service.scaleFactor).toBe(2.2);
|
||||
service.initScaleValue(undefined);
|
||||
expect(service.scaleFactor).toBe(1.0);
|
||||
});
|
||||
|
||||
it('setScale updates scaleFactor and emits on scaleChange$', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
const spy = vi.fn();
|
||||
service.scaleChange$.pipe(take(1)).subscribe(spy);
|
||||
service.setScale(1.8);
|
||||
expect(service.scaleFactor).toBe(1.8);
|
||||
expect(spy).toHaveBeenCalledWith(1.8);
|
||||
});
|
||||
|
||||
it('currentCardSize returns correct dimensions', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
service.scaleFactor = 2;
|
||||
expect(service.currentCardSize).toEqual({width: 270, height: 440});
|
||||
service.scaleFactor = 0.5;
|
||||
expect(service.currentCardSize).toEqual({width: 68, height: 110});
|
||||
});
|
||||
|
||||
it('gridColumnMinWidth returns correct string', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
service.scaleFactor = 1.23;
|
||||
expect(service.gridColumnMinWidth).toBe(`${Math.round(135 * 1.23)}px`);
|
||||
});
|
||||
|
||||
it('saveScalePreference saves to localStorage and shows success message', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
service['saveScalePreference'](1.25);
|
||||
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.25);
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'Cover Size Saved',
|
||||
detail: expect.stringContaining('1.25')
|
||||
}));
|
||||
});
|
||||
|
||||
it('saveScalePreference handles errors and shows error message', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
localStorageServiceMock.set.mockImplementation(() => {
|
||||
throw new Error('fail');
|
||||
});
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
service['saveScalePreference'](1.1);
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 'Save Failed'
|
||||
}));
|
||||
});
|
||||
|
||||
it('setScale triggers debounced saveScalePreference', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
service.setScale(1.7);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.7);
|
||||
});
|
||||
|
||||
it('debounced save only triggers once for rapid setScale calls', () => {
|
||||
localStorageServiceMock.get.mockReturnValue(null);
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
|
||||
service.setScale(1.1);
|
||||
service.setScale(1.2);
|
||||
service.setScale(1.3);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(localStorageServiceMock.set).toHaveBeenCalledTimes(1);
|
||||
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.3);
|
||||
});
|
||||
});
|
||||
-167
@@ -1,167 +0,0 @@
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {Subject} from 'rxjs';
|
||||
import {HeaderFilter} from './HeaderFilter';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
|
||||
const makeBook = (overrides: any = {}) => ({
|
||||
id: 1,
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'Test Title',
|
||||
authors: ['John Doe'],
|
||||
seriesName: 'Test Series',
|
||||
categories: ['Fiction'],
|
||||
isbn10: '1234567890',
|
||||
isbn13: '9781234567897',
|
||||
...overrides.metadata
|
||||
},
|
||||
...overrides
|
||||
});
|
||||
|
||||
const baseState: BookState = {
|
||||
books: [
|
||||
makeBook(),
|
||||
makeBook({id: 2, metadata: {bookId: 2, title: 'Another Book', authors: ['Jane Smith'], seriesName: 'Another Series', categories: ['Nonfiction'], isbn10: '0987654321', isbn13: '9780987654321'}}),
|
||||
makeBook({id: 3, metadata: {bookId: 3, title: 'Éxample Łatin', authors: ['Åuthor Æther'], seriesName: 'Série', categories: ['Categøry'], isbn10: 'ø123', isbn13: 'æ456'}}),
|
||||
makeBook({id: 4, metadata: {bookId: 4, title: 'Special!@#$', authors: ['O\'Connor'], seriesName: '', categories: [], isbn10: '', isbn13: ''}})
|
||||
],
|
||||
loaded: true,
|
||||
error: null
|
||||
};
|
||||
|
||||
describe('HeaderFilter', () => {
|
||||
let search$: Subject<string>;
|
||||
let filter: HeaderFilter;
|
||||
|
||||
beforeEach(() => {
|
||||
search$ = new Subject<string>();
|
||||
filter = new HeaderFilter(search$.asObservable());
|
||||
});
|
||||
|
||||
it('returns original state if search term is less than 2 chars', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result).toBe(baseState);
|
||||
});
|
||||
search$.next('a');
|
||||
});
|
||||
|
||||
it('filters by title (case-insensitive, normalized)', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(1);
|
||||
expect(result.books?.[0]?.metadata?.title).toBe('Test Title');
|
||||
});
|
||||
search$.next('test');
|
||||
});
|
||||
|
||||
it('filters by author', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(1);
|
||||
expect(result.books?.[0]?.metadata?.authors?.[0]).toBe('Jane Smith');
|
||||
});
|
||||
search$.next('smith');
|
||||
});
|
||||
|
||||
const expectBooksWithTitles = (searchTerm: string, expectedCount: number, expectedTitles: string[]) => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(expectedCount);
|
||||
const titles = result.books?.map(b => b.metadata?.title);
|
||||
expectedTitles.forEach(title => expect(titles).toContain(title));
|
||||
});
|
||||
search$.next(searchTerm);
|
||||
};
|
||||
|
||||
it('filters by series', () => {
|
||||
expectBooksWithTitles('series', 2, ['Test Title', 'Another Book']);
|
||||
});
|
||||
|
||||
it('filters by category', () => {
|
||||
expectBooksWithTitles('fiction', 2, ['Test Title', 'Another Book']);
|
||||
});
|
||||
|
||||
it('filters by isbn10', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(1);
|
||||
expect(result.books?.[0]?.metadata?.isbn10).toBe('1234567890');
|
||||
});
|
||||
search$.next('1234567890');
|
||||
});
|
||||
|
||||
it('filters by isbn13', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(1);
|
||||
expect(result.books?.[0]?.metadata?.isbn13).toBe('9780987654321');
|
||||
});
|
||||
search$.next('9780987654321');
|
||||
});
|
||||
|
||||
it('normalizes diacritics and special chars', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(1);
|
||||
expect(result.books?.[0]?.metadata?.title).toBe('Éxample Łatin');
|
||||
});
|
||||
search$.next('example latin');
|
||||
});
|
||||
|
||||
it('normalizes special Unicode chars in categories (ø -> o)', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(1);
|
||||
expect(result.books?.[0]?.metadata?.categories?.[0]).toBe('Categøry');
|
||||
});
|
||||
search$.next('category');
|
||||
});
|
||||
|
||||
it('removes punctuation and matches', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books?.length).toBe(1);
|
||||
expect(result.books?.[0]?.metadata?.title).toBe('Special!@#$');
|
||||
});
|
||||
search$.next('special');
|
||||
});
|
||||
|
||||
it('returns empty books if no match', () => {
|
||||
filter.filter(baseState).subscribe(result => {
|
||||
expect(result.books).toEqual([]);
|
||||
});
|
||||
search$.next('notfound');
|
||||
});
|
||||
|
||||
it('handles undefined fields gracefully', () => {
|
||||
const state: BookState = {
|
||||
books: [
|
||||
{
|
||||
id: 5,
|
||||
bookType: 'EPUB',
|
||||
libraryId: 1,
|
||||
libraryName: 'Test Library',
|
||||
metadata: {
|
||||
bookId: 5,
|
||||
title: undefined,
|
||||
authors: undefined,
|
||||
seriesName: undefined,
|
||||
categories: undefined,
|
||||
isbn10: undefined,
|
||||
isbn13: undefined
|
||||
}
|
||||
}
|
||||
],
|
||||
loaded: true,
|
||||
error: null
|
||||
};
|
||||
filter.filter(state).subscribe(result => {
|
||||
expect(result.books).toEqual([]);
|
||||
});
|
||||
search$.next('anything');
|
||||
});
|
||||
|
||||
it('distinctUntilChanged prevents duplicate emissions for same search term', async () => {
|
||||
const emissions: any[] = [];
|
||||
const subscription = filter.filter(baseState).subscribe(result => {
|
||||
emissions.push(result);
|
||||
});
|
||||
search$.next('test');
|
||||
search$.next('test');
|
||||
await new Promise(resolve => setTimeout(resolve, 600));
|
||||
expect(emissions.length).toBe(1);
|
||||
subscription.unsubscribe();
|
||||
});
|
||||
});
|
||||
-244
@@ -1,244 +0,0 @@
|
||||
import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {BehaviorSubject, firstValueFrom, of, Subject} from 'rxjs';
|
||||
import {SeriesCollapseFilter} from './SeriesCollapseFilter';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {Book} from '../../../model/book.model';
|
||||
|
||||
describe('SeriesCollapseFilter', () => {
|
||||
let userServiceMock: any;
|
||||
let messageServiceMock: any;
|
||||
let userStateSubject: BehaviorSubject<any>;
|
||||
let currentUser: any;
|
||||
|
||||
beforeEach(() => {
|
||||
userStateSubject = new BehaviorSubject({
|
||||
user: null,
|
||||
loaded: false,
|
||||
error: null
|
||||
});
|
||||
|
||||
currentUser = {
|
||||
id: 1,
|
||||
userSettings: {
|
||||
entityViewPreferences: {
|
||||
global: {seriesCollapsed: false},
|
||||
overrides: []
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
userServiceMock = {
|
||||
userState$: userStateSubject.asObservable(),
|
||||
getCurrentUser: vi.fn(() => currentUser),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
|
||||
messageServiceMock = {add: vi.fn()};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SeriesCollapseFilter,
|
||||
{provide: UserService, useValue: userServiceMock},
|
||||
{provide: MessageService, useValue: messageServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function createService(): SeriesCollapseFilter {
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
return runInInjectionContext(injector, () => TestBed.inject(SeriesCollapseFilter));
|
||||
}
|
||||
|
||||
it('should initialize with default collapsed=false', () => {
|
||||
const service = createService();
|
||||
expect(service.isSeriesCollapsed).toBe(false);
|
||||
});
|
||||
|
||||
it('should apply global preference on userState$ emit', () => {
|
||||
currentUser.userSettings.entityViewPreferences.global.seriesCollapsed = true;
|
||||
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||
const service = createService();
|
||||
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||
expect(service.isSeriesCollapsed).toBe(true);
|
||||
});
|
||||
|
||||
it('should apply override preference for context', () => {
|
||||
currentUser.userSettings.entityViewPreferences.overrides = [
|
||||
{entityType: 'LIBRARY', entityId: 42, preferences: {seriesCollapsed: true}}
|
||||
];
|
||||
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||
const service = createService();
|
||||
service.setContext('LIBRARY', 42);
|
||||
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||
expect(service.isSeriesCollapsed).toBe(true);
|
||||
});
|
||||
|
||||
it('should fallback to old seriesCollapse field for global', () => {
|
||||
currentUser.userSettings.entityViewPreferences.global = {seriesCollapse: true};
|
||||
delete currentUser.userSettings.entityViewPreferences.global.seriesCollapsed;
|
||||
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||
const service = createService();
|
||||
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||
expect(service.isSeriesCollapsed).toBe(true);
|
||||
});
|
||||
|
||||
it('should fallback to old seriesCollapse field for override', () => {
|
||||
currentUser.userSettings.entityViewPreferences.overrides = [
|
||||
{entityType: 'SHELF', entityId: 99, preferences: {seriesCollapse: true}}
|
||||
];
|
||||
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
|
||||
const service = createService();
|
||||
service.setContext('SHELF', 99);
|
||||
userStateSubject.next({user: currentUser, loaded: true, error: null});
|
||||
expect(service.isSeriesCollapsed).toBe(true);
|
||||
});
|
||||
|
||||
it('setCollapsed should update value and trigger persistence after debounce', () => {
|
||||
const service = createService();
|
||||
service.setCollapsed(true);
|
||||
expect(service.isSeriesCollapsed).toBe(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(userServiceMock.updateUserSetting).toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'Preference Saved',
|
||||
detail: expect.stringContaining('enabled')
|
||||
}));
|
||||
});
|
||||
|
||||
it('setCollapsed should persist override if context set', () => {
|
||||
const service = createService();
|
||||
service.setContext('MAGIC_SHELF', 123);
|
||||
service.setCollapsed(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||
1,
|
||||
'entityViewPreferences',
|
||||
expect.objectContaining({
|
||||
overrides: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
entityType: 'MAGIC_SHELF',
|
||||
entityId: 123,
|
||||
preferences: expect.objectContaining({seriesCollapsed: true})
|
||||
})
|
||||
])
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('setCollapsed should persist global if no context', () => {
|
||||
const service = createService();
|
||||
service.setCollapsed(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
|
||||
1,
|
||||
'entityViewPreferences',
|
||||
expect.objectContaining({
|
||||
global: expect.objectContaining({seriesCollapsed: true})
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should not persist if no user', () => {
|
||||
userServiceMock.getCurrentUser.mockReturnValue(null);
|
||||
const service = createService();
|
||||
service.setCollapsed(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should filter books and collapse series', async () => {
|
||||
const service = createService();
|
||||
service.setCollapsed(true);
|
||||
|
||||
const books: Book[] = [
|
||||
{id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any,
|
||||
{id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any,
|
||||
{id: 3, metadata: {seriesName: 'B', seriesNumber: 1}, title: 'B3'} as any,
|
||||
{id: 4, metadata: {}, title: 'B4'} as any
|
||||
];
|
||||
const state: BookState = {books, loaded: true, error: null};
|
||||
|
||||
const result = await firstValueFrom(service.filter(state));
|
||||
expect(result && result.books).toBeTruthy();
|
||||
if (!result || !result.books) throw new Error('No books in result');
|
||||
expect(result.books.length).toBe(3);
|
||||
// Series A collapsed to one book with seriesBooks of length 2
|
||||
const a = result.books.find(b => b.metadata?.seriesName === 'A');
|
||||
expect(a).toBeDefined();
|
||||
expect(a?.seriesBooks?.length).toBe(2);
|
||||
expect(a?.seriesCount).toBe(2);
|
||||
// Series B collapsed to one book with seriesBooks of length 1
|
||||
const b = result.books.find(b => b.metadata?.seriesName === 'B');
|
||||
expect(b).toBeDefined();
|
||||
expect(b?.seriesBooks?.length).toBe(1);
|
||||
expect(b?.seriesCount).toBe(1);
|
||||
// Non-series book remains
|
||||
expect(result.books.some(b => b['title'] === 'B4')).toBe(true);
|
||||
});
|
||||
|
||||
it('should not collapse series if forceExpandSeries=true', async () => {
|
||||
const service = createService();
|
||||
service.setCollapsed(true);
|
||||
|
||||
const books: Book[] = [
|
||||
{id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any,
|
||||
{id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any
|
||||
];
|
||||
const state: BookState = {books, loaded: true, error: null};
|
||||
|
||||
const result = await firstValueFrom(service.filter(state, true));
|
||||
expect(result && result.books).toBeTruthy();
|
||||
if (!result || !result.books) throw new Error('No books in result');
|
||||
expect(result.books.length).toBe(2);
|
||||
});
|
||||
|
||||
it('should return original state if books is null', async () => {
|
||||
const service = createService();
|
||||
service.setCollapsed(true);
|
||||
const state: BookState = {books: null, loaded: true, error: null};
|
||||
const result = await firstValueFrom(service.filter(state));
|
||||
expect(result).toBe(state);
|
||||
});
|
||||
|
||||
it('should not collapse if isSeriesCollapsed is false', async () => {
|
||||
const service = createService();
|
||||
service.setCollapsed(false);
|
||||
const books: Book[] = [
|
||||
{id: 1, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B1'} as any
|
||||
];
|
||||
const state: BookState = {books, loaded: true, error: null};
|
||||
const result = await firstValueFrom(service.filter(state));
|
||||
expect(result && result.books).toBeTruthy();
|
||||
if (!result || !result.books) throw new Error('No books in result');
|
||||
expect(result.books.length).toBe(1);
|
||||
expect(result.books[0]?.seriesBooks).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should clean up destroy$ on ngOnDestroy', () => {
|
||||
const service = createService();
|
||||
const spy = vi.spyOn(service['destroy$'], 'next');
|
||||
service.ngOnDestroy();
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('setContext(null, null) resets context and applies preference', () => {
|
||||
const service = createService();
|
||||
const applyPrefSpy = vi.spyOn(service as any, 'applyPreference');
|
||||
service.setContext(null, null);
|
||||
expect((service as any).currentContext).toBeNull();
|
||||
expect(applyPrefSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
-629
@@ -1,629 +0,0 @@
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {BehaviorSubject, firstValueFrom} from 'rxjs';
|
||||
import {doesBookMatchReadStatus, isFileSizeInRange, isMatchScoreInRange, isPageCountInRange, isRatingInRange, isRatingInRange10, SideBarFilter} from './SidebarFilter';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {Book, ReadStatus} from '../../../model/book.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
|
||||
describe('SidebarFilter helpers', () => {
|
||||
it('isRatingInRange returns true for value in range', () => {
|
||||
expect(isRatingInRange(3.0, '3to4')).toBe(true);
|
||||
expect(isRatingInRange(3.99, '3to4')).toBe(true);
|
||||
expect(isRatingInRange(4.0, '3to4')).toBe(false);
|
||||
});
|
||||
it('isRatingInRange returns false for value out of range', () => {
|
||||
expect(isRatingInRange(4.5, '3to4')).toBe(false);
|
||||
expect(isRatingInRange(2.9, '3to4')).toBe(false);
|
||||
});
|
||||
it('isRatingInRange10 matches rounded rating', () => {
|
||||
expect(isRatingInRange10(7.2, '7')).toBe(true);
|
||||
expect(isRatingInRange10(7.7, '8')).toBe(true);
|
||||
expect(isRatingInRange10(7.2, '8')).toBe(false);
|
||||
});
|
||||
it('isFileSizeInRange returns true for value in range', () => {
|
||||
expect(isFileSizeInRange(0, '<1mb')).toBe(true);
|
||||
expect(isFileSizeInRange(1023, '<1mb')).toBe(true);
|
||||
expect(isFileSizeInRange(1024, '<1mb')).toBe(false);
|
||||
});
|
||||
it('isFileSizeInRange returns false for value out of range', () => {
|
||||
expect(isFileSizeInRange(2000, '<1mb')).toBe(false);
|
||||
expect(isFileSizeInRange(-1, '<1mb')).toBe(false);
|
||||
});
|
||||
it('isPageCountInRange returns true for value in range', () => {
|
||||
expect(isPageCountInRange(100, '100to200')).toBe(true);
|
||||
expect(isPageCountInRange(199, '100to200')).toBe(true);
|
||||
expect(isPageCountInRange(200, '100to200')).toBe(false);
|
||||
});
|
||||
it('isPageCountInRange returns false for value out of range', () => {
|
||||
expect(isPageCountInRange(50, '100to200')).toBe(false);
|
||||
expect(isPageCountInRange(200, '100to200')).toBe(false);
|
||||
});
|
||||
it('isMatchScoreInRange returns true for value in range', () => {
|
||||
expect(isMatchScoreInRange(0.80, '0.80-0.89')).toBe(true);
|
||||
expect(isMatchScoreInRange(0.89, '0.80-0.89')).toBe(true);
|
||||
expect(isMatchScoreInRange(0.90, '0.80-0.89')).toBe(false);
|
||||
expect(isMatchScoreInRange(85, '0.80-0.89')).toBe(true);
|
||||
});
|
||||
it('isMatchScoreInRange returns false for value out of range', () => {
|
||||
expect(isMatchScoreInRange(0.5, '0.80-0.89')).toBe(false);
|
||||
expect(isMatchScoreInRange(0.95, '0.80-0.89')).toBe(false);
|
||||
});
|
||||
it('doesBookMatchReadStatus returns true if status matches', () => {
|
||||
const book = {readStatus: ReadStatus.READ} as Book;
|
||||
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(true);
|
||||
});
|
||||
it('doesBookMatchReadStatus returns false if status does not match', () => {
|
||||
const book = {readStatus: ReadStatus.UNREAD} as Book;
|
||||
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false);
|
||||
});
|
||||
it('doesBookMatchReadStatus returns true for unset if included', () => {
|
||||
const book = {} as Book;
|
||||
expect(doesBookMatchReadStatus(book, [ReadStatus.UNSET])).toBe(true);
|
||||
});
|
||||
it('isRatingInRange returns false for unknown rangeId', () => {
|
||||
expect(isRatingInRange(3.5, 'not-a-range')).toBe(false);
|
||||
});
|
||||
it('isRatingInRange returns false for null/undefined rating', () => {
|
||||
expect(isRatingInRange(undefined, '3to4')).toBe(false);
|
||||
expect(isRatingInRange(null, '3to4')).toBe(false);
|
||||
});
|
||||
it('isRatingInRange10 returns false for null/undefined rating', () => {
|
||||
expect(isRatingInRange10(undefined, '7')).toBe(false);
|
||||
expect(isRatingInRange10(null, '7')).toBe(false);
|
||||
});
|
||||
it('isFileSizeInRange returns false for unknown rangeId', () => {
|
||||
expect(isFileSizeInRange(500, 'not-a-range')).toBe(false);
|
||||
});
|
||||
it('isFileSizeInRange returns false for null/undefined fileSize', () => {
|
||||
expect(isFileSizeInRange(undefined, '<1mb')).toBe(false);
|
||||
});
|
||||
it('isPageCountInRange returns false for unknown rangeId', () => {
|
||||
expect(isPageCountInRange(150, 'not-a-range')).toBe(false);
|
||||
});
|
||||
it('isPageCountInRange returns false for null/undefined pageCount', () => {
|
||||
expect(isPageCountInRange(undefined, '100to200')).toBe(false);
|
||||
});
|
||||
it('isMatchScoreInRange returns false for unknown rangeId', () => {
|
||||
expect(isMatchScoreInRange(0.85, 'not-a-range')).toBe(false);
|
||||
});
|
||||
it('isMatchScoreInRange returns false for null/undefined score', () => {
|
||||
expect(isMatchScoreInRange(undefined, '0.80-0.89')).toBe(false);
|
||||
expect(isMatchScoreInRange(null, '0.80-0.89')).toBe(false);
|
||||
});
|
||||
it('doesBookMatchReadStatus returns false if selected is empty', () => {
|
||||
const book = {readStatus: ReadStatus.READ} as Book;
|
||||
expect(doesBookMatchReadStatus(book, [])).toBe(false);
|
||||
});
|
||||
it('doesBookMatchReadStatus returns false if status is not in selected', () => {
|
||||
const book = {readStatus: ReadStatus.READING} as Book;
|
||||
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SideBarFilter', () => {
|
||||
let books: Book[];
|
||||
let bookState: BookState;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create fresh book objects for each test to prevent mutation pollution
|
||||
books = [
|
||||
{
|
||||
id: 1,
|
||||
libraryId: 1,
|
||||
libraryName: 'Lib1',
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
authors: ['A1'],
|
||||
categories: ['C1'],
|
||||
moods: ['M1'],
|
||||
tags: ['T1'],
|
||||
publisher: 'P1',
|
||||
seriesName: 'S1',
|
||||
amazonRating: 4.2,
|
||||
goodreadsRating: 3.8,
|
||||
hardcoverRating: 4.0,
|
||||
ranobedbRating: 3.5,
|
||||
publishedDate: '2020-01-01',
|
||||
pageCount: 150,
|
||||
language: 'en'
|
||||
},
|
||||
personalRating: 7,
|
||||
fileSizeKb: 500,
|
||||
shelves: [{name: 'shelf1', icon: 'icon1'}] as Shelf[],
|
||||
metadataMatchScore: 0.8,
|
||||
bookType: 'EPUB',
|
||||
readStatus: ReadStatus.READ
|
||||
} as Book,
|
||||
{
|
||||
id: 2,
|
||||
libraryId: 1,
|
||||
libraryName: 'Lib1',
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
authors: ['A2'],
|
||||
categories: ['C2'],
|
||||
moods: ['M2'],
|
||||
tags: ['T2'],
|
||||
publisher: 'P2',
|
||||
seriesName: 'S2',
|
||||
amazonRating: 2.5,
|
||||
goodreadsRating: 2.8,
|
||||
hardcoverRating: 2.0,
|
||||
ranobedbRating: 2.4,
|
||||
publishedDate: '2019-01-01',
|
||||
pageCount: 50,
|
||||
language: 'fr'
|
||||
},
|
||||
personalRating: 3,
|
||||
fileSizeKb: 2000,
|
||||
shelves: [] as Shelf[],
|
||||
metadataMatchScore: 0.5,
|
||||
bookType: 'PDF',
|
||||
readStatus: ReadStatus.UNREAD
|
||||
} as Book
|
||||
];
|
||||
bookState = {books, loaded: true, error: null};
|
||||
});
|
||||
|
||||
function filterWith(activeFilters: any, mode: 'and' | 'or' = 'and') {
|
||||
const filter$ = new BehaviorSubject(activeFilters);
|
||||
const mode$ = new BehaviorSubject(mode);
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
return filter.filter(bookState);
|
||||
}
|
||||
|
||||
it('filters by author (and mode)', async () => {
|
||||
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.authors).toContain('A1');
|
||||
});
|
||||
|
||||
it('filters by author (or mode)', async () => {
|
||||
const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('filters by category', async () => {
|
||||
const result = await firstValueFrom(filterWith({category: ['C2']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.categories).toContain('C2');
|
||||
});
|
||||
|
||||
it('filters by mood', async () => {
|
||||
const result = await firstValueFrom(filterWith({mood: ['M1']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.moods).toContain('M1');
|
||||
});
|
||||
|
||||
it('filters by tag', async () => {
|
||||
const result = await firstValueFrom(filterWith({tag: ['T2']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.tags).toContain('T2');
|
||||
});
|
||||
|
||||
it('filters by publisher', async () => {
|
||||
const result = await firstValueFrom(filterWith({publisher: ['P1']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.publisher).toBe('P1');
|
||||
});
|
||||
|
||||
it('filters by series', async () => {
|
||||
const result = await firstValueFrom(filterWith({series: ['S2']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.seriesName).toBe('S2');
|
||||
});
|
||||
|
||||
it('filters by readStatus', async () => {
|
||||
const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ]}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.readStatus).toBe(ReadStatus.READ);
|
||||
});
|
||||
|
||||
it('filters by amazonRating', async () => {
|
||||
const result = await firstValueFrom(filterWith({amazonRating: ['4to4.5']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.amazonRating).toBeGreaterThanOrEqual(4);
|
||||
});
|
||||
|
||||
it('filters by goodreadsRating', async () => {
|
||||
const result = await firstValueFrom(filterWith({goodreadsRating: ['3to4']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.goodreadsRating).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('filters by hardcoverRating', async () => {
|
||||
const result = await firstValueFrom(filterWith({hardcoverRating: ['2to3']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.hardcoverRating).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('filters by ranobedbRating', async () => {
|
||||
const result = await firstValueFrom(filterWith({ranobedbRating: ['3to4']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.ranobedbRating).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('filters by personalRating', async () => {
|
||||
const result = await firstValueFrom(filterWith({personalRating: ['7']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.personalRating).toBe(7);
|
||||
});
|
||||
|
||||
it('filters by shelfStatus unshelved', async () => {
|
||||
const result = await firstValueFrom(filterWith({shelfStatus: ['unshelved']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.shelves?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('filters by fileSize', async () => {
|
||||
const result = await firstValueFrom(filterWith({fileSize: ['<1mb']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.fileSizeKb).toBeLessThan(1024);
|
||||
});
|
||||
|
||||
it('filters by language', async () => {
|
||||
const result = await firstValueFrom(filterWith({language: ['fr']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.language).toBe('fr');
|
||||
});
|
||||
|
||||
it('filters by pageCount', async () => {
|
||||
const result = await firstValueFrom(filterWith({pageCount: ['100to200']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadata?.pageCount).toBeGreaterThanOrEqual(100);
|
||||
});
|
||||
|
||||
it('filters by matchScore', async () => {
|
||||
const result = await firstValueFrom(filterWith({matchScore: ['0.80-0.89']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.metadataMatchScore).toBeGreaterThanOrEqual(0.8);
|
||||
});
|
||||
|
||||
it('filters by bookType', async () => {
|
||||
const result = await firstValueFrom(filterWith({bookType: ['PDF']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.bookType).toBe('PDF');
|
||||
});
|
||||
|
||||
it('returns all books if no filters', async () => {
|
||||
const result = await firstValueFrom(filterWith({}, 'and'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('returns all books if filters is null', async () => {
|
||||
const filter$ = new BehaviorSubject(null);
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(bookState));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('returns original state if books is null', async () => {
|
||||
bookState.books = null as any;
|
||||
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||
expect(result).toBe(bookState);
|
||||
expect(result.books).toBeNull();
|
||||
});
|
||||
|
||||
it('returns original state if books is undefined', async () => {
|
||||
bookState.books = undefined as any;
|
||||
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||
expect(result).toBe(bookState);
|
||||
expect(result.books).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns empty books array for empty bookState', async () => {
|
||||
bookState.books = [];
|
||||
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('filters by multiple authors in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('filters by multiple categories in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({category: ['C1', 'C2']}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('filters by multiple moods in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({mood: ['M1', 'M2']}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('filters by multiple tags in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({tag: ['T1', 'T2']}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('filters by multiple publishers in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('filters by multiple series in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('returns true for empty filter values in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({author: []}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('returns false for empty filter values in AND mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({author: []}, 'and'));
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('filters with multiple filter types in AND mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({
|
||||
author: ['A1'],
|
||||
category: ['C1'],
|
||||
readStatus: [ReadStatus.READ]
|
||||
}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('filters with multiple filter types in OR mode', async () => {
|
||||
const result = await firstValueFrom(filterWith({
|
||||
author: ['A1'],
|
||||
category: ['C2']
|
||||
}, 'or'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('returns false for unknown filter type', async () => {
|
||||
const result = await firstValueFrom(filterWith({unknownFilter: ['value']}, 'and'));
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('filters by shelfStatus shelved', async () => {
|
||||
const result = await firstValueFrom(filterWith({shelfStatus: ['shelved']}, 'and'));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
expect(result?.books?.[0]?.shelves?.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('returns false for book without publishedDate', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, publishedDate: undefined}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({publishedDate: [2020]});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('filters by multiple authors in AND mode - all must match', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, authors: ['A1', 'A3']}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({author: ['A1', 'A3']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('filters by multiple categories in AND mode - all must match', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, categories: ['C1', 'C3']}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({category: ['C1', 'C3']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('filters by multiple moods in AND mode - all must match', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, moods: ['M1', 'M3']}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({mood: ['M1', 'M3']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('filters by multiple tags in AND mode - all must match', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, tags: ['T1', 'T3']}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({tag: ['T1', 'T3']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
expect(result?.books?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('filters by multiple publishers in AND mode - returns books matching all', async () => {
|
||||
// Publisher can only have one value, so AND with multiple should return nothing
|
||||
const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'and'));
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('filters by multiple series in AND mode - returns books matching all', async () => {
|
||||
// Series can only have one value, so AND with multiple should return nothing
|
||||
const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'and'));
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null metadata', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: null as any},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with undefined metadata', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: undefined as any},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has undefined metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null authors array', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, authors: null as any}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with undefined authors array', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, authors: undefined as any}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({author: ['A1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has undefined authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null categories array', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, categories: null as any}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({category: ['C1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null categories, so it doesn't match. Book 2 has category 'C2', doesn't match 'C1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null moods array', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, moods: null as any}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({mood: ['M1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null moods, so it doesn't match. Book 2 has mood 'M2', doesn't match 'M1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null tags array', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, tags: null as any}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({tag: ['T1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null tags, so it doesn't match. Book 2 has tag 'T2', doesn't match 'T1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null publisher', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, publisher: null as any}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({publisher: ['P1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null publisher, so it doesn't match. Book 2 has publisher 'P2', doesn't match 'P1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null series', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], metadata: {...books[0].metadata!, seriesName: null as any}},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({series: ['S1']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null series, so it doesn't match. Book 2 has series 'S2', doesn't match 'S1'
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
|
||||
it('handles book with null shelves', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], shelves: null as any},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has null shelves (unshelved), book 2 has empty shelves array (also unshelved)
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('handles book with undefined shelves', async () => {
|
||||
const testBooks: Book[] = [
|
||||
{...books[0], shelves: undefined as any},
|
||||
{...books[1]}
|
||||
];
|
||||
const testState = {...bookState, books: testBooks};
|
||||
const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']});
|
||||
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
|
||||
const filter = new SideBarFilter(filter$, mode$);
|
||||
const result = await firstValueFrom(filter.filter(testState));
|
||||
// Book 1 has undefined shelves (unshelved), book 2 has empty shelves array (also unshelved)
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('filters by multiple readStatus values', async () => {
|
||||
const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ, ReadStatus.UNREAD]}, 'and'));
|
||||
expect(result?.books?.length).toBe(2);
|
||||
});
|
||||
|
||||
it('handles non-array filter values', async () => {
|
||||
const result = await firstValueFrom(filterWith({author: 'A1' as any}, 'and'));
|
||||
expect(result?.books?.length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -123,7 +123,7 @@ export class SideBarFilter implements BookFilter {
|
||||
case 'matchScore':
|
||||
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range));
|
||||
case 'bookType':
|
||||
return filterValues.includes(book.bookType);
|
||||
return filterValues.includes(book.primaryFile?.bookType);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
|
||||
import {take} from 'rxjs/operators';
|
||||
|
||||
describe('SidebarFilterTogglePrefService', () => {
|
||||
let messageServiceMock: any;
|
||||
let localStorageServiceMock: any;
|
||||
let originalInnerWidth: number;
|
||||
|
||||
beforeEach(() => {
|
||||
messageServiceMock = {add: vi.fn()};
|
||||
localStorageServiceMock = {
|
||||
set: vi.fn(),
|
||||
get: vi.fn()
|
||||
};
|
||||
originalInnerWidth = window.innerWidth;
|
||||
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 1024});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
SidebarFilterTogglePrefService,
|
||||
{provide: MessageService, useValue: messageServiceMock},
|
||||
{provide: LocalStorageService, useValue: localStorageServiceMock}
|
||||
]
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: originalInnerWidth});
|
||||
});
|
||||
|
||||
function createService(): SidebarFilterTogglePrefService {
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
return runInInjectionContext(injector, () => TestBed.inject(SidebarFilterTogglePrefService));
|
||||
}
|
||||
|
||||
it('should initialize with true if no saved value and not narrow', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||
const service = createService();
|
||||
expect(service.selectedShowFilter).toBe(true);
|
||||
});
|
||||
|
||||
it('should initialize with saved value if present and not narrow', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(false);
|
||||
const service = createService();
|
||||
expect(service.selectedShowFilter).toBe(false);
|
||||
});
|
||||
|
||||
it('should initialize with false if window is narrow', () => {
|
||||
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 600});
|
||||
const service = createService();
|
||||
expect(service.selectedShowFilter).toBe(false);
|
||||
});
|
||||
|
||||
it('should emit value on showFilter$', async () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||
const service = createService();
|
||||
const val = await service.showFilter$.pipe(take(1)).toPromise();
|
||||
expect(val).toBe(true);
|
||||
});
|
||||
|
||||
it('should update selectedShowFilter and persist preference', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||
const service = createService();
|
||||
service.selectedShowFilter = false;
|
||||
expect(service.selectedShowFilter).toBe(false);
|
||||
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false);
|
||||
});
|
||||
|
||||
it('should not persist if value is unchanged', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(true);
|
||||
const service = createService();
|
||||
localStorageServiceMock.set.mockClear();
|
||||
service.selectedShowFilter = true;
|
||||
expect(localStorageServiceMock.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should toggle selectedShowFilter', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(true);
|
||||
const service = createService();
|
||||
service.toggle();
|
||||
expect(service.selectedShowFilter).toBe(false);
|
||||
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false);
|
||||
service.toggle();
|
||||
expect(service.selectedShowFilter).toBe(true);
|
||||
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', true);
|
||||
});
|
||||
|
||||
it('should handle error in savePreference and show error message', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(null);
|
||||
localStorageServiceMock.set.mockImplementation(() => {
|
||||
throw new Error('fail');
|
||||
});
|
||||
const service = createService();
|
||||
service.selectedShowFilter = false;
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'error',
|
||||
summary: 'Save Failed'
|
||||
}));
|
||||
});
|
||||
|
||||
it('should call loadFromStorage and set correct value for wide screen', () => {
|
||||
localStorageServiceMock.get.mockReturnValueOnce(true);
|
||||
const service = createService();
|
||||
expect(service.selectedShowFilter).toBe(true);
|
||||
});
|
||||
|
||||
it('should call loadFromStorage and set correct value for narrow screen', () => {
|
||||
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 500});
|
||||
const service = createService();
|
||||
expect(service.selectedShowFilter).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {BookSorter} from './BookSorter';
|
||||
import {SortDirection, SortOption} from '../../../model/sort.model';
|
||||
|
||||
describe('BookSorter', () => {
|
||||
let applySortOption: (sort: SortOption) => void;
|
||||
let sorter: BookSorter;
|
||||
|
||||
beforeEach(() => {
|
||||
applySortOption = vi.fn();
|
||||
sorter = new BookSorter(applySortOption);
|
||||
});
|
||||
|
||||
it('should initialize with undefined selectedSort', () => {
|
||||
expect(sorter.selectedSort).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should have all default sort options', () => {
|
||||
expect(sorter.sortOptions).toBeInstanceOf(Array);
|
||||
expect(sorter.sortOptions.length).toBeGreaterThan(0);
|
||||
expect(sorter.sortOptions.some(opt => opt.field === 'title')).toBe(true);
|
||||
});
|
||||
|
||||
it('should set selectedSort and call applySortOption on sortBooks (first time)', () => {
|
||||
sorter.sortBooks('author');
|
||||
expect(sorter.selectedSort).toMatchObject({
|
||||
field: 'author',
|
||||
direction: SortDirection.ASCENDING
|
||||
});
|
||||
expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort);
|
||||
});
|
||||
|
||||
it('should toggle direction when sorting the same field again', () => {
|
||||
sorter.sortBooks('title');
|
||||
const firstSort = {...sorter.selectedSort!};
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.selectedSort?.field).toBe('title');
|
||||
expect(sorter.selectedSort?.direction).not.toBe(firstSort.direction);
|
||||
expect(applySortOption).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should reset direction to ASCENDING when sorting a new field', () => {
|
||||
sorter.sortBooks('title');
|
||||
sorter.sortBooks('author');
|
||||
expect(sorter.selectedSort?.field).toBe('author');
|
||||
expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING);
|
||||
});
|
||||
|
||||
it('should not change selectedSort or call applySortOption for unknown field', () => {
|
||||
sorter.sortBooks('notAField');
|
||||
expect(sorter.selectedSort).toBeUndefined();
|
||||
expect(applySortOption).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should update sortOptions with correct icon for selected field and direction', () => {
|
||||
sorter.sortBooks('title');
|
||||
const upIcon = 'pi pi-arrow-up';
|
||||
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(upIcon);
|
||||
expect(sorter.sortOptions.filter(opt => opt.field !== 'title').every(opt => !(opt as any).icon)).toBe(true);
|
||||
|
||||
sorter.sortBooks('title'); // toggle direction
|
||||
const downIcon = 'pi pi-arrow-down';
|
||||
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(downIcon);
|
||||
});
|
||||
|
||||
it('should only set icon for the selected field', () => {
|
||||
sorter.sortBooks('author');
|
||||
sorter.sortBooks('title');
|
||||
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe('pi pi-arrow-up');
|
||||
expect((sorter.sortOptions.find(opt => opt.field === 'author') as any)?.icon).toBe('');
|
||||
});
|
||||
|
||||
it('should preserve label and field when toggling direction', () => {
|
||||
sorter.sortBooks('fileName');
|
||||
const {label, field} = sorter.selectedSort!;
|
||||
sorter.sortBooks('fileName');
|
||||
expect(sorter.selectedSort?.label).toBe(label);
|
||||
expect(sorter.selectedSort?.field).toBe(field);
|
||||
});
|
||||
|
||||
it('should not throw if updateSortOptions is called with no selectedSort', () => {
|
||||
// @ts-ignore
|
||||
sorter.selectedSort = undefined;
|
||||
expect(() => sorter.updateSortOptions()).toThrow();
|
||||
});
|
||||
|
||||
it('should not mutate original sortOptions array reference on updateSortOptions', () => {
|
||||
const original = sorter.sortOptions;
|
||||
sorter.sortBooks('title');
|
||||
expect(sorter.sortOptions).not.toBe(original);
|
||||
});
|
||||
|
||||
it('should handle sorting "random" field', () => {
|
||||
sorter.sortBooks('random');
|
||||
expect(sorter.selectedSort?.field).toBe('random');
|
||||
expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING);
|
||||
expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort);
|
||||
});
|
||||
});
|
||||
-140
@@ -1,140 +0,0 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TableColumnPreferenceService} from './table-column-preference.service';
|
||||
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
|
||||
|
||||
describe('TableColumnPreferenceService', () => {
|
||||
let service: TableColumnPreferenceService;
|
||||
let userServiceMock: any;
|
||||
let messageServiceMock: any;
|
||||
|
||||
const allColumns = [
|
||||
{field: 'readStatus', header: 'Read'},
|
||||
{field: 'title', header: 'Title'},
|
||||
{field: 'authors', header: 'Authors'},
|
||||
{field: 'publisher', header: 'Publisher'},
|
||||
{field: 'seriesName', header: 'Series'},
|
||||
{field: 'seriesNumber', header: 'Series #'},
|
||||
{field: 'categories', header: 'Genres'},
|
||||
{field: 'publishedDate', header: 'Published'},
|
||||
{field: 'lastReadTime', header: 'Last Read'},
|
||||
{field: 'addedOn', header: 'Added'},
|
||||
{field: 'fileSizeKb', header: 'File Size'},
|
||||
{field: 'language', header: 'Language'},
|
||||
{field: 'isbn', header: 'ISBN'},
|
||||
{field: 'pageCount', header: 'Pages'},
|
||||
{field: 'amazonRating', header: 'Amazon'},
|
||||
{field: 'amazonReviewCount', header: 'AZ #'},
|
||||
{field: 'goodreadsRating', header: 'Goodreads'},
|
||||
{field: 'goodreadsReviewCount', header: 'GR #'},
|
||||
{field: 'hardcoverRating', header: 'Hardcover'},
|
||||
{field: 'hardcoverReviewCount', header: 'HC #'},
|
||||
{field: 'ranobedbRating', header: 'Ranobedb'},
|
||||
];
|
||||
|
||||
const fallbackPreferences: TableColumnPreference[] = allColumns.map((col, index) => ({
|
||||
field: col.field,
|
||||
visible: true,
|
||||
order: index
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
userServiceMock = {
|
||||
getCurrentUser: vi.fn(),
|
||||
updateUserSetting: vi.fn()
|
||||
};
|
||||
messageServiceMock = {
|
||||
add: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
TableColumnPreferenceService,
|
||||
{provide: UserService, useValue: userServiceMock},
|
||||
{provide: MessageService, useValue: messageServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(TableColumnPreferenceService));
|
||||
});
|
||||
|
||||
it('should initialize with fallback preferences if none provided', () => {
|
||||
service.initPreferences(undefined);
|
||||
expect(service.preferences).toEqual(fallbackPreferences);
|
||||
});
|
||||
|
||||
it('should initialize with provided preferences', () => {
|
||||
const savedPrefs: TableColumnPreference[] = [
|
||||
{field: 'title', visible: true, order: 0},
|
||||
{field: 'authors', visible: false, order: 1}
|
||||
];
|
||||
service.initPreferences(savedPrefs);
|
||||
expect(service.preferences.find(p => p.field === 'title')?.visible).toBe(true);
|
||||
expect(service.preferences.find(p => p.field === 'authors')?.visible).toBe(false);
|
||||
expect(service.preferences.length).toBe(allColumns.length);
|
||||
});
|
||||
|
||||
it('should return all columns', () => {
|
||||
expect(service.allColumns).toEqual(allColumns);
|
||||
});
|
||||
|
||||
it('should return visible columns sorted by order', () => {
|
||||
const prefs: TableColumnPreference[] = [
|
||||
{field: 'title', visible: true, order: 1},
|
||||
{field: 'authors', visible: true, order: 0},
|
||||
{field: 'publisher', visible: false, order: 2}
|
||||
];
|
||||
service['preferencesSubject'].next([
|
||||
...prefs,
|
||||
...fallbackPreferences.filter(p => !prefs.some(fp => fp.field === p.field))
|
||||
]);
|
||||
const visible = service.visibleColumns;
|
||||
const fields = visible.map(col => col.field);
|
||||
expect(fields.indexOf('authors')).toBeLessThan(fields.indexOf('title'));
|
||||
expect(fields).not.toContain('publisher');
|
||||
});
|
||||
|
||||
it('should save visible columns and update preferences', () => {
|
||||
const selectedColumns = [
|
||||
{field: 'title'},
|
||||
{field: 'authors'}
|
||||
];
|
||||
userServiceMock.getCurrentUser.mockReturnValue({id: 42});
|
||||
service.saveVisibleColumns(selectedColumns);
|
||||
const prefs = service.preferences;
|
||||
expect(prefs.find(p => p.field === 'title')?.visible).toBe(true);
|
||||
expect(prefs.find(p => p.field === 'authors')?.visible).toBe(true);
|
||||
expect(prefs.find(p => p.field === 'publisher')?.visible).toBe(false);
|
||||
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', prefs);
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
|
||||
severity: 'success',
|
||||
summary: 'Preferences Saved'
|
||||
}));
|
||||
});
|
||||
|
||||
it('should not call updateUserSetting if no current user', () => {
|
||||
userServiceMock.getCurrentUser.mockReturnValue(undefined);
|
||||
service.saveVisibleColumns([{field: 'title'}]);
|
||||
expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should get column header for known and unknown fields', () => {
|
||||
expect(service['getColumnHeader']('title')).toBe('Title');
|
||||
expect(service['getColumnHeader']('unknown')).toBe('unknown');
|
||||
});
|
||||
|
||||
it('should merge saved preferences with all columns', () => {
|
||||
const savedPrefs: TableColumnPreference[] = [
|
||||
{field: 'title', visible: false, order: 5}
|
||||
];
|
||||
const merged = service['mergeWithAllColumns'](savedPrefs);
|
||||
expect(merged.find(p => p.field === 'title')?.visible).toBe(false);
|
||||
expect(merged.length).toBe(allColumns.length);
|
||||
expect(merged.find(p => p.field === 'authors')?.visible).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
<div class="book-file-attacher-container">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-link header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">Attach {{ isBulkMode ? 'Files' : 'File' }} to Another Book</h2>
|
||||
<p class="panel-description">Move {{ isBulkMode ? 'these books\' files' : 'this book\'s file' }} to another book as alternative format{{ isBulkMode ? 's' : '' }}</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(click)="closeDialog()"
|
||||
styleClass="close-button">
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
<div class="dialog-content">
|
||||
<!-- Source Book(s) Info -->
|
||||
<div class="source-info">
|
||||
<h3 class="section-title">Source Book{{ isBulkMode ? 's' : '' }} ({{ sourceBooks.length }})</h3>
|
||||
<div class="source-books-list">
|
||||
@for (book of sourceBooks; track book.id) {
|
||||
<div class="book-info-card">
|
||||
<div class="book-title">{{ book.metadata?.title || 'Unknown Title' }}</div>
|
||||
@if (book.metadata?.authors?.length) {
|
||||
<div class="book-authors">{{ book.metadata?.authors?.join(', ') }}</div>
|
||||
}
|
||||
<div class="file-info">
|
||||
<i class="pi pi-file"></i>
|
||||
<span>{{ getSourceFileInfo(book) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Target Book Selection -->
|
||||
<div class="target-selection">
|
||||
<h3 class="section-title">Select Target Book</h3>
|
||||
<p-autocomplete
|
||||
[(ngModel)]="targetBook"
|
||||
[suggestions]="filteredBooks"
|
||||
(completeMethod)="filterBooks($event)"
|
||||
(onSelect)="onBookSelect($event)"
|
||||
(onClear)="onBookClear()"
|
||||
optionLabel="metadata.title"
|
||||
[dropdown]="true"
|
||||
[showClear]="true"
|
||||
placeholder="Search for a book in the same library..."
|
||||
styleClass="full-width"
|
||||
[disabled]="isAttaching">
|
||||
<ng-template let-book pTemplate="item">
|
||||
<div class="book-suggestion">
|
||||
<div class="suggestion-title">{{ book.metadata?.title || 'Unknown Title' }}</div>
|
||||
@if (book.metadata?.authors?.length) {
|
||||
<div class="suggestion-authors">{{ book.metadata.authors.join(', ') }}</div>
|
||||
}
|
||||
@if (book.primaryFile) {
|
||||
<div class="suggestion-format">{{ book.primaryFile.extension?.toUpperCase() || book.primaryFile.bookType }}</div>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
<ng-template let-book pTemplate="selectedItem">
|
||||
<span>{{ getBookDisplayName(book) }}</span>
|
||||
</ng-template>
|
||||
</p-autocomplete>
|
||||
</div>
|
||||
|
||||
<!-- Delete Source Book(s) Option -->
|
||||
<div class="delete-option">
|
||||
<p-checkbox
|
||||
[(ngModel)]="deleteSourceBooks"
|
||||
[binary]="true"
|
||||
inputId="deleteSourceBooks"
|
||||
[disabled]="isAttaching">
|
||||
</p-checkbox>
|
||||
<label for="deleteSourceBooks" class="delete-label">
|
||||
Delete source book{{ isBulkMode ? 's' : '' }} after attachment
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- Warning Message -->
|
||||
<div class="warning-message">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<div class="warning-text">
|
||||
<p>This will move {{ isBulkMode ? 'the files from the selected books' : 'the file from the source book' }} to the target book as alternative format{{ isBulkMode ? 's' : '' }}.</p>
|
||||
@if (deleteSourceBooks) {
|
||||
<p>The source book{{ isBulkMode ? ' records' : ' record' }} will be deleted (file{{ isBulkMode ? 's' : '' }} will be preserved in target book).</p>
|
||||
} @else {
|
||||
<p>The source book{{ isBulkMode ? ' records' : ' record' }} will remain but will have no readable files.</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="action-buttons">
|
||||
<p-button
|
||||
label="Cancel"
|
||||
[outlined]="true"
|
||||
severity="secondary"
|
||||
(click)="closeDialog()"
|
||||
[disabled]="isAttaching">
|
||||
</p-button>
|
||||
<p-button
|
||||
label="Attach {{ isBulkMode ? 'Files' : 'File' }}"
|
||||
icon="pi pi-link"
|
||||
(click)="attach()"
|
||||
[disabled]="!canAttach()"
|
||||
[loading]="isAttaching">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
@use '../../../../shared/styles/panel-shared' as panel;
|
||||
|
||||
.book-file-attacher-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
@include panel.panel-header;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.dialog-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
min-height: 0;
|
||||
padding: 1.5rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-top: none;
|
||||
border-radius: 0 0 10px 10px;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-muted-color);
|
||||
margin-bottom: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.source-info {
|
||||
.source-books-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.book-info-card {
|
||||
background: var(--p-surface-100);
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem 1rem;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.book-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.9375rem;
|
||||
margin-bottom: 0.125rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.book-authors {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.8125rem;
|
||||
margin-bottom: 0.375rem;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--p-primary-color);
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
|
||||
i {
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
span {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.target-selection {
|
||||
:host ::ng-deep {
|
||||
.full-width {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.book-suggestion {
|
||||
padding: 0.25rem 0;
|
||||
|
||||
.suggestion-title {
|
||||
font-weight: 500;
|
||||
margin-bottom: 0.125rem;
|
||||
}
|
||||
|
||||
.suggestion-authors {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
|
||||
.suggestion-format {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-primary-color);
|
||||
font-weight: 600;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.delete-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
|
||||
.delete-label {
|
||||
font-size: 0.9375rem;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
}
|
||||
|
||||
.warning-message {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
background: var(--p-yellow-50);
|
||||
border: 1px solid var(--p-yellow-200);
|
||||
border-radius: 8px;
|
||||
color: var(--p-yellow-800);
|
||||
|
||||
i {
|
||||
flex-shrink: 0;
|
||||
font-size: 1.25rem;
|
||||
margin-top: 0.125rem;
|
||||
}
|
||||
|
||||
.warning-text {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
|
||||
&:not(:last-child) {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:host-context(.p-dark) {
|
||||
.warning-message {
|
||||
background: rgba(234, 179, 8, 0.1);
|
||||
border-color: rgba(234, 179, 8, 0.3);
|
||||
color: var(--p-yellow-400);
|
||||
}
|
||||
|
||||
.source-info .book-info-card {
|
||||
background: var(--p-surface-800);
|
||||
}
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
margin-top: auto;
|
||||
padding-top: 0.5rem;
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import { Component, OnInit, OnDestroy } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
|
||||
import { AutoComplete, AutoCompleteSelectEvent } from 'primeng/autocomplete';
|
||||
import { Button } from 'primeng/button';
|
||||
import { Checkbox } from 'primeng/checkbox';
|
||||
import { Subject, takeUntil } from 'rxjs';
|
||||
import { filter, take } from 'rxjs/operators';
|
||||
import { BookService } from '../../service/book.service';
|
||||
import { Book } from '../../model/book.model';
|
||||
import { MessageService } from 'primeng/api';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-file-attacher',
|
||||
standalone: true,
|
||||
imports: [
|
||||
FormsModule,
|
||||
AutoComplete,
|
||||
Button,
|
||||
Checkbox
|
||||
],
|
||||
templateUrl: './book-file-attacher.component.html',
|
||||
styleUrls: ['./book-file-attacher.component.scss']
|
||||
})
|
||||
export class BookFileAttacherComponent implements OnInit, OnDestroy {
|
||||
sourceBooks: Book[] = [];
|
||||
targetBook: Book | null = null;
|
||||
deleteSourceBooks = true;
|
||||
isAttaching = false;
|
||||
searchQuery = '';
|
||||
filteredBooks: Book[] = [];
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private allBooks: Book[] = [];
|
||||
|
||||
constructor(
|
||||
private dialogRef: DynamicDialogRef,
|
||||
private config: DynamicDialogConfig,
|
||||
private bookService: BookService,
|
||||
private messageService: MessageService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
// Support both single book and multiple books
|
||||
if (this.config.data.sourceBook) {
|
||||
this.sourceBooks = [this.config.data.sourceBook];
|
||||
} else if (this.config.data.sourceBooks) {
|
||||
this.sourceBooks = this.config.data.sourceBooks;
|
||||
}
|
||||
|
||||
if (this.sourceBooks.length === 0) {
|
||||
this.closeDialog();
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the library ID from first source book (all should be same library)
|
||||
const libraryId = this.sourceBooks[0].libraryId;
|
||||
const sourceBookIds = new Set(this.sourceBooks.map(b => b.id));
|
||||
|
||||
// Load all books from state and filter for same library, excluding source books
|
||||
this.bookService.bookState$.pipe(
|
||||
filter(state => state.loaded && !!state.books),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(state => {
|
||||
this.allBooks = (state.books || []).filter(book =>
|
||||
book.libraryId === libraryId && !sourceBookIds.has(book.id)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
get isBulkMode(): boolean {
|
||||
return this.sourceBooks.length > 1;
|
||||
}
|
||||
|
||||
filterBooks(event: { query: string }): void {
|
||||
const query = event.query.toLowerCase().trim();
|
||||
if (!query) {
|
||||
this.filteredBooks = this.allBooks.slice(0, 20);
|
||||
return;
|
||||
}
|
||||
|
||||
this.filteredBooks = this.allBooks
|
||||
.filter(book => {
|
||||
const title = book.metadata?.title?.toLowerCase() || '';
|
||||
const authors = book.metadata?.authors?.join(' ').toLowerCase() || '';
|
||||
return title.includes(query) || authors.includes(query);
|
||||
})
|
||||
.slice(0, 20);
|
||||
}
|
||||
|
||||
onBookSelect(event: AutoCompleteSelectEvent): void {
|
||||
this.targetBook = event.value as Book;
|
||||
}
|
||||
|
||||
onBookClear(): void {
|
||||
this.targetBook = null;
|
||||
}
|
||||
|
||||
getBookDisplayName(book: Book): string {
|
||||
const title = book.metadata?.title || `Book #${book.id}`;
|
||||
const authors = book.metadata?.authors?.join(', ');
|
||||
return authors ? `${title} - ${authors}` : title;
|
||||
}
|
||||
|
||||
getSourceFileInfo(book: Book): string {
|
||||
const file = book.primaryFile;
|
||||
if (!file) return 'Unknown file';
|
||||
const format = file.extension?.toUpperCase() || file.bookType || 'Unknown';
|
||||
return `${format} - ${file.fileName || 'Unknown filename'}`;
|
||||
}
|
||||
|
||||
canAttach(): boolean {
|
||||
return !!this.targetBook && !this.isAttaching;
|
||||
}
|
||||
|
||||
attach(): void {
|
||||
if (!this.targetBook) return;
|
||||
|
||||
this.isAttaching = true;
|
||||
|
||||
const sourceBookIds = this.sourceBooks.map(b => b.id);
|
||||
|
||||
this.bookService.attachBookFiles(
|
||||
this.targetBook.id,
|
||||
sourceBookIds,
|
||||
this.deleteSourceBooks
|
||||
).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: () => {
|
||||
this.dialogRef.close({ success: true, deletedSourceBooks: this.deleteSourceBooks });
|
||||
},
|
||||
error: () => {
|
||||
this.isAttaching = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
closeDialog(): void {
|
||||
this.dialogRef.close();
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,7 @@
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (userState.user!.permissions.canMoveOrganizeFiles) {
|
||||
@if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-arrows-h"
|
||||
|
||||
@@ -21,6 +21,7 @@ import {BookDialogHelperService} from "../book-browser/book-dialog-helper.servic
|
||||
import {TaskHelperService} from "../../../settings/task-management/task-helper.service";
|
||||
import {MetadataRefreshType} from "../../../metadata/model/request/metadata-refresh-type.enum";
|
||||
import {TieredMenu} from "primeng/tieredmenu";
|
||||
import {AppSettingsService} from "../../../../shared/service/app-settings.service";
|
||||
import {Tooltip} from "primeng/tooltip";
|
||||
import {Divider} from "primeng/divider";
|
||||
import {animate, style, transition, trigger} from "@angular/animations";
|
||||
@@ -78,6 +79,7 @@ export class SeriesPageComponent implements OnDestroy {
|
||||
private dialogHelperService = inject(BookDialogHelperService);
|
||||
protected taskHelperService = inject(TaskHelperService);
|
||||
private messageService = inject(MessageService);
|
||||
protected appSettingsService = inject(AppSettingsService);
|
||||
|
||||
tab: string = "view";
|
||||
isExpanded = false;
|
||||
|
||||
@@ -3,7 +3,7 @@ import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrol
|
||||
import {BookReview} from '../components/book-reviews/book-review-service';
|
||||
import {ZoomType} from 'ngx-extended-pdf-viewer';
|
||||
|
||||
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3";
|
||||
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3" | "AUDIOBOOK";
|
||||
|
||||
export enum AdditionalFileType {
|
||||
ALTERNATIVE_FORMAT = 'ALTERNATIVE_FORMAT',
|
||||
@@ -17,17 +17,23 @@ export interface FileInfo {
|
||||
fileSizeKb?: number;
|
||||
}
|
||||
|
||||
export interface AdditionalFile extends FileInfo {
|
||||
export interface BookFile extends FileInfo {
|
||||
id: number;
|
||||
bookId: number;
|
||||
additionalFileType: AdditionalFileType;
|
||||
description?: string;
|
||||
bookType?: BookType;
|
||||
folderBased?: boolean;
|
||||
extension?: string;
|
||||
addedOn?: string;
|
||||
}
|
||||
|
||||
export interface AdditionalFile extends BookFile {
|
||||
additionalFileType?: AdditionalFileType;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface Book extends FileInfo {
|
||||
id: number;
|
||||
bookType: BookType;
|
||||
primaryFile?: BookFile;
|
||||
libraryId: number;
|
||||
libraryName: string;
|
||||
metadata?: BookMetadata;
|
||||
@@ -37,6 +43,7 @@ export interface Book extends FileInfo {
|
||||
epubProgress?: EpubProgress;
|
||||
pdfProgress?: PdfProgress;
|
||||
cbxProgress?: CbxProgress;
|
||||
audiobookProgress?: AudiobookProgress;
|
||||
koreaderProgress?: KoReaderProgress;
|
||||
koboProgress?: KoboProgress;
|
||||
seriesCount?: number | null;
|
||||
@@ -48,6 +55,7 @@ export interface Book extends FileInfo {
|
||||
libraryPath?: { id: number };
|
||||
alternativeFormats?: AdditionalFile[];
|
||||
supplementaryFiles?: AdditionalFile[];
|
||||
isPhysical?: boolean;
|
||||
|
||||
[key: string]: unknown;
|
||||
}
|
||||
@@ -75,6 +83,20 @@ export interface KoboProgress {
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface AudiobookProgress {
|
||||
positionMs: number;
|
||||
trackIndex?: number;
|
||||
trackPositionMs?: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface BookFileProgress {
|
||||
bookFileId: number;
|
||||
positionData?: string;
|
||||
positionHref?: string;
|
||||
progressPercent: number;
|
||||
}
|
||||
|
||||
export interface BookMetadata {
|
||||
bookId: number;
|
||||
title?: string;
|
||||
@@ -291,3 +313,16 @@ export enum ReadStatus {
|
||||
ABANDONED = 'ABANDONED',
|
||||
UNSET = 'UNSET'
|
||||
}
|
||||
|
||||
export interface CreatePhysicalBookRequest {
|
||||
libraryId: number;
|
||||
isbn?: string;
|
||||
title?: string;
|
||||
authors?: string[];
|
||||
description?: string;
|
||||
publisher?: string;
|
||||
publishedDate?: string;
|
||||
language?: string;
|
||||
pageCount?: number;
|
||||
categories?: string[];
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import {SortOption} from './sort.model';
|
||||
|
||||
export type LibraryScanMode = 'FILE_AS_BOOK' | 'FOLDER_AS_BOOK';
|
||||
export type BookFileType = 'PDF' | 'EPUB' | 'CBX' | 'FB2' | 'MOBI' | 'AZW3';
|
||||
import {BookType} from './book.model';
|
||||
|
||||
export interface Library {
|
||||
id?: number;
|
||||
@@ -12,8 +10,7 @@ export interface Library {
|
||||
fileNamingPattern?: string;
|
||||
sort?: SortOption;
|
||||
paths: LibraryPath[];
|
||||
scanMode?: LibraryScanMode;
|
||||
defaultBookFormat?: BookFileType;
|
||||
formatPriority?: BookType[];
|
||||
}
|
||||
|
||||
export interface LibraryPath {
|
||||
|
||||
@@ -1,478 +0,0 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {BookService} from './book.service';
|
||||
import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {User} from '../../settings/user-management/user.service';
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {HttpErrorResponse} from '@angular/common/http';
|
||||
import {APIException} from '../../../shared/models/api-exception.model';
|
||||
import {BookMenuService} from './book-menu.service';
|
||||
|
||||
describe('BookMenuService', () => {
|
||||
let service: BookMenuService;
|
||||
let confirmationService: any;
|
||||
let messageService: any;
|
||||
let bookService: any;
|
||||
let loadingService: any;
|
||||
|
||||
const mockUser: User = {
|
||||
id: 1,
|
||||
username: 'testuser',
|
||||
email: 'test@example.com',
|
||||
permissions: {
|
||||
canBulkAutoFetchMetadata: true,
|
||||
canBulkCustomFetchMetadata: true,
|
||||
canBulkEditMetadata: true,
|
||||
canBulkRegenerateCover: true,
|
||||
canBulkResetBookReadStatus: true,
|
||||
canBulkResetBookloreReadProgress: true,
|
||||
canBulkResetKoReaderReadProgress: true
|
||||
}
|
||||
} as User;
|
||||
|
||||
const mockUserNoPermissions: User = {
|
||||
id: 2,
|
||||
username: 'limiteduser',
|
||||
email: 'limited@example.com',
|
||||
permissions: {
|
||||
canBulkAutoFetchMetadata: false,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: false,
|
||||
canBulkRegenerateCover: false,
|
||||
canBulkResetBookReadStatus: false,
|
||||
canBulkResetBookloreReadProgress: false,
|
||||
canBulkResetKoReaderReadProgress: false
|
||||
}
|
||||
} as User;
|
||||
|
||||
beforeEach(() => {
|
||||
confirmationService = {
|
||||
confirm: vi.fn()
|
||||
};
|
||||
|
||||
messageService = {
|
||||
add: vi.fn()
|
||||
};
|
||||
|
||||
bookService = {
|
||||
updateBookReadStatus: vi.fn(),
|
||||
resetProgress: vi.fn()
|
||||
};
|
||||
|
||||
loadingService = {
|
||||
show: vi.fn().mockReturnValue('loader-id'),
|
||||
hide: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookMenuService,
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: BookService, useValue: bookService},
|
||||
{provide: LoadingService, useValue: loadingService}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(BookMenuService)
|
||||
);
|
||||
});
|
||||
|
||||
describe('getMetadataMenuItems', () => {
|
||||
it('should return all metadata menu items when user has all permissions', () => {
|
||||
const autoFetch = vi.fn();
|
||||
const fetch = vi.fn();
|
||||
const bulkEdit = vi.fn();
|
||||
const multiEdit = vi.fn();
|
||||
const regenerate = vi.fn();
|
||||
const generateCustomCovers = vi.fn();
|
||||
|
||||
const items = service.getMetadataMenuItems(
|
||||
autoFetch,
|
||||
fetch,
|
||||
bulkEdit,
|
||||
multiEdit,
|
||||
regenerate,
|
||||
generateCustomCovers,
|
||||
mockUser
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(6);
|
||||
expect(items[0].label).toBe('Auto Fetch Metadata');
|
||||
expect(items[0].icon).toBe('pi pi-bolt');
|
||||
expect(items[1].label).toBe('Custom Fetch Metadata');
|
||||
expect(items[1].icon).toBe('pi pi-sync');
|
||||
expect(items[2].label).toBe('Bulk Metadata Editor');
|
||||
expect(items[2].icon).toBe('pi pi-table');
|
||||
expect(items[3].label).toBe('Multi-Book Metadata Editor');
|
||||
expect(items[3].icon).toBe('pi pi-clone');
|
||||
expect(items[4].label).toBe('Regenerate Covers');
|
||||
expect(items[4].icon).toBe('pi pi-image');
|
||||
expect(items[5].label).toBe('Generate Custom Covers');
|
||||
expect(items[5].icon).toBe('pi pi-palette');
|
||||
});
|
||||
|
||||
it('should return empty array when user has no permissions', () => {
|
||||
const items = service.getMetadataMenuItems(
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
mockUserNoPermissions
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return empty array when user is null', () => {
|
||||
const items = service.getMetadataMenuItems(
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
null
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should call command functions when menu items are clicked', () => {
|
||||
const autoFetch = vi.fn();
|
||||
const fetch = vi.fn();
|
||||
const bulkEdit = vi.fn();
|
||||
const multiEdit = vi.fn();
|
||||
const regenerate = vi.fn();
|
||||
const generateCustomCovers = vi.fn();
|
||||
|
||||
const items = service.getMetadataMenuItems(
|
||||
autoFetch,
|
||||
fetch,
|
||||
bulkEdit,
|
||||
multiEdit,
|
||||
regenerate,
|
||||
generateCustomCovers,
|
||||
mockUser
|
||||
);
|
||||
|
||||
items[0].command!({} as any);
|
||||
expect(autoFetch).toHaveBeenCalledOnce();
|
||||
|
||||
items[1].command!({} as any);
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
|
||||
items[2].command!({} as any);
|
||||
expect(bulkEdit).toHaveBeenCalledOnce();
|
||||
|
||||
items[3].command!({} as any);
|
||||
expect(multiEdit).toHaveBeenCalledOnce();
|
||||
|
||||
items[4].command!({} as any);
|
||||
expect(regenerate).toHaveBeenCalledOnce();
|
||||
|
||||
items[5].command!({} as any);
|
||||
expect(generateCustomCovers).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('should return only items for granted permissions', () => {
|
||||
const partialUser: User = {
|
||||
...mockUser,
|
||||
permissions: {
|
||||
...mockUser.permissions,
|
||||
canBulkAutoFetchMetadata: true,
|
||||
canBulkCustomFetchMetadata: false,
|
||||
canBulkEditMetadata: true,
|
||||
canBulkRegenerateCover: false
|
||||
}
|
||||
} as User;
|
||||
|
||||
const items = service.getMetadataMenuItems(
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
partialUser
|
||||
);
|
||||
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items[0].label).toBe('Auto Fetch Metadata');
|
||||
expect(items[1].label).toBe('Bulk Metadata Editor');
|
||||
expect(items[2].label).toBe('Multi-Book Metadata Editor');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBulkReadActionsMenu', () => {
|
||||
it('should return all read action items when user has all permissions', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items[0].label).toBe('Update Read Status');
|
||||
expect(items[0].icon).toBe('pi pi-book');
|
||||
expect(items[0].items).toBeDefined();
|
||||
expect(items[0].items!.length).toBeGreaterThan(0);
|
||||
expect(items[1].label).toBe('Reset Booklore Progress');
|
||||
expect(items[1].icon).toBe('pi pi-undo');
|
||||
expect(items[2].label).toBe('Reset KOReader Progress');
|
||||
expect(items[2].icon).toBe('pi pi-undo');
|
||||
});
|
||||
|
||||
it('should return empty array when user has no permissions', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUserNoPermissions);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should return empty array when user is null', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, null);
|
||||
|
||||
expect(items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should show confirmation dialog when updating read status', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
const readStatusItems = items[0].items!;
|
||||
readStatusItems[0].command!({} as any);
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain('3 book(s)');
|
||||
expect(confirmCall.header).toBe('Confirm Read Status Update');
|
||||
});
|
||||
|
||||
it('should update read status on confirmation accept', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(of([]));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
const readStatusItems = items[0].items!;
|
||||
|
||||
const readItem = readStatusItems.find(item => item.label === 'Read');
|
||||
expect(readItem).toBeDefined();
|
||||
|
||||
readItem!.command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(loadingService.show).toHaveBeenCalledWith('Updating read status for 3 book(s)...');
|
||||
expect(bookService.updateBookReadStatus).toHaveBeenCalledWith([1, 2, 3], ReadStatus.READ);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'Read Status Updated',
|
||||
detail: 'Marked as "Read"',
|
||||
life: 2000
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message when read status update fails', () => {
|
||||
const selectedBooks = new Set([1, 2]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {message: 'Update failed'} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
const readStatusItems = items[0].items!;
|
||||
|
||||
readStatusItems[0].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Update failed',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog when resetting Booklore progress', () => {
|
||||
const selectedBooks = new Set([1, 2, 3]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
items[1].command!({} as any);
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain('3 book(s)');
|
||||
expect(confirmCall.header).toBe('Confirm Reset');
|
||||
});
|
||||
|
||||
it('should reset Booklore progress on confirmation accept', () => {
|
||||
const selectedBooks = new Set([5, 6]);
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(of([]));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[1].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(loadingService.show).toHaveBeenCalledWith('Resetting Booklore progress for 2 book(s)...');
|
||||
expect(bookService.resetProgress).toHaveBeenCalledWith([5, 6], ResetProgressTypes.BOOKLORE);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'Booklore reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message when Booklore progress reset fails', () => {
|
||||
const selectedBooks = new Set([1]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {message: 'Reset failed'} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[1].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Reset failed',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog when resetting KOReader progress', () => {
|
||||
const selectedBooks = new Set([7, 8]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
items[2].command!({} as any);
|
||||
|
||||
expect(confirmationService.confirm).toHaveBeenCalledOnce();
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain('2 book(s)');
|
||||
expect(confirmCall.message).toContain('KOReader');
|
||||
expect(confirmCall.header).toBe('Confirm Reset');
|
||||
});
|
||||
|
||||
it('should reset KOReader progress on confirmation accept', () => {
|
||||
const selectedBooks = new Set([9]);
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(of([]));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[2].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(loadingService.show).toHaveBeenCalledWith('Resetting KOReader progress for 1 book(s)...');
|
||||
expect(bookService.resetProgress).toHaveBeenCalledWith([9], ResetProgressTypes.KOREADER);
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'success',
|
||||
summary: 'Progress Reset',
|
||||
detail: 'KOReader reading progress has been reset.',
|
||||
life: 1500
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message when KOReader progress reset fails', () => {
|
||||
const selectedBooks = new Set([10]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {message: 'KOReader reset failed'} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
items[2].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'KOReader reset failed',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle API error without message gracefully', () => {
|
||||
const selectedBooks = new Set([1]);
|
||||
const errorResponse = new HttpErrorResponse({
|
||||
error: {} as APIException,
|
||||
status: 500
|
||||
});
|
||||
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse));
|
||||
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
const readStatusItems = items[0].items!;
|
||||
|
||||
readStatusItems[0].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.accept!();
|
||||
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Could not update read status.',
|
||||
life: 3000
|
||||
});
|
||||
});
|
||||
|
||||
it('should return only items for granted read permissions', () => {
|
||||
const partialUser: User = {
|
||||
...mockUser,
|
||||
permissions: {
|
||||
...mockUser.permissions,
|
||||
canBulkResetBookReadStatus: true,
|
||||
canBulkResetBookloreReadProgress: false,
|
||||
canBulkResetKoReaderReadProgress: true
|
||||
}
|
||||
} as User;
|
||||
|
||||
const selectedBooks = new Set([1, 2]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, partialUser);
|
||||
|
||||
expect(items).toHaveLength(2);
|
||||
expect(items[0].label).toBe('Update Read Status');
|
||||
expect(items[1].label).toBe('Reset KOReader Progress');
|
||||
});
|
||||
|
||||
it('should not call bookService when confirmation is rejected', () => {
|
||||
const selectedBooks = new Set([1, 2]);
|
||||
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
|
||||
|
||||
items[1].command!({} as any);
|
||||
|
||||
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
|
||||
confirmCall.reject?.();
|
||||
|
||||
expect(bookService.resetProgress).not.toHaveBeenCalled();
|
||||
expect(loadingService.show).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import {beforeEach, describe, expect, it} from 'vitest';
|
||||
import {firstValueFrom} from 'rxjs';
|
||||
import {BookNavigationService} from './book-navigation.service';
|
||||
|
||||
describe('BookNavigationService', () => {
|
||||
let service: BookNavigationService;
|
||||
const bookIds = [10, 20, 30, 40];
|
||||
|
||||
beforeEach(() => {
|
||||
service = new BookNavigationService();
|
||||
});
|
||||
|
||||
it('should set and get available book ids', () => {
|
||||
service.setAvailableBookIds(bookIds);
|
||||
expect(service.getAvailableBookIds()).toEqual(bookIds);
|
||||
});
|
||||
|
||||
it('should set navigation context and emit state', async () => {
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state).not.toBeNull();
|
||||
expect(state!.bookIds).toEqual(bookIds);
|
||||
expect(state!.currentIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('should emit null if currentBookId not in bookIds', async () => {
|
||||
service.setNavigationContext(bookIds, 99);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state).toBeNull();
|
||||
});
|
||||
|
||||
it('should determine canNavigatePrevious correctly', () => {
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
expect(service.canNavigatePrevious()).toBe(false);
|
||||
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
expect(service.canNavigatePrevious()).toBe(true);
|
||||
});
|
||||
|
||||
it('should determine canNavigateNext correctly', () => {
|
||||
service.setNavigationContext(bookIds, 40);
|
||||
expect(service.canNavigateNext()).toBe(false);
|
||||
|
||||
service.setNavigationContext(bookIds, 20);
|
||||
expect(service.canNavigateNext()).toBe(true);
|
||||
});
|
||||
|
||||
it('should get previous book id', () => {
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
expect(service.getPreviousBookId()).toBe(20);
|
||||
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
expect(service.getPreviousBookId()).toBeNull();
|
||||
});
|
||||
|
||||
it('should get next book id', () => {
|
||||
service.setNavigationContext(bookIds, 20);
|
||||
expect(service.getNextBookId()).toBe(30);
|
||||
|
||||
service.setNavigationContext(bookIds, 40);
|
||||
expect(service.getNextBookId()).toBeNull();
|
||||
});
|
||||
|
||||
it('should update current book and emit new index', async () => {
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
service.updateCurrentBook(30);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state!.currentIndex).toBe(2);
|
||||
expect(state!.bookIds[state!.currentIndex]).toBe(30);
|
||||
});
|
||||
|
||||
it('should not update current book if id not in list', async () => {
|
||||
service.setNavigationContext(bookIds, 10);
|
||||
service.updateCurrentBook(99);
|
||||
|
||||
const state = await firstValueFrom(service.getNavigationState());
|
||||
|
||||
expect(state!.currentIndex).toBe(0);
|
||||
expect(state!.bookIds[state!.currentIndex]).toBe(10);
|
||||
});
|
||||
|
||||
it('should return current position', () => {
|
||||
service.setNavigationContext(bookIds, 30);
|
||||
expect(service.getCurrentPosition()).toEqual({current: 3, total: 4});
|
||||
});
|
||||
|
||||
it('should return null for current position if no state', () => {
|
||||
expect(service.getCurrentPosition()).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle navigation methods gracefully if state is null', () => {
|
||||
expect(service.canNavigatePrevious()).toBe(false);
|
||||
expect(service.canNavigateNext()).toBe(false);
|
||||
expect(service.getPreviousBookId()).toBeNull();
|
||||
expect(service.getNextBookId()).toBeNull();
|
||||
|
||||
service.updateCurrentBook(10);
|
||||
expect(service.getCurrentPosition()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,171 +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 {BookPatchService} from './book-patch.service';
|
||||
import {BookStateService} from './book-state.service';
|
||||
import {Book, ReadStatus} from '../model/book.model';
|
||||
|
||||
describe('BookPatchService', () => {
|
||||
let service: BookPatchService;
|
||||
let httpMock: any;
|
||||
let bookStateServiceMock: any;
|
||||
|
||||
const mockBooks: Book[] = [
|
||||
{id: 1, bookType: 'PDF', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book,
|
||||
{id: 2, bookType: 'EPUB', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book,
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
httpMock = {
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
};
|
||||
bookStateServiceMock = {
|
||||
getCurrentBookState: vi.fn(),
|
||||
updateBookState: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookPatchService,
|
||||
{provide: HttpClient, useValue: httpMock},
|
||||
{provide: BookStateService, useValue: bookStateServiceMock},
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(BookPatchService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should update book shelves and update state', () => {
|
||||
const updatedBooks = [{...mockBooks[0], id: 1, libraryName: 'Updated'}];
|
||||
httpMock.post.mockReturnValue(of(updatedBooks));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])).subscribe(result => {
|
||||
expect(result).toEqual(updatedBooks);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
|
||||
books: expect.arrayContaining([expect.objectContaining({id: 1, libraryName: 'Updated'})])
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
it('should save PDF progress', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
service.savePdfProgress(1, 10, 0.5).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 1,
|
||||
pdfProgress: {page: 10, percentage: 0.5}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should save EPUB progress', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
service.saveEpubProgress(2, 'cfi123', 'href123', 0.8);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 2,
|
||||
epubProgress: {cfi: 'cfi123', href: 'href123', percentage: 0.8}
|
||||
});
|
||||
});
|
||||
|
||||
it('should save CBX progress', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
service.saveCbxProgress(3, 5, 0.2).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
|
||||
bookId: 3,
|
||||
cbxProgress: {page: 5, percentage: 0.2}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should update date finished and update state', () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateDateFinished(1, '2023-01-01').subscribe(() => {
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
|
||||
books: expect.arrayContaining([expect.objectContaining({id: 1, dateFinished: '2023-01-01'})])
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset progress and update state', () => {
|
||||
const responses = [{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: 'now', dateFinished: undefined}];
|
||||
httpMock.post.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.resetProgress([1], 'BOOKLORE').subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/reset-progress'),
|
||||
[1],
|
||||
{params: expect.any(HttpParams)}
|
||||
);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should update book read status and update state', () => {
|
||||
const responses = [{bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: 'now', dateFinished: '2023-01-01'}];
|
||||
httpMock.post.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateBookReadStatus([2], ReadStatus.READING).subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/status'),
|
||||
{bookIds: [2], status: ReadStatus.READING}
|
||||
);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should reset personal rating and update state', () => {
|
||||
const responses = [{bookId: 1, personalRating: null}];
|
||||
httpMock.post.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.resetPersonalRating([1]).subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/reset-personal-rating'), [1]);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should update personal rating and update state', () => {
|
||||
const responses = [{bookId: 2, personalRating: 5}];
|
||||
httpMock.put.mockReturnValue(of(responses));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updatePersonalRating([2], 5).subscribe(result => {
|
||||
expect(result).toEqual(responses);
|
||||
expect(httpMock.put).toHaveBeenCalledWith(expect.stringContaining('/personal-rating'), {ids: [2], rating: 5});
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should update last read time in state', () => {
|
||||
const now = new Date().toISOString();
|
||||
vi.useFakeTimers().setSystemTime(new Date(now));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
|
||||
service.updateLastReadTime(1);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
|
||||
books: expect.arrayContaining([expect.objectContaining({id: 1, lastReadTime: now})])
|
||||
}));
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should handle errors from http.post gracefully', () => {
|
||||
httpMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.savePdfProgress(1, 1, 1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {Observable, Subject} from 'rxjs';
|
||||
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
|
||||
import {Book, ReadStatus} from '../model/book.model';
|
||||
import {Book, BookFileProgress, ReadStatus} from '../model/book.model';
|
||||
import {BookStateService} from './book-state.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
@@ -17,17 +17,18 @@ export class BookPatchService {
|
||||
private http = inject(HttpClient);
|
||||
private bookStateService = inject(BookStateService);
|
||||
|
||||
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number }>();
|
||||
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number; bookFileId?: number }>();
|
||||
|
||||
private epubProgress$ = this.epubProgressSubject.pipe(
|
||||
distinctUntilChanged((prev, curr) =>
|
||||
prev.bookId === curr.bookId &&
|
||||
prev.cfi === curr.cfi &&
|
||||
prev.href === curr.href &&
|
||||
prev.percentage === curr.percentage
|
||||
prev.percentage === curr.percentage &&
|
||||
prev.bookFileId === curr.bookFileId
|
||||
),
|
||||
exhaustMap(payload => {
|
||||
const body = {
|
||||
const body: any = {
|
||||
bookId: payload.bookId,
|
||||
epubProgress: {
|
||||
cfi: payload.cfi,
|
||||
@@ -35,6 +36,15 @@ export class BookPatchService {
|
||||
percentage: payload.percentage
|
||||
}
|
||||
};
|
||||
// Add file-level progress if bookFileId is provided
|
||||
if (payload.bookFileId) {
|
||||
body.fileProgress = {
|
||||
bookFileId: payload.bookFileId,
|
||||
positionData: payload.cfi,
|
||||
positionHref: payload.href,
|
||||
progressPercent: payload.percentage
|
||||
};
|
||||
}
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}),
|
||||
share()
|
||||
@@ -65,29 +75,57 @@ export class BookPatchService {
|
||||
);
|
||||
}
|
||||
|
||||
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
const body = {
|
||||
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||
const body: any = {
|
||||
bookId: bookId,
|
||||
pdfProgress: {
|
||||
page: page,
|
||||
percentage: percentage
|
||||
}
|
||||
};
|
||||
// Add file-level progress if bookFileId is provided
|
||||
if (bookFileId) {
|
||||
body.fileProgress = {
|
||||
bookFileId: bookFileId,
|
||||
positionData: String(page),
|
||||
progressPercent: percentage
|
||||
};
|
||||
}
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): void {
|
||||
this.epubProgressSubject.next({bookId, cfi, href, percentage});
|
||||
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number, bookFileId?: number): void {
|
||||
this.epubProgressSubject.next({bookId, cfi, href, percentage, bookFileId});
|
||||
}
|
||||
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
const body = {
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||
const body: any = {
|
||||
bookId: bookId,
|
||||
cbxProgress: {
|
||||
page: page,
|
||||
percentage: percentage
|
||||
}
|
||||
};
|
||||
// Add file-level progress if bookFileId is provided
|
||||
if (bookFileId) {
|
||||
body.fileProgress = {
|
||||
bookFileId: bookFileId,
|
||||
positionData: String(page),
|
||||
progressPercent: percentage
|
||||
};
|
||||
}
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save file-level progress directly using the new API.
|
||||
* This is the preferred method for per-file progress tracking.
|
||||
*/
|
||||
saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
fileProgress: fileProgress
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,511 +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 {firstValueFrom, of, throwError} from 'rxjs';
|
||||
import {BookService} from './book.service';
|
||||
import {BookStateService} from './book-state.service';
|
||||
import {BookSocketService} from './book-socket.service';
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {AdditionalFileType, Book, BookMetadata, ReadStatus} from '../model/book.model';
|
||||
|
||||
describe('BookService', () => {
|
||||
let service: BookService;
|
||||
let httpMock: any;
|
||||
let messageServiceMock: any;
|
||||
let authServiceMock: any;
|
||||
let fileDownloadServiceMock: any;
|
||||
let routerMock: any;
|
||||
let bookStateServiceMock: any;
|
||||
let bookSocketServiceMock: any;
|
||||
let bookPatchServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
messageServiceMock = {add: vi.fn()};
|
||||
authServiceMock = {token$: of('token')};
|
||||
fileDownloadServiceMock = {downloadFile: vi.fn()};
|
||||
routerMock = {navigate: vi.fn()};
|
||||
bookStateServiceMock = {
|
||||
bookState$: of({books: [{id: 1, bookType: 'PDF', shelves: [], metadata: {seriesName: 'S'}}], loaded: true, error: null}),
|
||||
getCurrentBookState: vi.fn(),
|
||||
updateBookState: vi.fn(),
|
||||
resetBookState: vi.fn()
|
||||
};
|
||||
bookSocketServiceMock = {
|
||||
handleNewlyCreatedBook: vi.fn(),
|
||||
handleRemovedBookIds: vi.fn(),
|
||||
handleBookUpdate: vi.fn(),
|
||||
handleMultipleBookUpdates: vi.fn(),
|
||||
handleBookMetadataUpdate: vi.fn(),
|
||||
handleMultipleBookCoverPatches: vi.fn()
|
||||
};
|
||||
bookPatchServiceMock = {
|
||||
updateBookShelves: vi.fn(),
|
||||
updateLastReadTime: vi.fn(),
|
||||
savePdfProgress: vi.fn(),
|
||||
saveEpubProgress: vi.fn(),
|
||||
saveCbxProgress: vi.fn(),
|
||||
updateDateFinished: vi.fn(),
|
||||
resetProgress: vi.fn(),
|
||||
updateBookReadStatus: vi.fn(),
|
||||
resetPersonalRating: vi.fn(),
|
||||
updatePersonalRating: vi.fn()
|
||||
};
|
||||
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [
|
||||
{id: 1, bookType: 'PDF', shelves: [{id: 10}], metadata: {seriesName: 'S'}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file.pdf'},
|
||||
{id: 2, bookType: 'EPUB', shelves: [], metadata: {}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file2.epub'}
|
||||
],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
BookService,
|
||||
{provide: HttpClient, useValue: httpMock},
|
||||
{provide: MessageService, useValue: messageServiceMock},
|
||||
{provide: AuthService, useValue: authServiceMock},
|
||||
{provide: FileDownloadService, useValue: fileDownloadServiceMock},
|
||||
{provide: Router, useValue: routerMock},
|
||||
{provide: BookStateService, useValue: bookStateServiceMock},
|
||||
{provide: BookSocketService, useValue: bookSocketServiceMock},
|
||||
{provide: BookPatchService, useValue: bookPatchServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(BookService));
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
it('should get current book state', () => {
|
||||
expect(service.getCurrentBookState()).toEqual(bookStateServiceMock.getCurrentBookState());
|
||||
});
|
||||
|
||||
it('should fetch books and update state', async () => {
|
||||
const books = [{id: 1}];
|
||||
httpMock.get.mockReturnValue(of(books));
|
||||
await firstValueFrom(service['fetchBooks']());
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books,
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle fetchBooks error', async () => {
|
||||
httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: false, error: null});
|
||||
await expect(firstValueFrom(service['fetchBooks']())).rejects.toBeTruthy();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: [],
|
||||
loaded: true,
|
||||
error: 'fail'
|
||||
});
|
||||
});
|
||||
|
||||
it('should refreshBooks and update state', () => {
|
||||
httpMock.get.mockReturnValue(of([{id: 1}]));
|
||||
service.refreshBooks();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: [{id: 1}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle refreshBooks error', () => {
|
||||
httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
service.refreshBooks();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: null,
|
||||
loaded: true,
|
||||
error: 'fail'
|
||||
});
|
||||
});
|
||||
|
||||
it('should remove books by library id', () => {
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, libraryId: 2}, {id: 2, libraryId: 3}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
service.removeBooksByLibraryId(2);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
|
||||
books: [{id: 2, libraryId: 3}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
});
|
||||
|
||||
it('should remove books from shelf', () => {
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, shelves: [{id: 10}, {id: 20}]}, {id: 2, shelves: [{id: 20}]}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
service.removeBooksFromShelf(20);
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Book Retrieval', () => {
|
||||
it('should get book by id from state', () => {
|
||||
expect(service.getBookByIdFromState(1)).toEqual(expect.objectContaining({id: 1}));
|
||||
expect(service.getBookByIdFromState(999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get books by ids from state', () => {
|
||||
expect(service.getBooksByIdsFromState([1, 2])).toHaveLength(2);
|
||||
expect(service.getBooksByIdsFromState([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('should get book by id from API', async () => {
|
||||
httpMock.get.mockReturnValue(of({id: 1}));
|
||||
const result = await firstValueFrom(service.getBookByIdFromAPI(1, true));
|
||||
expect(result).toEqual({id: 1});
|
||||
});
|
||||
|
||||
it('should get books in series', async () => {
|
||||
const result = await firstValueFrom(service.getBooksInSeries(1));
|
||||
expect(result).toEqual([expect.objectContaining({id: 1})]);
|
||||
});
|
||||
|
||||
it('should get book recommendations', async () => {
|
||||
httpMock.get.mockReturnValue(of([{id: 1}]));
|
||||
const result = await firstValueFrom(service.getBookRecommendations(1));
|
||||
expect(result).toEqual([{id: 1}]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Book Operations', () => {
|
||||
it('should delete books and update state', async () => {
|
||||
httpMock.delete.mockReturnValue(of({failedFileDeletions: []}));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1}, {id: 2}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
await firstValueFrom(service.deleteBooks(new Set([1])));
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('should show warning if some files could not be deleted', async () => {
|
||||
httpMock.delete.mockReturnValue(of({failedFileDeletions: ['file.pdf']}));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, fileName: 'file.pdf'}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
await firstValueFrom(service.deleteBooks(new Set([1])));
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'warn'}));
|
||||
});
|
||||
|
||||
it('should handle deleteBooks error', async () => {
|
||||
httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||
await expect(firstValueFrom(service.deleteBooks(new Set([1])))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should update book shelves', async () => {
|
||||
bookPatchServiceMock.updateBookShelves.mockReturnValue(of([{id: 1}]));
|
||||
const result = await firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])));
|
||||
expect(result).toEqual([{id: 1}]);
|
||||
});
|
||||
|
||||
it('should handle updateBookShelves error', async () => {
|
||||
bookPatchServiceMock.updateBookShelves.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
await expect(firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])))).rejects.toBeTruthy();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Reading & Viewer Settings', () => {
|
||||
it('should navigate to correct reader and update last read time', () => {
|
||||
service.readBook(1);
|
||||
expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1'], undefined);
|
||||
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should not navigate if book not found', () => {
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null});
|
||||
service.readBook(999);
|
||||
expect(routerMock.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should get book setting', async () => {
|
||||
httpMock.get.mockReturnValue(of({fontSize: 12}));
|
||||
const result = await firstValueFrom(service.getBookSetting(1));
|
||||
expect(result).toEqual({fontSize: 12});
|
||||
});
|
||||
|
||||
it('should update viewer setting', async () => {
|
||||
httpMock.put.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.updateViewerSetting({fontSize: 12}, 1));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('File Operations', () => {
|
||||
it('should get file content', async () => {
|
||||
httpMock.get.mockReturnValue(of(new Blob(['abc'])));
|
||||
const result = await firstValueFrom(service.getFileContent(1));
|
||||
expect(result).toBeInstanceOf(Blob);
|
||||
});
|
||||
|
||||
it('should download file', () => {
|
||||
const book = {id: 1, fileName: 'file.pdf'};
|
||||
service.downloadFile(book as Book);
|
||||
expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should delete additional file and update state', async () => {
|
||||
httpMock.delete.mockReturnValue(of(void 0));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, alternativeFormats: [{id: 2}], supplementaryFiles: [{id: 3}]}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
await firstValueFrom(service.deleteAdditionalFile(1, 2));
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('should handle deleteAdditionalFile error', async () => {
|
||||
httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||
await expect(firstValueFrom(service.deleteAdditionalFile(1, 2))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should upload additional file and update state', async () => {
|
||||
httpMock.post.mockReturnValue(of({id: 2}));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, alternativeFormats: [], supplementaryFiles: []}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
const file = new File(['abc'], 'file.txt');
|
||||
await firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT));
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
|
||||
});
|
||||
|
||||
it('should handle uploadAdditionalFile error', async () => {
|
||||
httpMock.post.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
|
||||
const file = new File(['abc'], 'file.txt');
|
||||
await expect(firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should download additional file', () => {
|
||||
const book = {id: 1, alternativeFormats: [{id: 2, fileName: 'f.txt'}]};
|
||||
service.downloadAdditionalFile(book as Book, 2);
|
||||
expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Progress & Status Tracking', () => {
|
||||
it('should update last read time', () => {
|
||||
service.updateLastReadTime(1);
|
||||
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it('should save pdf progress', async () => {
|
||||
bookPatchServiceMock.savePdfProgress.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.savePdfProgress(1, 2, 0.5));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should save cbx progress', async () => {
|
||||
bookPatchServiceMock.saveCbxProgress.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.saveCbxProgress(1, 2, 0.5));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should update date finished', async () => {
|
||||
bookPatchServiceMock.updateDateFinished.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.updateDateFinished(1, '2020-01-01'));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should reset progress', async () => {
|
||||
bookPatchServiceMock.resetProgress.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]));
|
||||
const result = await firstValueFrom(service.resetProgress([1], 'BOOKLORE'));
|
||||
expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]);
|
||||
});
|
||||
|
||||
it('should update book read status', async () => {
|
||||
bookPatchServiceMock.updateBookReadStatus.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]));
|
||||
const result = await firstValueFrom(service.updateBookReadStatus([1], ReadStatus.READ));
|
||||
expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Personal Rating', () => {
|
||||
it('should reset personal rating', async () => {
|
||||
bookPatchServiceMock.resetPersonalRating.mockReturnValue(of([{bookId: 1}]));
|
||||
const result = await firstValueFrom(service.resetPersonalRating([1]));
|
||||
expect(result).toEqual([{bookId: 1}]);
|
||||
});
|
||||
|
||||
it('should update personal rating', async () => {
|
||||
bookPatchServiceMock.updatePersonalRating.mockReturnValue(of([{bookId: 1, personalRating: 5}]));
|
||||
const result = await firstValueFrom(service.updatePersonalRating([1], 5));
|
||||
expect(result).toEqual([{bookId: 1, personalRating: 5}]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Metadata Operations', () => {
|
||||
|
||||
it('should update book metadata', async () => {
|
||||
httpMock.put.mockReturnValue(of({bookId: 1}));
|
||||
const spy = vi.spyOn(BookService.prototype, 'handleBookMetadataUpdate');
|
||||
const result = await firstValueFrom(service.updateBookMetadata(1, {} as any, true));
|
||||
expect(result).toEqual({bookId: 1});
|
||||
expect(spy).toHaveBeenCalledWith(1, {bookId: 1});
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should update books metadata', async () => {
|
||||
httpMock.put.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.updateBooksMetadata({} as any));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should toggle all lock', async () => {
|
||||
httpMock.put.mockReturnValue(of([{bookId: 1}]));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, metadata: {bookId: 1}}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
const result = await firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'));
|
||||
expect(result).toBeUndefined();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle toggle all lock error', async () => {
|
||||
httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
await expect(firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'))).rejects.toBeTruthy();
|
||||
});
|
||||
|
||||
it('should toggle field locks', async () => {
|
||||
httpMock.put.mockReturnValue(of(void 0));
|
||||
bookStateServiceMock.getCurrentBookState.mockReturnValue({
|
||||
books: [{id: 1, metadata: {}}],
|
||||
loaded: true,
|
||||
error: null
|
||||
});
|
||||
const result = await firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}));
|
||||
expect(result).toBeUndefined();
|
||||
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle toggle field locks error', async () => {
|
||||
httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'})));
|
||||
await expect(firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}))).rejects.toBeTruthy();
|
||||
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
|
||||
});
|
||||
|
||||
it('should consolidate metadata', async () => {
|
||||
httpMock.post.mockReturnValue(of({}));
|
||||
service.refreshBooks = vi.fn();
|
||||
await firstValueFrom(service.consolidateMetadata('authors', ['a'], ['b']));
|
||||
expect(service.refreshBooks).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should delete metadata', async () => {
|
||||
httpMock.post.mockReturnValue(of({}));
|
||||
service.refreshBooks = vi.fn();
|
||||
await firstValueFrom(service.deleteMetadata('authors', ['a']));
|
||||
expect(service.refreshBooks).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Cover Operations', () => {
|
||||
it('should get upload cover url', () => {
|
||||
expect(service.getUploadCoverUrl(1)).toContain('/1/metadata/cover/upload');
|
||||
});
|
||||
|
||||
it('should regenerate covers', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.regenerateCovers());
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should regenerate cover', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.regenerateCover(1));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should generate custom cover', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.generateCustomCover(1));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should regenerate covers for books', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const result = await firstValueFrom(service.regenerateCoversForBooks([1, 2]));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should bulk upload cover', async () => {
|
||||
httpMock.post.mockReturnValue(of(void 0));
|
||||
const file = new File(['abc'], 'cover.jpg');
|
||||
const result = await firstValueFrom(service.bulkUploadCover([1, 2], file));
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Websocket Handlers', () => {
|
||||
it('should handle newly created book', () => {
|
||||
const book = {id: 1};
|
||||
service.handleNewlyCreatedBook(book as Book);
|
||||
expect(bookSocketServiceMock.handleNewlyCreatedBook).toHaveBeenCalledWith(book);
|
||||
});
|
||||
|
||||
it('should handle removed book ids', () => {
|
||||
service.handleRemovedBookIds([1, 2]);
|
||||
expect(bookSocketServiceMock.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]);
|
||||
});
|
||||
|
||||
it('should handle book update', () => {
|
||||
const book = {id: 1};
|
||||
service.handleBookUpdate(book as Book);
|
||||
expect(bookSocketServiceMock.handleBookUpdate).toHaveBeenCalledWith(book);
|
||||
});
|
||||
|
||||
it('should handle multiple book updates', () => {
|
||||
const books = [{id: 1}, {id: 2}];
|
||||
service.handleMultipleBookUpdates(books as Book[]);
|
||||
expect(bookSocketServiceMock.handleMultipleBookUpdates).toHaveBeenCalledWith(books);
|
||||
});
|
||||
|
||||
it('should handle book metadata update', () => {
|
||||
service.handleBookMetadataUpdate(1, {bookId: 1} as BookMetadata);
|
||||
expect(bookSocketServiceMock.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1});
|
||||
});
|
||||
|
||||
it('should handle multiple book cover patches', () => {
|
||||
const patches = [{id: 1, coverUpdatedOn: 'now'}];
|
||||
service.handleMultipleBookCoverPatches(patches);
|
||||
expect(bookSocketServiceMock.handleMultipleBookCoverPatches).toHaveBeenCalledWith(patches);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
|
||||
import {first, Observable, of, throwError} from 'rxjs';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, tap} from 'rxjs/operators';
|
||||
import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
|
||||
import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BookType, BulkMetadataUpdateRequest, CreatePhysicalBookRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
|
||||
import {BookState} from '../model/state/book-state.model';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MessageService} from 'primeng/api';
|
||||
@@ -242,9 +242,35 @@ export class BookService {
|
||||
);
|
||||
}
|
||||
|
||||
createPhysicalBook(request: CreatePhysicalBookRequest): Observable<Book> {
|
||||
return this.http.post<Book>(`${this.url}/physical`, request).pipe(
|
||||
tap(newBook => {
|
||||
const currentState = this.bookStateService.getCurrentBookState();
|
||||
const updatedBooks = [...(currentState.books || []), newBook];
|
||||
this.bookStateService.updateBookState({
|
||||
...currentState,
|
||||
books: updatedBooks
|
||||
});
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Physical Book Created',
|
||||
detail: `"${newBook.metadata?.title || 'Book'}" has been added to your library.`
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Creation Failed',
|
||||
detail: error?.error?.message || error?.message || 'An error occurred while creating the physical book.'
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/*------------------ Reading & Viewer Settings ------------------*/
|
||||
|
||||
readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming'): void {
|
||||
readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming', explicitBookType?: BookType): void {
|
||||
const book = this.bookStateService
|
||||
.getCurrentBookState()
|
||||
.books?.find(b => b.id === bookId);
|
||||
@@ -254,10 +280,14 @@ export class BookService {
|
||||
return;
|
||||
}
|
||||
|
||||
let baseUrl: string | null = null;
|
||||
let queryParams: Record<string, any> | undefined;
|
||||
// Determine the book type - use explicit type if provided, otherwise use primary
|
||||
const bookType: BookType | undefined = explicitBookType ?? book.primaryFile?.bookType;
|
||||
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;
|
||||
|
||||
switch (book.bookType) {
|
||||
let baseUrl: string | null = null;
|
||||
let queryParams: Record<string, any> = {};
|
||||
|
||||
switch (bookType) {
|
||||
case 'PDF':
|
||||
baseUrl = reader === 'pdf-streaming' ? 'cbx-reader' : 'pdf-reader';
|
||||
break;
|
||||
@@ -265,7 +295,7 @@ export class BookService {
|
||||
case 'EPUB':
|
||||
baseUrl = 'ebook-reader';
|
||||
if (reader === 'epub-streaming') {
|
||||
queryParams = { streaming: true };
|
||||
queryParams['streaming'] = true;
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -278,20 +308,30 @@ export class BookService {
|
||||
case 'CBX':
|
||||
baseUrl = 'cbx-reader';
|
||||
break;
|
||||
|
||||
case 'AUDIOBOOK':
|
||||
baseUrl = 'audiobook-reader';
|
||||
break;
|
||||
}
|
||||
|
||||
if (!baseUrl) {
|
||||
console.error('Unsupported book type:', book.bookType);
|
||||
console.error('Unsupported book type:', bookType);
|
||||
return;
|
||||
}
|
||||
|
||||
this.router.navigate([`/${baseUrl}/book/${book.id}`], queryParams ? { queryParams } : undefined);
|
||||
// Add bookType to query params if reading an alternative format
|
||||
if (isAlternativeFormat) {
|
||||
queryParams['bookType'] = bookType;
|
||||
}
|
||||
|
||||
const hasQueryParams = Object.keys(queryParams).length > 0;
|
||||
this.router.navigate([`/${baseUrl}/book/${book.id}`], hasQueryParams ? { queryParams } : undefined);
|
||||
|
||||
this.updateLastReadTime(book.id);
|
||||
}
|
||||
|
||||
getBookSetting(bookId: number): Observable<BookSetting> {
|
||||
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`);
|
||||
getBookSetting(bookId: number, bookFileId: number): Observable<BookSetting> {
|
||||
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting?bookFileId=${bookFileId}`);
|
||||
}
|
||||
|
||||
updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
|
||||
@@ -300,13 +340,25 @@ export class BookService {
|
||||
|
||||
/*------------------ File Operations ------------------*/
|
||||
|
||||
getFileContent(bookId: number): Observable<Blob> {
|
||||
return this.http.get<Blob>(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'});
|
||||
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
|
||||
let url = `${this.url}/${bookId}/content`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<Blob>(url, {responseType: 'blob' as 'json'});
|
||||
}
|
||||
|
||||
downloadFile(book: Book): void {
|
||||
const downloadUrl = `${this.url}/${book.id}/download`;
|
||||
this.fileDownloadService.downloadFile(downloadUrl, book.fileName!);
|
||||
this.fileDownloadService.downloadFile(downloadUrl, book.primaryFile?.fileName ?? 'book');
|
||||
}
|
||||
|
||||
downloadAllFiles(book: Book): void {
|
||||
const downloadUrl = `${this.url}/${book.id}/download-all`;
|
||||
const fileName = book.metadata?.title
|
||||
? `${book.metadata.title.replace(/[^a-zA-Z0-9\-_]/g, '_')}.zip`
|
||||
: `book-${book.id}.zip`;
|
||||
this.fileDownloadService.downloadFile(downloadUrl, fileName);
|
||||
}
|
||||
|
||||
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
|
||||
@@ -347,6 +399,63 @@ export class BookService {
|
||||
);
|
||||
}
|
||||
|
||||
deleteBookFile(bookId: number, fileId: number, isPrimary: boolean): Observable<void> {
|
||||
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
|
||||
return this.http.delete<void>(deleteUrl).pipe(
|
||||
tap(() => {
|
||||
const currentState = this.bookStateService.getCurrentBookState();
|
||||
const updatedBooks = (currentState.books || []).map(book => {
|
||||
if (book.id === bookId) {
|
||||
if (isPrimary) {
|
||||
// Primary file was deleted - promote first alternative to primary, or set null
|
||||
const remainingAlternatives = book.alternativeFormats?.filter(file => file.id !== fileId) || [];
|
||||
if (remainingAlternatives.length > 0) {
|
||||
const [newPrimary, ...restAlternatives] = remainingAlternatives;
|
||||
return {
|
||||
...book,
|
||||
primaryFile: newPrimary,
|
||||
alternativeFormats: restAlternatives
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
...book,
|
||||
primaryFile: undefined,
|
||||
alternativeFormats: []
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// Alternative file was deleted
|
||||
return {
|
||||
...book,
|
||||
alternativeFormats: book.alternativeFormats?.filter(file => file.id !== fileId)
|
||||
};
|
||||
}
|
||||
}
|
||||
return book;
|
||||
});
|
||||
|
||||
this.bookStateService.updateBookState({
|
||||
...currentState,
|
||||
books: updatedBooks
|
||||
});
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'File Deleted',
|
||||
detail: 'Book file deleted successfully.'
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Delete Failed',
|
||||
detail: error?.error?.message || error?.message || 'An error occurred while deleting the file.'
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
uploadAdditionalFile(bookId: number, file: File, fileType: AdditionalFileType, description?: string): Observable<AdditionalFile> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
@@ -363,7 +472,9 @@ export class BookService {
|
||||
? 'EPUB'
|
||||
: (ext === 'cbz' || ext === 'cbr' || ext === 'cb7' || ext === 'cbt')
|
||||
? 'CBX'
|
||||
: null;
|
||||
: (ext === 'm4b' || ext === 'm4a' || ext === 'mp3')
|
||||
? 'AUDIOBOOK'
|
||||
: null;
|
||||
|
||||
if (bookType) {
|
||||
formData.append('bookType', bookType);
|
||||
@@ -426,16 +537,16 @@ export class BookService {
|
||||
this.bookPatchService.updateLastReadTime(bookId);
|
||||
}
|
||||
|
||||
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
return this.bookPatchService.savePdfProgress(bookId, page, percentage);
|
||||
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||
return this.bookPatchService.savePdfProgress(bookId, page, percentage, bookFileId);
|
||||
}
|
||||
|
||||
/*saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): Observable<void> {
|
||||
return this.bookPatchService.saveEpubProgress(bookId, cfi, href, percentage);
|
||||
}*/
|
||||
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
return this.bookPatchService.saveCbxProgress(bookId, page, percentage);
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||
return this.bookPatchService.saveCbxProgress(bookId, page, percentage, bookFileId);
|
||||
}
|
||||
|
||||
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
|
||||
@@ -621,4 +732,46 @@ export class BookService {
|
||||
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
||||
this.bookSocketService.handleMultipleBookCoverPatches(patches);
|
||||
}
|
||||
|
||||
/*------------------ Book File Attachment ------------------*/
|
||||
|
||||
attachBookFiles(targetBookId: number, sourceBookIds: number[], deleteSourceBooks: boolean): Observable<Book> {
|
||||
return this.http.post<Book>(`${this.url}/${targetBookId}/attach-file`, {
|
||||
sourceBookIds,
|
||||
deleteSourceBooks
|
||||
}).pipe(
|
||||
tap(updatedBook => {
|
||||
const currentState = this.bookStateService.getCurrentBookState();
|
||||
let updatedBooks = (currentState.books || []).map(book =>
|
||||
book.id === targetBookId ? updatedBook : book
|
||||
);
|
||||
|
||||
// If deleteSourceBooks, remove source books from state
|
||||
if (deleteSourceBooks) {
|
||||
const sourceIdSet = new Set(sourceBookIds);
|
||||
updatedBooks = updatedBooks.filter(book => !sourceIdSet.has(book.id));
|
||||
}
|
||||
|
||||
this.bookStateService.updateBookState({
|
||||
...currentState,
|
||||
books: updatedBooks
|
||||
});
|
||||
|
||||
const fileCount = sourceBookIds.length;
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Files Attached',
|
||||
detail: `${fileCount} book file${fileCount > 1 ? 's have' : ' has'} been attached successfully.`
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Attachment Failed',
|
||||
detail: error?.error?.message || error?.message || 'An error occurred while attaching the files.'
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,96 +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 {CbxReaderService} from './cbx-reader.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
describe('CbxReaderService', () => {
|
||||
let service: CbxReaderService;
|
||||
let httpClientMock: any;
|
||||
let authServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn()
|
||||
};
|
||||
|
||||
authServiceMock = {
|
||||
getOidcAccessToken: vi.fn(),
|
||||
getInternalAccessToken: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
CbxReaderService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: AuthService, useValue: authServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(CbxReaderService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should get available pages with token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('abc123');
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
httpClientMock.get.mockReturnValue(of([1, 2, 3]));
|
||||
service.getAvailablePages(42).subscribe(pages => {
|
||||
expect(pages).toEqual([1, 2, 3]);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('token=abc123'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should get available pages without token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
httpClientMock.get.mockReturnValue(of([4, 5]));
|
||||
service.getAvailablePages(99).subscribe(pages => {
|
||||
expect(pages).toEqual([4, 5]);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.not.stringContaining('token='));
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle error when getting available pages', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.getAvailablePages(1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should return correct page image url with oidc token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
const url = service.getPageImageUrl(5, 7);
|
||||
expect(url).toContain('/api/v1/media/book/5/cbx/pages/7');
|
||||
expect(url).toContain('token=tok');
|
||||
});
|
||||
|
||||
it('should return correct page image url with internal token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue('inttok');
|
||||
const url = service.getPageImageUrl(8, 2);
|
||||
expect(url).toContain('/api/v1/media/book/8/cbx/pages/2');
|
||||
expect(url).toContain('token=inttok');
|
||||
});
|
||||
|
||||
it('should return correct page image url without token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
const url = service.getPageImageUrl(3, 1);
|
||||
expect(url).toContain('/api/v1/media/book/3/cbx/pages/1');
|
||||
expect(url).not.toContain('token=');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,15 +25,27 @@ export class CbxReaderService {
|
||||
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
|
||||
}
|
||||
|
||||
getAvailablePages(bookId: number) {
|
||||
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
|
||||
getAvailablePages(bookId: number, bookType?: string) {
|
||||
let url = `${this.pagesUrl}/${bookId}/pages`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<number[]>(this.appendToken(url));
|
||||
}
|
||||
|
||||
getPageInfo(bookId: number) {
|
||||
return this.http.get<CbxPageInfo[]>(this.appendToken(`${this.pagesUrl}/${bookId}/page-info`));
|
||||
getPageInfo(bookId: number, bookType?: string) {
|
||||
let url = `${this.pagesUrl}/${bookId}/page-info`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<CbxPageInfo[]>(this.appendToken(url));
|
||||
}
|
||||
|
||||
getPageImageUrl(bookId: number, page: number): string {
|
||||
return this.appendToken(`${this.imageUrl}/${bookId}/cbx/pages/${page}`);
|
||||
getPageImageUrl(bookId: number, page: number, bookType?: string): string {
|
||||
let url = `${this.imageUrl}/${bookId}/cbx/pages/${page}`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,350 +0,0 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {Router} from '@angular/router';
|
||||
import {LibraryService} from './library.service';
|
||||
import {ShelfService} from './shelf.service';
|
||||
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
|
||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||
import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {UserService} from "../../settings/user-management/user.service";
|
||||
import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {LibraryShelfMenuService} from './library-shelf-menu.service';
|
||||
import {Library} from '../model/library.model';
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
describe('LibraryShelfMenuService', () => {
|
||||
let service: LibraryShelfMenuService;
|
||||
let confirmationService: any;
|
||||
let messageService: any;
|
||||
let libraryService: any;
|
||||
let shelfService: any;
|
||||
let taskHelperService: any;
|
||||
let router: any;
|
||||
let dialogLauncherService: any;
|
||||
let magicShelfService: any;
|
||||
let userService: any;
|
||||
let loadingService: any;
|
||||
|
||||
const mockLibrary: Library = {id: 1, name: 'Lib1'} as Library;
|
||||
const mockShelf: Shelf = {id: 2, name: 'Shelf1'} as Shelf;
|
||||
const mockMagicShelf: MagicShelf = {id: 3, name: 'Magic1', isPublic: false} as MagicShelf;
|
||||
|
||||
beforeEach(() => {
|
||||
confirmationService = {confirm: vi.fn()};
|
||||
messageService = {add: vi.fn()};
|
||||
libraryService = {
|
||||
refreshLibrary: vi.fn(),
|
||||
deleteLibrary: vi.fn()
|
||||
};
|
||||
shelfService = {
|
||||
deleteShelf: vi.fn()
|
||||
};
|
||||
taskHelperService = {
|
||||
refreshMetadataTask: vi.fn()
|
||||
};
|
||||
router = {navigate: vi.fn()};
|
||||
dialogLauncherService = {
|
||||
openLibraryEditDialog: vi.fn(),
|
||||
openLibraryMetadataFetchDialog: vi.fn(),
|
||||
openShelfEditDialog: vi.fn(),
|
||||
openMagicShelfEditDialog: vi.fn()
|
||||
};
|
||||
magicShelfService = {
|
||||
deleteShelf: vi.fn()
|
||||
};
|
||||
userService = {
|
||||
getCurrentUser: vi.fn()
|
||||
};
|
||||
loadingService = {
|
||||
show: vi.fn().mockReturnValue('loader-id'),
|
||||
hide: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
LibraryShelfMenuService,
|
||||
{provide: ConfirmationService, useValue: confirmationService},
|
||||
{provide: MessageService, useValue: messageService},
|
||||
{provide: LibraryService, useValue: libraryService},
|
||||
{provide: ShelfService, useValue: shelfService},
|
||||
{provide: TaskHelperService, useValue: taskHelperService},
|
||||
{provide: Router, useValue: router},
|
||||
{provide: DialogLauncherService, useValue: dialogLauncherService},
|
||||
{provide: MagicShelfService, useValue: magicShelfService},
|
||||
{provide: UserService, useValue: userService},
|
||||
{provide: LoadingService, useValue: loadingService}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(LibraryShelfMenuService));
|
||||
});
|
||||
|
||||
describe('initializeLibraryMenuItems', () => {
|
||||
it('should provide all menu items for a library', () => {
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
expect(items.length).toBe(1);
|
||||
const options = items[0].items!;
|
||||
expect(options.some(i => i.label === 'Edit Library')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Re-scan Library')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Custom Fetch Metadata')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Auto Fetch Metadata')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Delete Library')).toBe(true);
|
||||
});
|
||||
|
||||
it('should call openLibraryEditDialog when Edit Library is clicked', () => {
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Library');
|
||||
edit!.command!({});
|
||||
expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(mockLibrary.id);
|
||||
});
|
||||
|
||||
it('should call openLibraryMetadataFetchDialog when Custom Fetch Metadata is clicked', () => {
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const fetch = items[0].items!.find(i => i.label === 'Custom Fetch Metadata');
|
||||
fetch!.command!({});
|
||||
expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(mockLibrary.id);
|
||||
});
|
||||
|
||||
it('should call refreshMetadataTask when Auto Fetch Metadata is clicked', () => {
|
||||
taskHelperService.refreshMetadataTask.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const auto = items[0].items!.find(i => i.label === 'Auto Fetch Metadata');
|
||||
auto!.command!({});
|
||||
expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({
|
||||
refreshType: MetadataRefreshType.LIBRARY,
|
||||
libraryId: mockLibrary.id
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Re-scan Library', () => {
|
||||
libraryService.refreshLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
|
||||
rescan!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockLibrary.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should refresh library and show success message on accept', () => {
|
||||
libraryService.refreshLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
|
||||
rescan!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(libraryService.refreshLibrary).toHaveBeenCalledWith(mockLibrary.id);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Library refresh scheduled'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message if refreshLibrary fails', () => {
|
||||
libraryService.refreshLibrary.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
|
||||
rescan!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to refresh library'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Delete Library', () => {
|
||||
libraryService.deleteLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Library');
|
||||
del!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockLibrary.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should delete library, navigate, and show success message on accept', () => {
|
||||
libraryService.deleteLibrary.mockReturnValue(of({}));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Library');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(loadingService.show).toHaveBeenCalledWith(expect.stringContaining(mockLibrary.name));
|
||||
expect(libraryService.deleteLibrary).toHaveBeenCalledWith(mockLibrary.id);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Library was deleted'
|
||||
});
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
});
|
||||
|
||||
it('should show error message if deleteLibrary fails', () => {
|
||||
libraryService.deleteLibrary.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeLibraryMenuItems(mockLibrary);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Library');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete library'
|
||||
});
|
||||
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeShelfMenuItems', () => {
|
||||
it('should provide all menu items for a shelf', () => {
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
expect(items.length).toBe(1);
|
||||
const options = items[0].items!;
|
||||
expect(options.some(i => i.label === 'Edit Shelf')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Delete Shelf')).toBe(true);
|
||||
});
|
||||
|
||||
it('should call openShelfEditDialog when Edit Shelf is clicked', () => {
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Shelf');
|
||||
edit!.command!({});
|
||||
expect(dialogLauncherService.openShelfEditDialog).toHaveBeenCalledWith(mockShelf.id);
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Delete Shelf', () => {
|
||||
shelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
|
||||
del!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockShelf.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should delete shelf, navigate, and show success message on accept', () => {
|
||||
shelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(shelfService.deleteShelf).toHaveBeenCalledWith(mockShelf.id);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Shelf was deleted'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message if deleteShelf fails', () => {
|
||||
shelfService.deleteShelf.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeShelfMenuItems(mockShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete shelf'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeMagicShelfMenuItems', () => {
|
||||
it('should provide all menu items for a magic shelf', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
expect(items.length).toBe(1);
|
||||
const options = items[0].items!;
|
||||
expect(options.some(i => i.label === 'Edit Magic Shelf')).toBe(true);
|
||||
expect(options.some(i => i.label === 'Delete Magic Shelf')).toBe(true);
|
||||
});
|
||||
|
||||
it('should call openMagicShelfEditDialog when Edit Magic Shelf is clicked', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
|
||||
edit!.command!({});
|
||||
expect(dialogLauncherService.openMagicShelfEditDialog).toHaveBeenCalledWith(mockMagicShelf.id);
|
||||
});
|
||||
|
||||
it('should show confirmation dialog for Delete Magic Shelf', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
magicShelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
del!.command!({});
|
||||
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
expect(confirmCall.message).toContain(mockMagicShelf.name);
|
||||
expect(confirmCall.header).toBe('Confirmation');
|
||||
});
|
||||
|
||||
it('should delete magic shelf, navigate, and show success message on accept', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
magicShelfService.deleteShelf.mockReturnValue(of({}));
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(magicShelfService.deleteShelf).toHaveBeenCalledWith(mockMagicShelf.id);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/']);
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'info',
|
||||
summary: 'Success',
|
||||
detail: 'Magic shelf was deleted'
|
||||
});
|
||||
});
|
||||
|
||||
it('should show error message if deleteMagicShelf fails', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
magicShelfService.deleteShelf.mockReturnValue(throwError(() => ({})));
|
||||
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
del!.command!({});
|
||||
const confirmCall = confirmationService.confirm.mock.calls[0][0];
|
||||
confirmCall.accept();
|
||||
expect(messageService.add).toHaveBeenCalledWith({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to delete shelf'
|
||||
});
|
||||
});
|
||||
|
||||
it('should disable options for public shelf if not admin', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: false}});
|
||||
const publicMagicShelf = {...mockMagicShelf, isPublic: true};
|
||||
const items = service.initializeMagicShelfMenuItems(publicMagicShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
expect(edit!.disabled).toBe(true);
|
||||
expect(del!.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it('should not disable options for public shelf if admin', () => {
|
||||
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
|
||||
const publicMagicShelf = {...mockMagicShelf, isPublic: true};
|
||||
const items = service.initializeMagicShelfMenuItems(publicMagicShelf);
|
||||
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
|
||||
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
|
||||
expect(edit!.disabled).toBe(false);
|
||||
expect(del!.disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import {UserService} from "../../settings/user-management/user.service";
|
||||
import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {finalize} from 'rxjs';
|
||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -28,12 +29,23 @@ export class LibraryShelfMenuService {
|
||||
private magicShelfService = inject(MagicShelfService);
|
||||
private userService = inject(UserService);
|
||||
private loadingService = inject(LoadingService);
|
||||
private bookDialogHelperService = inject(BookDialogHelperService);
|
||||
|
||||
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
label: 'Options',
|
||||
items: [
|
||||
{
|
||||
label: 'Add Physical Book',
|
||||
icon: 'pi pi-book',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number);
|
||||
}
|
||||
},
|
||||
{
|
||||
separator: true
|
||||
},
|
||||
{
|
||||
label: 'Edit Library',
|
||||
icon: 'pi pi-pen-to-square',
|
||||
|
||||
@@ -1,167 +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 {firstValueFrom, of, throwError} from 'rxjs';
|
||||
|
||||
import {LibraryService} from './library.service';
|
||||
import {BookService} from './book.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {Library} from '../model/library.model';
|
||||
|
||||
describe('LibraryService', () => {
|
||||
let service: LibraryService;
|
||||
let httpClientMock: any;
|
||||
let bookServiceMock: any;
|
||||
let authServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
|
||||
bookServiceMock = {
|
||||
removeBooksByLibraryId: vi.fn(),
|
||||
bookState$: of({
|
||||
books: [
|
||||
{id: 1, libraryId: 10},
|
||||
{id: 2, libraryId: 20},
|
||||
{id: 3, libraryId: 10},
|
||||
{id: 4}
|
||||
]
|
||||
})
|
||||
};
|
||||
|
||||
authServiceMock = {
|
||||
token$: of('token')
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
LibraryService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: BookService, useValue: bookServiceMock},
|
||||
{provide: AuthService, useValue: authServiceMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(LibraryService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should fetch libraries and update state', () => {
|
||||
const libraries: Library[] = [{id: 1, name: 'LibA', icon: 'icon', watch: true, paths: []}];
|
||||
httpClientMock.get.mockReturnValue(of(libraries));
|
||||
service['fetchLibraries']().subscribe(result => {
|
||||
expect(result).toEqual(libraries);
|
||||
expect(service['libraryStateSubject'].value.libraries).toEqual(libraries);
|
||||
expect(service['libraryStateSubject'].value.loaded).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle fetch libraries error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service['libraryStateSubject'].next({libraries: null, loaded: false, error: null});
|
||||
service['fetchLibraries']().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(service['libraryStateSubject'].value.error).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should create a library and update state', () => {
|
||||
const library: Library = {id: 2, name: 'LibB', icon: 'icon', watch: true, paths: []};
|
||||
httpClientMock.post.mockReturnValue(of(library));
|
||||
service['libraryStateSubject'].next({libraries: [], loaded: true, error: null});
|
||||
service.createLibrary(library).subscribe(result => {
|
||||
expect(result).toEqual(library);
|
||||
expect(service['libraryStateSubject'].value.libraries).toContain(library);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update a library and update state', () => {
|
||||
const library: Library = {id: 3, name: 'LibC', icon: 'icon', watch: true, paths: []};
|
||||
httpClientMock.put.mockReturnValue(of({...library, name: 'LibC2'}));
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
service.updateLibrary({...library, name: 'LibC2'}, 3).subscribe(result => {
|
||||
expect(result.name).toBe('LibC2');
|
||||
expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 3)?.name).toBe('LibC2');
|
||||
});
|
||||
});
|
||||
|
||||
it('should delete a library and update state', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
const library: Library = {id: 4, name: 'LibD', icon: 'icon', watch: true, paths: []};
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
service.deleteLibrary(4).subscribe(() => {
|
||||
expect(service['libraryStateSubject'].value.libraries).toEqual([]);
|
||||
expect(bookServiceMock.removeBooksByLibraryId).toHaveBeenCalledWith(4);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle delete library error', () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
|
||||
service['libraryStateSubject'].next({libraries: [{id: 5, name: 'LibE', icon: 'icon', watch: true, paths: []}], loaded: true, error: null});
|
||||
service.deleteLibrary(5).subscribe({
|
||||
error: () => {
|
||||
expect(service['libraryStateSubject'].value.error).toBe('delete error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should refresh a library and handle error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('refresh error')));
|
||||
service['libraryStateSubject'].next({libraries: [{id: 6, name: 'LibF', icon: 'icon', watch: true, paths: []}], loaded: true, error: null});
|
||||
service.refreshLibrary(6).subscribe({
|
||||
error: () => {
|
||||
expect(service['libraryStateSubject'].value.error).toBe('refresh error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should update library file naming pattern', () => {
|
||||
const library: Library = {id: 7, name: 'LibG', icon: 'icon', watch: true, paths: [], fileNamingPattern: 'old'};
|
||||
const updatedLibrary = {...library, fileNamingPattern: 'new'};
|
||||
httpClientMock.patch.mockReturnValue(of(updatedLibrary));
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
service.updateLibraryFileNamingPattern(7, 'new').subscribe(result => {
|
||||
expect(result.fileNamingPattern).toBe('new');
|
||||
expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 7)?.fileNamingPattern).toBe('new');
|
||||
});
|
||||
});
|
||||
|
||||
it('should check if library exists by name', () => {
|
||||
const library: Library = {id: 8, name: 'LibH', icon: 'icon', watch: true, paths: []};
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
expect(service.doesLibraryExistByName('LibH')).toBe(true);
|
||||
expect(service.doesLibraryExistByName('NonExistent')).toBe(false);
|
||||
});
|
||||
|
||||
it('should find library by id', () => {
|
||||
const library: Library = {id: 9, name: 'LibI', icon: 'icon', watch: true, paths: []};
|
||||
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
|
||||
expect(service.findLibraryById(9)).toEqual(library);
|
||||
expect(service.findLibraryById(999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get libraries from state', () => {
|
||||
const libraries: Library[] = [
|
||||
{id: 10, name: 'LibJ', icon: 'icon', watch: true, paths: []}
|
||||
];
|
||||
service['libraryStateSubject'].next({libraries, loaded: true, error: null});
|
||||
expect(service.getLibrariesFromState()).toEqual(libraries);
|
||||
});
|
||||
|
||||
it('should get book count for library', async () => {
|
||||
const count = await firstValueFrom(service.getBookCount(10));
|
||||
expect(count).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,123 +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 {firstValueFrom, of, throwError} from 'rxjs';
|
||||
|
||||
import {MetadataFetchTask, MetadataTaskService} from './metadata-task';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../../shared/model/metadata-batch-progress.model';
|
||||
|
||||
describe('MetadataTaskService', () => {
|
||||
let service: MetadataTaskService;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
post: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
MetadataTaskService,
|
||||
{ provide: HttpClient, useValue: httpClientMock }
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(MetadataTaskService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should get task with proposals', async () => {
|
||||
const task: MetadataFetchTask = {
|
||||
id: 'task1',
|
||||
status: 'IN_PROGRESS',
|
||||
completed: 1,
|
||||
totalBooks: 2,
|
||||
startedAt: '2024-01-01T00:00:00Z',
|
||||
completedAt: null,
|
||||
initiatedBy: 'user1',
|
||||
errorMessage: null,
|
||||
proposals: []
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of({ task }));
|
||||
const result = await firstValueFrom(service.getTaskWithProposals('task1'));
|
||||
expect(result).toEqual(task);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task1`);
|
||||
});
|
||||
|
||||
it('should handle error in getTaskWithProposals', async () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
try {
|
||||
await firstValueFrom(service.getTaskWithProposals('task2'));
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
|
||||
it('should delete a task', async () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
await firstValueFrom(service.deleteTask('task3'));
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task3`);
|
||||
});
|
||||
|
||||
it('should handle error in deleteTask', async () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
|
||||
try {
|
||||
await firstValueFrom(service.deleteTask('task4'));
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('delete error');
|
||||
}
|
||||
});
|
||||
|
||||
it('should update proposal status', async () => {
|
||||
httpClientMock.post.mockReturnValue(of(void 0));
|
||||
await firstValueFrom(service.updateProposalStatus('task5', 123, 'ACCEPTED'));
|
||||
expect(httpClientMock.post).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/metadata/tasks/task5/proposals/123/status`,
|
||||
null,
|
||||
{ params: { status: 'ACCEPTED' } }
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle error in updateProposalStatus', async () => {
|
||||
httpClientMock.post.mockReturnValue(throwError(() => new Error('status error')));
|
||||
try {
|
||||
await firstValueFrom(service.updateProposalStatus('task6', 456, 'REJECTED'));
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('status error');
|
||||
}
|
||||
});
|
||||
|
||||
it('should get active tasks', async () => {
|
||||
const notifications: MetadataBatchProgressNotification[] = [
|
||||
{
|
||||
taskId: 't1',
|
||||
completed: 1,
|
||||
total: 2,
|
||||
message: 'Running',
|
||||
status: MetadataBatchStatus.IN_PROGRESS,
|
||||
review: false
|
||||
}
|
||||
];
|
||||
httpClientMock.get.mockReturnValue(of(notifications));
|
||||
const result = await firstValueFrom(service.getActiveTasks());
|
||||
expect(result).toEqual(notifications);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/active`);
|
||||
});
|
||||
|
||||
it('should handle error in getActiveTasks', async () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('active error')));
|
||||
try {
|
||||
await firstValueFrom(service.getActiveTasks());
|
||||
} catch (e: any) {
|
||||
expect(e.message).toBe('active error');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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 {HttpClient} from '@angular/common/http';
|
||||
|
||||
import {NewPdfReaderService} from './new-pdf-reader.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
|
||||
describe('NewPdfReaderService', () => {
|
||||
let service: NewPdfReaderService;
|
||||
let authServiceMock: any;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
authServiceMock = {
|
||||
getOidcAccessToken: vi.fn(),
|
||||
getInternalAccessToken: vi.fn()
|
||||
};
|
||||
|
||||
httpClientMock = {
|
||||
get: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
NewPdfReaderService,
|
||||
{provide: AuthService, useValue: authServiceMock},
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(NewPdfReaderService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should append token from OIDC access token', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token');
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
|
||||
const url = 'http://test.com/resource';
|
||||
const result = (service as any).appendToken(url);
|
||||
|
||||
expect(result).toContain('token=oidc-token');
|
||||
});
|
||||
|
||||
it('should not append token if both tokens are null', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue(null);
|
||||
authServiceMock.getInternalAccessToken.mockReturnValue(null);
|
||||
|
||||
const url = 'http://test.com/resource';
|
||||
const result = (service as any).appendToken(url);
|
||||
|
||||
expect(result).toBe(url);
|
||||
});
|
||||
|
||||
it('should call http.get with correct URL', () => {
|
||||
authServiceMock.getOidcAccessToken.mockReturnValue('token123');
|
||||
|
||||
service.getAvailablePages(42);
|
||||
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(
|
||||
`${API_CONFIG.BASE_URL}/api/v1/pdf/42/pages?token=token123`
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -38,15 +38,27 @@ export class NewPdfReaderService {
|
||||
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
|
||||
}
|
||||
|
||||
getAvailablePages(bookId: number) {
|
||||
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
|
||||
getAvailablePages(bookId: number, bookType?: string) {
|
||||
let url = `${this.pagesUrl}/${bookId}/pages`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<number[]>(this.appendToken(url));
|
||||
}
|
||||
|
||||
getPageInfo(bookId: number) {
|
||||
return this.http.get<PdfInfo>(this.appendToken(`${this.pagesUrl}/${bookId}/info`));
|
||||
getPageInfo(bookId: number, bookType?: string) {
|
||||
let url = `${this.pagesUrl}/${bookId}/info`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<PdfInfo>(this.appendToken(url));
|
||||
}
|
||||
|
||||
getPageImageUrl(bookId: number, page: number): string {
|
||||
return this.appendToken(`${this.imageUrl}/${bookId}/pdf/pages/${page}`);
|
||||
getPageImageUrl(bookId: number, page: number, bookType?: string): string {
|
||||
let url = `${this.imageUrl}/${bookId}/pdf/pages/${page}`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,131 +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 {firstValueFrom, of, throwError} from 'rxjs';
|
||||
|
||||
import {ShelfService} from './shelf.service';
|
||||
import {BookService} from './book.service';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
|
||||
describe('ShelfService', () => {
|
||||
let service: ShelfService;
|
||||
let httpClientMock: any;
|
||||
let bookServiceMock: any;
|
||||
let userServiceMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
};
|
||||
|
||||
bookServiceMock = {
|
||||
removeBooksFromShelf: vi.fn(),
|
||||
bookState$: of({
|
||||
books: [
|
||||
{id: 1, shelves: [{id: 10}]},
|
||||
{id: 2, shelves: [{id: 20}]},
|
||||
{id: 3, shelves: []},
|
||||
{id: 4}
|
||||
]
|
||||
})
|
||||
};
|
||||
|
||||
userServiceMock = {
|
||||
userState$: of({user: {id: 1}})
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ShelfService,
|
||||
{provide: HttpClient, useValue: httpClientMock},
|
||||
{provide: BookService, useValue: bookServiceMock},
|
||||
{provide: UserService, useValue: userServiceMock},
|
||||
{provide: 'OAuthService', useValue: {}}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
|
||||
service = runInInjectionContext(
|
||||
injector,
|
||||
() => TestBed.inject(ShelfService)
|
||||
);
|
||||
});
|
||||
|
||||
it('should fetch shelves and update state', () => {
|
||||
const shelves: Shelf[] = [{id: 1, name: 'A', icon: 'icon'}];
|
||||
httpClientMock.get.mockReturnValue(of(shelves));
|
||||
service['fetchShelves']().subscribe(result => {
|
||||
expect(result).toEqual(shelves);
|
||||
expect(service['shelfStateSubject'].value.shelves).toEqual(shelves);
|
||||
expect(service['shelfStateSubject'].value.loaded).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle fetch shelves error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service['shelfStateSubject'].next({shelves: null, loaded: false, error: null});
|
||||
service['fetchShelves']().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(service['shelfStateSubject'].value.error).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should create a shelf and update state', () => {
|
||||
const shelf: Shelf = {id: 2, name: 'B', icon: 'icon'};
|
||||
httpClientMock.post.mockReturnValue(of(shelf));
|
||||
service['shelfStateSubject'].next({shelves: [], loaded: true, error: null});
|
||||
service.createShelf(shelf).subscribe(result => {
|
||||
expect(result).toEqual(shelf);
|
||||
expect(service['shelfStateSubject'].value.shelves).toContain(shelf);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update a shelf and update state', () => {
|
||||
const shelf: Shelf = {id: 3, name: 'C', icon: 'icon'};
|
||||
httpClientMock.put.mockReturnValue(of({...shelf, name: 'C2'}));
|
||||
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
|
||||
service.updateShelf({...shelf, name: 'C2'}, 3).subscribe(result => {
|
||||
expect(result.name).toBe('C2');
|
||||
expect(service['shelfStateSubject'].value.shelves?.find(s => s.id === 3)?.name).toBe('C2');
|
||||
});
|
||||
});
|
||||
|
||||
it('should delete a shelf and update state', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
const shelf: Shelf = {id: 4, name: 'D', icon: 'icon'};
|
||||
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
|
||||
service.deleteShelf(4).subscribe(() => {
|
||||
expect(service['shelfStateSubject'].value.shelves).toEqual([]);
|
||||
expect(bookServiceMock.removeBooksFromShelf).toHaveBeenCalledWith(4);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle delete shelf error', () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
|
||||
service['shelfStateSubject'].next({shelves: [{id: 5, name: 'E', icon: 'icon'}], loaded: true, error: null});
|
||||
service.deleteShelf(5).subscribe({
|
||||
error: () => {
|
||||
expect(service['shelfStateSubject'].value.error).toBe('delete error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should get shelf by id', () => {
|
||||
const shelf: Shelf = {id: 6, name: 'F', icon: 'icon'};
|
||||
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
|
||||
expect(service.getShelfById(6)).toEqual(shelf);
|
||||
expect(service.getShelfById(999)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get unshelved book count', async () => {
|
||||
const count = await firstValueFrom(service.getUnshelvedBookCount());
|
||||
expect(count).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {SortService} from './sort.service';
|
||||
import {Book} from '../model/book.model';
|
||||
import {SortDirection} from '../model/sort.model';
|
||||
|
||||
function makeBook(partial: Partial<Book>): Book {
|
||||
return {
|
||||
id: 1,
|
||||
bookType: "PDF",
|
||||
libraryId: 1,
|
||||
libraryName: "Lib",
|
||||
...partial,
|
||||
} as Book;
|
||||
}
|
||||
|
||||
describe('SortService', () => {
|
||||
let service: SortService;
|
||||
let books: Book[];
|
||||
|
||||
beforeEach(() => {
|
||||
service = new SortService();
|
||||
books = [
|
||||
makeBook({
|
||||
id: 1,
|
||||
fileName: 'Book10.pdf',
|
||||
metadata: {
|
||||
bookId: 1,
|
||||
title: 'Book 10',
|
||||
authors: ['Alice'],
|
||||
publishedDate: '2020-01-01',
|
||||
seriesName: 'Series A',
|
||||
seriesNumber: 2,
|
||||
rating: 4.5,
|
||||
reviewCount: 10,
|
||||
},
|
||||
personalRating: 3,
|
||||
addedOn: '2021-01-01T00:00:00Z',
|
||||
lastReadTime: '2022-01-01T00:00:00Z',
|
||||
fileSizeKb: 1000,
|
||||
}),
|
||||
makeBook({
|
||||
id: 2,
|
||||
fileName: 'Book2.pdf',
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Book 2',
|
||||
authors: ['Bob'],
|
||||
publishedDate: '2019-01-01',
|
||||
seriesName: 'Series A',
|
||||
seriesNumber: 1,
|
||||
rating: 4.8,
|
||||
reviewCount: 20,
|
||||
},
|
||||
personalRating: 5,
|
||||
addedOn: '2020-01-01T00:00:00Z',
|
||||
lastReadTime: '2023-01-01T00:00:00Z',
|
||||
fileSizeKb: 2000,
|
||||
}),
|
||||
makeBook({
|
||||
id: 3,
|
||||
fileName: 'Book1.pdf',
|
||||
metadata: {
|
||||
bookId: 3,
|
||||
title: 'Book 1',
|
||||
authors: ['Alice'],
|
||||
publishedDate: '2021-01-01',
|
||||
rating: 4.0,
|
||||
reviewCount: 5,
|
||||
},
|
||||
personalRating: 4,
|
||||
addedOn: '2022-01-01T00:00:00Z',
|
||||
lastReadTime: '2021-01-01T00:00:00Z',
|
||||
fileSizeKb: 500,
|
||||
}),
|
||||
];
|
||||
});
|
||||
|
||||
it('should sort by title (natural order)', () => {
|
||||
const sorted = service.applySort(books, {field: 'title', direction: SortDirection.ASCENDING, label: 'Title'});
|
||||
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']);
|
||||
});
|
||||
|
||||
it('should sort by author', () => {
|
||||
const sorted = service.applySort(books, {field: 'author', direction: SortDirection.ASCENDING, label: 'Author'});
|
||||
expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Alice', 'Alice', 'Bob']);
|
||||
});
|
||||
|
||||
it('should sort by author surname', () => {
|
||||
const testBooks = [
|
||||
makeBook({ id: 1, metadata: { bookId: 1, title: 'T1', authors: ['Terry Pratchett'] } }),
|
||||
makeBook({ id: 2, metadata: { bookId: 2, title: 'T2', authors: ['Neil Gaiman'] } }),
|
||||
makeBook({ id: 3, metadata: { bookId: 3, title: 'T3', authors: ['Stephen King'] } }),
|
||||
];
|
||||
|
||||
const sorted = service.applySort(testBooks, { field: 'authorSurnameVorname', direction: SortDirection.ASCENDING, label: 'Author (Surname)' });
|
||||
expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Neil Gaiman', 'Stephen King', 'Terry Pratchett']);
|
||||
});
|
||||
|
||||
it('should sort by publishedDate descending', () => {
|
||||
const sorted = service.applySort(books, {field: 'publishedDate', direction: SortDirection.DESCENDING, label: 'Published Date'});
|
||||
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 10', 'Book 2']);
|
||||
});
|
||||
|
||||
it('should sort by series (titleSeries)', () => {
|
||||
const sorted = service.applySort(books, {field: 'titleSeries', direction: SortDirection.ASCENDING, label: 'Series'});
|
||||
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']);
|
||||
});
|
||||
|
||||
it('should sort by personalRating descending', () => {
|
||||
const sorted = service.applySort(books, {field: 'personalRating', direction: SortDirection.DESCENDING, label: 'Personal Rating'});
|
||||
expect(sorted.map(b => b.personalRating)).toEqual([5, 4, 3]);
|
||||
});
|
||||
|
||||
it('should sort by fileName (natural order)', () => {
|
||||
const sorted = service.applySort(books, {field: 'fileName', direction: SortDirection.ASCENDING, label: 'File Name'});
|
||||
expect(sorted.map(b => b.fileName)).toEqual(['Book1.pdf', 'Book2.pdf', 'Book10.pdf']);
|
||||
});
|
||||
|
||||
it('should sort by fileSizeKb ascending', () => {
|
||||
const sorted = service.applySort(books, {field: 'fileSizeKb', direction: SortDirection.ASCENDING, label: 'File Size'});
|
||||
expect(sorted.map(b => b.fileSizeKb)).toEqual([500, 1000, 2000]);
|
||||
});
|
||||
|
||||
it('should sort by addedOn descending', () => {
|
||||
const sorted = service.applySort(books, {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'});
|
||||
expect(sorted.map(b => b.addedOn)).toEqual([
|
||||
'2022-01-01T00:00:00Z',
|
||||
'2021-01-01T00:00:00Z',
|
||||
'2020-01-01T00:00:00Z',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle missing extractor gracefully', () => {
|
||||
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {
|
||||
});
|
||||
const sorted = service.applySort(books, {field: 'nonexistent', direction: SortDirection.ASCENDING, label: 'Nonexistent'} as any);
|
||||
expect(sorted).toBe(books);
|
||||
expect(spy).toHaveBeenCalled();
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it('should return original array if no sort option', () => {
|
||||
const sorted = service.applySort(books, null);
|
||||
expect(sorted).toBe(books);
|
||||
});
|
||||
|
||||
it('should sort by random (order is not predictable)', () => {
|
||||
const sorted = service.applySort(books, {field: 'random', direction: SortDirection.ASCENDING, label: 'Random'});
|
||||
expect(sorted.length).toBe(3);
|
||||
// Can't assert order, but should be a permutation of the input
|
||||
expect(sorted.map(b => b.id).sort()).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
<div class="library-creator">
|
||||
<div class="main-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="header-icon pi pi-book"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h1 class="panel-title">
|
||||
{{ mode === 'edit' ? 'Edit Library' : 'Create New Library' }}
|
||||
</h1>
|
||||
<p class="panel-description">Set up a new library to organize and manage your book collection</p>
|
||||
<header class="dialog-header">
|
||||
<div class="header-content">
|
||||
<div class="header-icon">
|
||||
<i class="pi pi-book"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h1>{{ mode === 'edit' ? 'Edit Library' : 'New Library' }}</h1>
|
||||
<p>Configure your book collection</p>
|
||||
</div>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
@@ -15,346 +15,186 @@
|
||||
[rounded]="true"
|
||||
severity="secondary"
|
||||
(onClick)="closeDialog()"
|
||||
class="close-button"
|
||||
/>
|
||||
</header>
|
||||
|
||||
<div class="dialog-body">
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<span>Library Details</span>
|
||||
</div>
|
||||
|
||||
<div class="form-row two-col">
|
||||
<div class="form-field">
|
||||
<label>
|
||||
Name <span class="required">*</span>
|
||||
</label>
|
||||
<div class="input-container">
|
||||
<input
|
||||
pInputText
|
||||
[(ngModel)]="chosenLibraryName"
|
||||
placeholder="My Library"
|
||||
class="input-full"
|
||||
/>
|
||||
@if (chosenLibraryName.trim()) {
|
||||
<i class="pi pi-check-circle field-status success"></i>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label>
|
||||
Icon <span class="required">*</span>
|
||||
</label>
|
||||
@if (!selectedIcon) {
|
||||
<button class="icon-picker-trigger" (click)="openIconPicker()" type="button">
|
||||
<i class="pi pi-plus"></i>
|
||||
<span>Choose icon</span>
|
||||
</button>
|
||||
} @else {
|
||||
<div class="icon-selected">
|
||||
<div class="icon-preview">
|
||||
<app-icon-display [icon]="selectedIcon" size="16px" />
|
||||
</div>
|
||||
<span class="icon-value">
|
||||
@if (selectedIcon.type === 'PRIME_NG') {
|
||||
{{ selectedIcon.value }}
|
||||
} @else {
|
||||
Custom SVG
|
||||
}
|
||||
</span>
|
||||
<button class="icon-clear" (click)="clearSelectedIcon()" type="button">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-folder-open"></i>
|
||||
<span>Book Folders</span>
|
||||
<span class="section-badge">{{ folders.length }}</span>
|
||||
</div>
|
||||
|
||||
<div class="folders-zone">
|
||||
<button class="add-folder-trigger" (click)="openDirectoryPicker()" type="button">
|
||||
<i class="pi pi-plus-circle"></i>
|
||||
<span>Add folder</span>
|
||||
</button>
|
||||
|
||||
@if (folders.length > 0) {
|
||||
<div class="folders-list">
|
||||
@for (folder of folders; track folder; let i = $index) {
|
||||
<div class="folder-item">
|
||||
<div class="folder-info">
|
||||
<i class="pi pi-folder"></i>
|
||||
<span class="folder-path" [pTooltip]="folder" tooltipPosition="top">
|
||||
{{ folder }}
|
||||
</span>
|
||||
</div>
|
||||
<button class="folder-remove" (click)="removeFolder(i)" type="button">
|
||||
<i class="pi pi-times"></i>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<div class="empty-hint">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<span>Add folders containing your book files</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="form-section collapsible">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-cog"></i>
|
||||
<span>Options</span>
|
||||
</div>
|
||||
|
||||
<div class="options-grid">
|
||||
<div class="option-item">
|
||||
<div class="option-label">
|
||||
<span>Watch folders</span>
|
||||
<i
|
||||
class="pi pi-question-circle info-icon"
|
||||
pTooltip="Automatically detect new books added to folders"
|
||||
tooltipPosition="right"
|
||||
></i>
|
||||
</div>
|
||||
<p-toggleswitch [(ngModel)]="watch" />
|
||||
</div>
|
||||
|
||||
<div class="option-item format-priority-option">
|
||||
<div class="option-label">
|
||||
<span>Format priority</span>
|
||||
<i
|
||||
class="pi pi-question-circle info-icon"
|
||||
pTooltip="Drag to set preferred format when a book has multiple files"
|
||||
tooltipPosition="right"
|
||||
></i>
|
||||
</div>
|
||||
<div
|
||||
class="format-chips"
|
||||
cdkDropList
|
||||
cdkDropListOrientation="mixed"
|
||||
[cdkDropListData]="formatPriority"
|
||||
(cdkDropListDropped)="onFormatPriorityDrop($event)"
|
||||
>
|
||||
@for (format of formatPriority; track format.type; let i = $index) {
|
||||
<div class="format-chip" cdkDrag>
|
||||
<span class="chip-rank">{{ i + 1 }}</span>
|
||||
<span class="chip-label">{{ format.type }}</span>
|
||||
<i class="pi pi-arrows-alt drag-indicator" cdkDragHandle></i>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<p-stepper [value]="1" class="custom-stepper">
|
||||
<p-step-list>
|
||||
<p-step [value]="1">
|
||||
<div class="step-content">
|
||||
<div class="step-labels">
|
||||
<span class="step-title">Library Details</span>
|
||||
</div>
|
||||
<footer class="dialog-footer">
|
||||
<div class="validation-status">
|
||||
@if (!isLibraryDetailsValid() || !isDirectorySelectionValid()) {
|
||||
<div class="status-message warning">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<span>
|
||||
@if (!chosenLibraryName.trim()) {
|
||||
Enter library name
|
||||
} @else if (!selectedIcon) {
|
||||
Select an icon
|
||||
} @else {
|
||||
Add at least one folder
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</p-step>
|
||||
<p-step [value]="2">
|
||||
<div class="step-content">
|
||||
<div class="step-labels">
|
||||
<span class="step-title">Select Directories</span>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="status-message ready">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<span>Ready to {{ mode === 'edit' ? 'update' : 'create' }}</span>
|
||||
</div>
|
||||
</p-step>
|
||||
</p-step-list>
|
||||
|
||||
<p-step-panels>
|
||||
<p-step-panel [value]="1">
|
||||
<ng-template #content let-activateCallback="activateCallback">
|
||||
<div class="step-panel-wrapper">
|
||||
<div class="step-panel-container">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-bookmark header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">Step 1: Library Information</h2>
|
||||
<p class="panel-description">Set up your library name, icon, and import preferences</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-container">
|
||||
<div class="form-section">
|
||||
<div class="form-group highlight-group">
|
||||
<label class="form-label">
|
||||
<i class="pi pi-tag label-icon"></i>
|
||||
1. Library Name
|
||||
<span class="required-indicator">*</span>
|
||||
</label>
|
||||
<div class="input-wrapper">
|
||||
<input
|
||||
pInputText
|
||||
fluid
|
||||
[(ngModel)]="chosenLibraryName"
|
||||
placeholder="e.g., My Personal Library"
|
||||
[class.filled]="chosenLibraryName.trim()"
|
||||
class="input-full"
|
||||
/>
|
||||
@if (chosenLibraryName.trim()) {
|
||||
<i class="pi pi-check-circle input-icon success"></i>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-group highlight-group">
|
||||
<label class="form-label">
|
||||
<i class="pi pi-palette label-icon"></i>
|
||||
2. Library Icon
|
||||
<span class="required-indicator">*</span>
|
||||
</label>
|
||||
@if (!selectedIcon) {
|
||||
<button class="icon-select-btn" (click)="openIconPicker()" type="button">
|
||||
<i class="pi pi-plus"></i>
|
||||
<div class="btn-content">
|
||||
<span class="btn-title">Choose an Icon</span>
|
||||
<span class="btn-subtitle">Select from available icons</span>
|
||||
</div>
|
||||
</button>
|
||||
} @else {
|
||||
<div class="selected-icon-display">
|
||||
<div class="icon-preview">
|
||||
<app-icon-display
|
||||
[icon]="selectedIcon"
|
||||
size="24px"
|
||||
/>
|
||||
</div>
|
||||
<div class="icon-info">
|
||||
<span class="icon-label">Selected Icon</span>
|
||||
<span class="icon-name">
|
||||
@if (selectedIcon.type === 'PRIME_NG') {
|
||||
{{ selectedIcon.value }}
|
||||
} @else {
|
||||
{{ selectedIcon.value }} (Custom)
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
size="small"
|
||||
(onClick)="clearSelectedIcon()"
|
||||
pTooltip="Remove icon"
|
||||
tooltipPosition="left"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-section">
|
||||
<div class="form-group">
|
||||
<label class="form-label">
|
||||
<i class="pi pi-cog label-icon"></i>
|
||||
3. Import Mode
|
||||
</label>
|
||||
<div class="input-with-info">
|
||||
<p-select
|
||||
[(ngModel)]="scanMode"
|
||||
[options]="scanModeOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Choose scan mode"
|
||||
class="full-width"
|
||||
[showClear]="false"
|
||||
/>
|
||||
<div class="info-tooltip large">
|
||||
<i
|
||||
class="pi pi-question-circle"
|
||||
pTooltip="File as Book: Each file becomes a separate book. Folder as Book: Each folder is treated as one book with multiple formats."
|
||||
[escape]="false"
|
||||
tooltipPosition="right"
|
||||
></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (scanMode === 'FOLDER_AS_BOOK') {
|
||||
<div class="form-group nested-group">
|
||||
<label class="form-label">
|
||||
<i class="pi pi-file label-icon"></i>
|
||||
Preferred Format
|
||||
</label>
|
||||
<div class="input-with-info">
|
||||
<p-select
|
||||
[(ngModel)]="defaultBookFormat"
|
||||
[options]="bookFormatOptions"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
placeholder="Select preferred format"
|
||||
class="full-width"
|
||||
appendTo="body"
|
||||
/>
|
||||
<div class="info-tooltip">
|
||||
<i
|
||||
class="pi pi-question-circle"
|
||||
pTooltip="If a folder has multiple formats, this determines the primary format to use"
|
||||
tooltipPosition="right"
|
||||
></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="gradient-divider"></div>
|
||||
|
||||
<div class="form-section">
|
||||
<div class="form-group">
|
||||
<label class="form-label">
|
||||
<i class="pi pi-eye label-icon"></i>
|
||||
4. Monitor Folders
|
||||
</label>
|
||||
<div class="toggle-group">
|
||||
<div class="toggle-wrapper">
|
||||
<p-toggleswitch [(ngModel)]="watch" inputId="watch-toggle"/>
|
||||
<label for="watch-toggle" class="toggle-label">
|
||||
@if (watch) {
|
||||
<span class="toggle-status active">Enabled</span>
|
||||
} @else {
|
||||
<span class="toggle-status inactive">Disabled</span>
|
||||
}
|
||||
</label>
|
||||
</div>
|
||||
<div class="info-tooltip large">
|
||||
<i
|
||||
class="pi pi-question-circle"
|
||||
pTooltip="Automatically detect and import new books when files are added to watched folders"
|
||||
[escape]="false"
|
||||
tooltipPosition="right"
|
||||
></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-footer">
|
||||
<div class="validation-status">
|
||||
@if (!isLibraryDetailsValid()) {
|
||||
<div class="validation-message error">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<span>Please complete all required fields</span>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="validation-message success">
|
||||
<i class="pi pi-check-circle"></i>
|
||||
<span>Ready to proceed</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<p-button
|
||||
label="Continue to Directories"
|
||||
icon="pi pi-arrow-right"
|
||||
iconPos="right"
|
||||
severity="success"
|
||||
(onClick)="validateLibraryNameAndProceed(activateCallback)"
|
||||
[disabled]="!isLibraryDetailsValid()"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-step-panel>
|
||||
|
||||
<p-step-panel [value]="2">
|
||||
<ng-template #content let-activateCallback="activateCallback">
|
||||
<div class="step-panel-wrapper">
|
||||
<div class="step-panel-container">
|
||||
<div class="panel-header">
|
||||
<div class="header-icon-wrapper">
|
||||
<i class="pi pi-folder-open header-icon"></i>
|
||||
</div>
|
||||
<div class="header-text">
|
||||
<h2 class="panel-title">Step 2: Book Directories</h2>
|
||||
<p class="panel-description">Add folders containing your book files</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="directories-container">
|
||||
<div class="add-folder-section">
|
||||
<p-button
|
||||
class="add-folder-btn"
|
||||
outlined
|
||||
severity="info"
|
||||
(onClick)="openDirectoryPicker()"
|
||||
>
|
||||
<i class="pi pi-plus-circle"></i>
|
||||
<div class="btn-content">
|
||||
<span class="btn-title">Add Book Folder</span>
|
||||
<span class="btn-subtitle">Browse for directories</span>
|
||||
</div>
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
@if (folders.length === 0) {
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon-wrapper">
|
||||
<i class="pi pi-folder-open empty-icon"></i>
|
||||
</div>
|
||||
<h3 class="empty-title">No Folders Added Yet</h3>
|
||||
<p class="empty-description">
|
||||
Click the button above to add folders containing your books.<br/>
|
||||
You can add multiple folders from different locations.
|
||||
</p>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="folders-list">
|
||||
<div class="list-header">
|
||||
<span class="folder-count">
|
||||
<i class="pi pi-folder"></i>
|
||||
{{ folders.length }} {{ folders.length === 1 ? 'folder' : 'folders' }} added
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="folders-grid">
|
||||
@for (folder of folders; track folder; let i = $index) {
|
||||
<div class="folder-card">
|
||||
<div class="folder-icon-section">
|
||||
<div class="folder-icon-wrapper">
|
||||
<i class="pi pi-folder folder-icon"></i>
|
||||
</div>
|
||||
<div class="folder-number">{{ i + 1 }}</div>
|
||||
</div>
|
||||
<div class="folder-details">
|
||||
<div class="folder-path" [pTooltip]="folder" tooltipPosition="top">
|
||||
{{ folder }}
|
||||
</div>
|
||||
<div class="folder-meta">
|
||||
<i class="pi pi-map-marker"></i>
|
||||
<span>{{ getFolderName(folder) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
outlined="true"
|
||||
rounded
|
||||
size="small"
|
||||
(onClick)="removeFolder(i)"
|
||||
pTooltip="Remove folder"
|
||||
tooltipPosition="left"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-footer">
|
||||
<p-button
|
||||
label="Back"
|
||||
icon="pi pi-arrow-left"
|
||||
iconPos="left"
|
||||
severity="warn"
|
||||
(onClick)="activateCallback(1)"
|
||||
/>
|
||||
<div class="footer-right">
|
||||
@if (!isDirectorySelectionValid()) {
|
||||
<div class="validation-message error">
|
||||
<i class="pi pi-exclamation-circle"></i>
|
||||
<span>Add at least one folder</span>
|
||||
</div>
|
||||
}
|
||||
<p-button
|
||||
[label]="mode === 'edit' ? 'Update Library' : 'Create Library'"
|
||||
[icon]="mode === 'edit' ? 'pi pi-save' : 'pi pi-check'"
|
||||
severity="success"
|
||||
[disabled]="!isDirectorySelectionValid()"
|
||||
(onClick)="createOrUpdateLibrary()"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-step-panel>
|
||||
|
||||
</p-step-panels>
|
||||
</p-stepper>
|
||||
}
|
||||
</div>
|
||||
<div class="footer-actions">
|
||||
<p-button
|
||||
label="Cancel"
|
||||
severity="secondary"
|
||||
[outlined]="true"
|
||||
(onClick)="closeDialog()"
|
||||
/>
|
||||
<p-button
|
||||
[label]="mode === 'edit' ? 'Update' : 'Create'"
|
||||
[icon]="mode === 'edit' ? 'pi pi-save' : 'pi pi-check'"
|
||||
severity="primary"
|
||||
[disabled]="!isLibraryDetailsValid() || !isDirectorySelectionValid()"
|
||||
(onClick)="createOrUpdateLibrary()"
|
||||
/>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,26 +3,25 @@ import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Router} from '@angular/router';
|
||||
import {LibraryService} from '../book/service/library.service';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {Step, StepList, StepPanel, StepPanels, Stepper} from 'primeng/stepper';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {BookFileType, Library, LibraryScanMode} from '../book/model/library.model';
|
||||
import {Library} from '../book/model/library.model';
|
||||
import {BookType} from '../book/model/book.model';
|
||||
import {ToggleSwitch} from 'primeng/toggleswitch';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {IconPickerService, IconSelection} from '../../shared/service/icon-picker.service';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Button} from 'primeng/button';
|
||||
import {IconDisplayComponent} from '../../shared/components/icon-display/icon-display.component';
|
||||
import {DialogLauncherService} from '../../shared/services/dialog-launcher.service';
|
||||
import {switchMap} from 'rxjs/operators';
|
||||
import {map, of} from 'rxjs';
|
||||
import {map} from 'rxjs';
|
||||
import {CdkDragDrop, DragDropModule, moveItemInArray} from '@angular/cdk/drag-drop';
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-creator',
|
||||
standalone: true,
|
||||
templateUrl: './library-creator.component.html',
|
||||
imports: [TableModule, StepPanel, FormsModule, InputText, Stepper, StepList, Step, StepPanels, ToggleSwitch, Tooltip, Select, Button, IconDisplayComponent],
|
||||
imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule],
|
||||
styleUrl: './library-creator.component.scss'
|
||||
})
|
||||
export class LibraryCreatorComponent implements OnInit {
|
||||
@@ -34,19 +33,16 @@ export class LibraryCreatorComponent implements OnInit {
|
||||
library!: Library | undefined;
|
||||
editModeLibraryName: string = '';
|
||||
watch: boolean = false;
|
||||
scanMode: LibraryScanMode = 'FILE_AS_BOOK';
|
||||
defaultBookFormat: BookFileType | undefined = undefined;
|
||||
formatPriority: {type: BookType, label: string}[] = [];
|
||||
|
||||
readonly scanModeOptions = [
|
||||
{label: 'Each file is a book (Recommended)', value: 'FILE_AS_BOOK'},
|
||||
{label: 'Each folder is a book with extras (Deprecated)', value: 'FOLDER_AS_BOOK'}
|
||||
];
|
||||
|
||||
readonly bookFormatOptions = [
|
||||
{label: 'None', value: undefined},
|
||||
{label: 'EPUB', value: 'EPUB'},
|
||||
{label: 'PDF', value: 'PDF'},
|
||||
{label: 'CBX/CBZ/CBR', value: 'CBX'}
|
||||
readonly allBookFormats: {type: BookType, label: string}[] = [
|
||||
{type: 'EPUB', label: 'EPUB'},
|
||||
{type: 'PDF', label: 'PDF'},
|
||||
{type: 'CBX', label: 'CBX (CBZ/CBR/CB7)'},
|
||||
{type: 'MOBI', label: 'MOBI'},
|
||||
{type: 'AZW3', label: 'AZW3'},
|
||||
{type: 'FB2', label: 'FB2'},
|
||||
{type: 'AUDIOBOOK', label: 'Audiobook'}
|
||||
];
|
||||
|
||||
private dialogLauncherService = inject(DialogLauncherService);
|
||||
@@ -58,12 +54,14 @@ export class LibraryCreatorComponent implements OnInit {
|
||||
private iconPicker = inject(IconPickerService);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.initializeFormatPriority();
|
||||
|
||||
const data = this.dynamicDialogConfig?.data;
|
||||
if (data?.mode === 'edit') {
|
||||
this.mode = data.mode;
|
||||
this.library = this.libraryService.findLibraryById(data.libraryId);
|
||||
if (this.library) {
|
||||
const {name, icon, iconType, paths, watch, scanMode, defaultBookFormat} = this.library;
|
||||
const {name, icon, iconType, paths, watch, formatPriority} = this.library;
|
||||
this.chosenLibraryName = name;
|
||||
this.editModeLibraryName = name;
|
||||
|
||||
@@ -75,13 +73,26 @@ export class LibraryCreatorComponent implements OnInit {
|
||||
}
|
||||
|
||||
this.watch = watch;
|
||||
this.scanMode = scanMode || 'FILE_AS_BOOK';
|
||||
this.defaultBookFormat = defaultBookFormat || undefined;
|
||||
if (formatPriority && formatPriority.length > 0) {
|
||||
this.formatPriority = formatPriority.map(type =>
|
||||
this.allBookFormats.find(f => f.type === type)!
|
||||
).filter(f => f !== undefined);
|
||||
const existingTypes = new Set(formatPriority);
|
||||
this.allBookFormats.forEach(f => {
|
||||
if (!existingTypes.has(f.type)) {
|
||||
this.formatPriority.push(f);
|
||||
}
|
||||
});
|
||||
}
|
||||
this.folders = paths.map(path => path.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private initializeFormatPriority(): void {
|
||||
this.formatPriority = [...this.allBookFormats];
|
||||
}
|
||||
|
||||
closeDialog(): void {
|
||||
this.dynamicDialogRef.close();
|
||||
}
|
||||
@@ -127,9 +138,9 @@ export class LibraryCreatorComponent implements OnInit {
|
||||
return this.folders.length > 0;
|
||||
}
|
||||
|
||||
validateLibraryNameAndProceed(activateCallback: Function): void {
|
||||
createOrUpdateLibrary(): void {
|
||||
const trimmedLibraryName = this.chosenLibraryName.trim();
|
||||
if (trimmedLibraryName && trimmedLibraryName != this.editModeLibraryName) {
|
||||
if (trimmedLibraryName && trimmedLibraryName !== this.editModeLibraryName) {
|
||||
const exists = this.libraryService.doesLibraryExistByName(trimmedLibraryName);
|
||||
if (exists) {
|
||||
this.messageService.add({
|
||||
@@ -137,15 +148,10 @@ export class LibraryCreatorComponent implements OnInit {
|
||||
summary: 'Library Name Exists',
|
||||
detail: 'This library name is already taken.',
|
||||
});
|
||||
} else {
|
||||
activateCallback(2);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
activateCallback(2);
|
||||
}
|
||||
}
|
||||
|
||||
createOrUpdateLibrary(): void {
|
||||
const iconValue = this.selectedIcon?.value || 'heart';
|
||||
const iconType = this.selectedIcon?.type || 'PRIME_NG';
|
||||
|
||||
@@ -155,8 +161,7 @@ export class LibraryCreatorComponent implements OnInit {
|
||||
iconType: iconType,
|
||||
paths: this.folders.map(folder => ({path: folder})),
|
||||
watch: this.watch,
|
||||
scanMode: this.scanMode,
|
||||
defaultBookFormat: this.defaultBookFormat
|
||||
formatPriority: this.formatPriority.map(f => f.type)
|
||||
};
|
||||
|
||||
if (this.mode === 'edit') {
|
||||
@@ -208,11 +213,7 @@ export class LibraryCreatorComponent implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
getFolderName(path: string): string {
|
||||
if (!path || typeof path !== 'string') {
|
||||
return '';
|
||||
}
|
||||
const parts = path.split('/').filter(p => p);
|
||||
return parts[parts.length - 1] || path;
|
||||
onFormatPriorityDrop(event: CdkDragDrop<{type: BookType, label: string}[]>): void {
|
||||
moveItemInArray(this.formatPriority, event.previousIndex, event.currentIndex);
|
||||
}
|
||||
}
|
||||
|
||||
+21
-8
@@ -24,8 +24,8 @@
|
||||
class="p-datatable-sm">
|
||||
<ng-template #header>
|
||||
<tr>
|
||||
<th>Start Time</th>
|
||||
<th>End Time</th>
|
||||
<th>Session</th>
|
||||
<th>Type</th>
|
||||
<th>Duration</th>
|
||||
<th>Progress</th>
|
||||
<th>Progress Delta</th>
|
||||
@@ -34,8 +34,18 @@
|
||||
</ng-template>
|
||||
<ng-template #body let-session>
|
||||
<tr>
|
||||
<td>{{ formatDate(session.startTime) }}</td>
|
||||
<td>{{ formatDate(session.endTime) }}</td>
|
||||
<td>
|
||||
<div class="session-time">
|
||||
<span class="session-date">{{ formatSessionDate(session.startTime) }}</span>
|
||||
<span class="session-range">{{ formatTime(session.startTime) }} → {{ formatTime(session.endTime) }}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="book-type-badge" [ngClass]="'book-type-' + session.bookType.toLowerCase()">
|
||||
<i [class]="getBookTypeIcon(session.bookType)"></i>
|
||||
<span>{{ formatBookType(session.bookType) }}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ getActualDuration(session) }}</td>
|
||||
<td>
|
||||
@if (session.startProgress !== null && session.startProgress !== undefined && session.endProgress !== null && session.endProgress !== undefined) {
|
||||
@@ -46,14 +56,17 @@
|
||||
</td>
|
||||
<td>
|
||||
@if (session.progressDelta !== null && session.progressDelta !== undefined) {
|
||||
<p-tag [value]="(session.progressDelta > 0 ? '+' : '') + session.progressDelta + '%'" [severity]="getProgressColor(session.progressDelta)"></p-tag>
|
||||
<span class="progress-delta-badge" [ngClass]="getProgressDeltaClass(session.progressDelta)">
|
||||
<i [class]="getProgressDeltaIcon(session.progressDelta)"></i>
|
||||
<span>{{ (session.progressDelta > 0 ? '+' : '') + session.progressDelta }}%</span>
|
||||
</span>
|
||||
} @else {
|
||||
<span class="text-color-secondary">N/A</span>
|
||||
<span class="text-color-secondary">-</span>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@if (session.startLocation && session.endLocation && isPageNumber(session.startLocation)) {
|
||||
<span class="location-text">Page {{ session.startLocation }} → Page {{ session.endLocation }}</span>
|
||||
@if (session.startLocation && session.endLocation) {
|
||||
<span class="location-text">{{ formatLocation(session) }}</span>
|
||||
} @else {
|
||||
<span class="text-color-secondary">-</span>
|
||||
}
|
||||
|
||||
+97
@@ -27,6 +27,103 @@
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.session-time {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
|
||||
.session-date {
|
||||
font-weight: 500;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.session-range {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.book-type-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
|
||||
i {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
&.book-type-pdf {
|
||||
color: var(--book-type-pdf-color);
|
||||
background-color: rgba(220, 38, 38, 0.1);
|
||||
}
|
||||
|
||||
&.book-type-epub {
|
||||
color: var(--book-type-epub-color);
|
||||
background-color: rgba(22, 163, 74, 0.1);
|
||||
}
|
||||
|
||||
&.book-type-cbx,
|
||||
&.book-type-cbz,
|
||||
&.book-type-cbr,
|
||||
&.book-type-cb7 {
|
||||
color: var(--book-type-cbx-color);
|
||||
background-color: rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
|
||||
&.book-type-fb2 {
|
||||
color: var(--book-type-fb2-color);
|
||||
background-color: rgba(236, 72, 153, 0.1);
|
||||
}
|
||||
|
||||
&.book-type-mobi {
|
||||
color: var(--book-type-mobi-color);
|
||||
background-color: rgba(99, 102, 241, 0.1);
|
||||
}
|
||||
|
||||
&.book-type-azw3 {
|
||||
color: var(--book-type-azw3-color);
|
||||
background-color: rgba(20, 184, 166, 0.1);
|
||||
}
|
||||
|
||||
&.book-type-audiobook {
|
||||
color: var(--book-type-audiobook-color);
|
||||
background-color: rgba(234, 179, 8, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
.progress-delta-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
|
||||
i {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
&.progress-positive {
|
||||
color: #16a34a;
|
||||
background-color: rgba(22, 163, 74, 0.1);
|
||||
}
|
||||
|
||||
&.progress-negative {
|
||||
color: #dc2626;
|
||||
background-color: rgba(220, 38, 38, 0.1);
|
||||
}
|
||||
|
||||
&.progress-neutral {
|
||||
color: var(--text-color-secondary);
|
||||
background-color: rgba(128, 128, 128, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
:host ::ng-deep {
|
||||
.p-datatable {
|
||||
.p-datatable-thead > tr > th {
|
||||
|
||||
+66
-3
@@ -3,12 +3,10 @@ import {CommonModule} from '@angular/common';
|
||||
import {ReadingSessionApiService, ReadingSessionResponse} from '../../../../../shared/service/reading-session-api.service';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {ProgressSpinnerModule} from 'primeng/progressspinner';
|
||||
import {TagModule} from 'primeng/tag';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-reading-sessions',
|
||||
standalone: true,
|
||||
imports: [CommonModule, TableModule, ProgressSpinnerModule, TagModule],
|
||||
imports: [CommonModule, TableModule, ProgressSpinnerModule],
|
||||
templateUrl: './book-reading-sessions.component.html',
|
||||
styleUrls: ['./book-reading-sessions.component.scss']
|
||||
})
|
||||
@@ -91,14 +89,79 @@ export class BookReadingSessionsComponent implements OnInit, OnChanges {
|
||||
return new Date(dateString).toLocaleString();
|
||||
}
|
||||
|
||||
formatSessionDate(dateString: string): string {
|
||||
return new Date(dateString).toLocaleDateString(undefined, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric'
|
||||
});
|
||||
}
|
||||
|
||||
formatTime(dateString: string): string {
|
||||
return new Date(dateString).toLocaleTimeString(undefined, {
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
getBookTypeIcon(bookType: string): string {
|
||||
const iconMap: Record<string, string> = {
|
||||
'PDF': 'pi pi-file-pdf',
|
||||
'EPUB': 'pi pi-book',
|
||||
'CBX': 'pi pi-images',
|
||||
'CBZ': 'pi pi-images',
|
||||
'CBR': 'pi pi-images',
|
||||
'CB7': 'pi pi-images',
|
||||
'FB2': 'pi pi-file',
|
||||
'MOBI': 'pi pi-book',
|
||||
'AZW3': 'pi pi-book',
|
||||
'AUDIOBOOK': 'pi pi-headphones'
|
||||
};
|
||||
return iconMap[bookType] || 'pi pi-file';
|
||||
}
|
||||
|
||||
formatBookType(bookType: string): string {
|
||||
if (bookType === 'AUDIOBOOK') return 'Audio';
|
||||
return bookType;
|
||||
}
|
||||
|
||||
getProgressColor(delta: number): 'success' | 'secondary' | 'danger' {
|
||||
if (delta > 0) return 'success';
|
||||
if (delta < 0) return 'danger';
|
||||
return 'secondary';
|
||||
}
|
||||
|
||||
getProgressDeltaClass(delta: number): string {
|
||||
if (delta > 0) return 'progress-positive';
|
||||
if (delta < 0) return 'progress-negative';
|
||||
return 'progress-neutral';
|
||||
}
|
||||
|
||||
getProgressDeltaIcon(delta: number): string {
|
||||
if (delta > 0) return 'pi pi-arrow-up';
|
||||
if (delta < 0) return 'pi pi-arrow-down';
|
||||
return 'pi pi-minus';
|
||||
}
|
||||
|
||||
isPageNumber(location: string | undefined): boolean {
|
||||
if (!location) return false;
|
||||
return !isNaN(Number(location)) && location.trim() !== '';
|
||||
}
|
||||
|
||||
formatLocation(session: ReadingSessionResponse): string {
|
||||
const start = session.startLocation;
|
||||
const end = session.endLocation;
|
||||
|
||||
if (!start || !end) return '-';
|
||||
|
||||
if (session.bookType === 'AUDIOBOOK') {
|
||||
return `${start} → ${end}`;
|
||||
}
|
||||
|
||||
if (this.isPageNumber(start)) {
|
||||
return `Page ${start} → ${end}`;
|
||||
}
|
||||
|
||||
return '-';
|
||||
}
|
||||
}
|
||||
|
||||
+329
-440
@@ -1,465 +1,354 @@
|
||||
@if (book$ | async; as book) {
|
||||
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="form-container">
|
||||
<div class="form-content">
|
||||
<div class="metadata-header desktop-only">
|
||||
<p class="metadata-header-text">Current Metadata</p>
|
||||
<p-button
|
||||
severity="info"
|
||||
icon='pi pi-angle-left'
|
||||
class="button-left"
|
||||
[outlined]="true"
|
||||
pTooltip="Move all missing fields" tooltipPosition="bottom"
|
||||
(onClick)="copyMissing()"></p-button>
|
||||
<p-button
|
||||
severity="info"
|
||||
icon='pi pi-angle-double-left'
|
||||
class="button-double-left"
|
||||
[outlined]="true"
|
||||
pTooltip="Move all fields" tooltipPosition="bottom"
|
||||
(onClick)="copyAll()"></p-button>
|
||||
<p class="metadata-header-text">Fetched Metadata</p>
|
||||
</div>
|
||||
<div class="metadata-header-mobile mobile-only">
|
||||
<p-button
|
||||
severity="info"
|
||||
icon='pi pi-angle-up'
|
||||
label="Copy Missing"
|
||||
[outlined]="true"
|
||||
size="small"
|
||||
(onClick)="copyMissing()"></p-button>
|
||||
<p-button
|
||||
severity="info"
|
||||
icon='pi pi-angle-double-up'
|
||||
label="Copy All"
|
||||
[outlined]="true"
|
||||
size="small"
|
||||
(onClick)="copyAll()"></p-button>
|
||||
</div>
|
||||
|
||||
<!-- Thumbnail Row -->
|
||||
<div class="form-row thumbnail-row">
|
||||
<label class="label desktop-only"></label>
|
||||
<div class="input-container thumbnail-container">
|
||||
<!-- Mobile layout: current image -> lock -> arrow -> fetched image -->
|
||||
<div class="mobile-thumbnail-row mobile-only">
|
||||
<p-image
|
||||
class="thumbnail"
|
||||
[src]="metadataForm.get('thumbnailUrl')?.value"
|
||||
alt="Image"
|
||||
appendTo="body"
|
||||
lazyLoad
|
||||
[preview]="true">
|
||||
</p-image>
|
||||
@if (!metadataForm.get('coverLocked')?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success" size="small"></p-button>
|
||||
}
|
||||
@if (metadataForm.get('coverLocked')?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn" size="small"></p-button>
|
||||
}
|
||||
<p-button
|
||||
[icon]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved('thumbnailUrl'),
|
||||
'yellow-outlined-button': isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl'],
|
||||
'red-outlined-button': isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']
|
||||
}"
|
||||
class="arrow-button"
|
||||
size="small"
|
||||
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
|
||||
(mouseenter)="onMouseEnter('thumbnailUrl')"
|
||||
(mouseleave)="onMouseLeave('thumbnailUrl')"/>
|
||||
<p-image
|
||||
class="thumbnail"
|
||||
[src]="fetchedMetadata.thumbnailUrl!"
|
||||
alt="Image"
|
||||
appendTo="body"
|
||||
lazyLoad
|
||||
[preview]="true">
|
||||
</p-image>
|
||||
</div>
|
||||
<!-- Desktop layout -->
|
||||
<div class="desktop-only desktop-field-row">
|
||||
@if (!metadataForm.get('coverLocked')?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
|
||||
}
|
||||
@if (metadataForm.get('coverLocked')?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
|
||||
}
|
||||
<p-image
|
||||
class="thumbnail"
|
||||
[src]="metadataForm.get('thumbnailUrl')?.value"
|
||||
alt="Image"
|
||||
appendTo="body"
|
||||
lazyLoad
|
||||
[preview]="true">
|
||||
</p-image>
|
||||
<input type="hidden" id="thumbnailUrl" formControlName="thumbnailUrl" class="input"/>
|
||||
<p-button
|
||||
[icon]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved('thumbnailUrl'),
|
||||
'yellow-outlined-button': isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl'],
|
||||
'red-outlined-button': isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']
|
||||
}"
|
||||
class="arrow-button"
|
||||
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
|
||||
(mouseenter)="onMouseEnter('thumbnailUrl')"
|
||||
(mouseleave)="onMouseLeave('thumbnailUrl')"/>
|
||||
<input type="hidden" [value]="fetchedMetadata.thumbnailUrl" class="input" readonly/>
|
||||
<p-image
|
||||
class="thumbnail"
|
||||
[src]="fetchedMetadata.thumbnailUrl!"
|
||||
alt="Image"
|
||||
appendTo="body"
|
||||
lazyLoad
|
||||
[preview]="true">
|
||||
</p-image>
|
||||
</div>
|
||||
<form [formGroup]="metadataForm" (ngSubmit)="onSave()" class="metadata-picker">
|
||||
<div class="dialog-body">
|
||||
<!-- Column Headers (Desktop) -->
|
||||
<div class="column-headers desktop-only">
|
||||
<div class="column-label current">
|
||||
<i class="pi pi-file-edit"></i>
|
||||
<span>Current</span>
|
||||
</div>
|
||||
<div class="column-actions">
|
||||
<p-button
|
||||
icon="pi pi-angle-left"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
severity="secondary"
|
||||
pTooltip="Copy missing fields"
|
||||
tooltipPosition="bottom"
|
||||
(onClick)="copyMissing()"
|
||||
/>
|
||||
<p-button
|
||||
icon="pi pi-angle-double-left"
|
||||
[rounded]="true"
|
||||
[outlined]="true"
|
||||
severity="primary"
|
||||
pTooltip="Copy all fields"
|
||||
tooltipPosition="bottom"
|
||||
(onClick)="copyAll()"
|
||||
/>
|
||||
</div>
|
||||
<div class="column-label fetched">
|
||||
<i class="pi pi-cloud-download"></i>
|
||||
<span>Fetched</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@for (field of metadataFieldsTop; track field) {
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
<!-- Mobile layout -->
|
||||
<div class="mobile-field-row mobile-only">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success" size="small"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn" size="small"></p-button>
|
||||
}
|
||||
@if (field.controlName === 'publishedDate') {
|
||||
<input pSize="small" fluid pInputText id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input" placeholder="YYYY-MM-DD"/>
|
||||
} @else {
|
||||
<input pSize="small" fluid pInputText id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"/>
|
||||
}
|
||||
</div>
|
||||
<div class="mobile-field-row mobile-only">
|
||||
<input pSize="small" pInputText [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input fetched-input" readonly/>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-up')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
size="small"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
</div>
|
||||
<!-- Desktop layout -->
|
||||
<div class="desktop-only desktop-field-row">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
@if (field.controlName === 'publishedDate') {
|
||||
<input pSize="small" fluid pInputText formControlName="{{field.controlName}}" class="input" placeholder="YYYY-MM-DD"/>
|
||||
} @else {
|
||||
<input pSize="small" fluid pInputText formControlName="{{field.controlName}}" class="input"/>
|
||||
}
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
<input pSize="small" pInputText [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input" readonly/>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Cover Image Section -->
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-image"></i>
|
||||
<span>Cover Image</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@for (field of metadataChips; track field) {
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
<!-- Mobile layout -->
|
||||
<div class="mobile-field-row mobile-only">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success" size="small"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn" size="small"></p-button>
|
||||
}
|
||||
<div class="autocomplete-container">
|
||||
<p-autoComplete
|
||||
class="autocomplete-full-width"
|
||||
formControlName="{{field.controlName}}"
|
||||
[multiple]="true"
|
||||
[dropdown]="false"
|
||||
[forceSelection]="false"
|
||||
[showClear]="true"
|
||||
[suggestions]="getFiltered(field.controlName)"
|
||||
(completeMethod)="filterItems($event, field.controlName)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp(field.controlName, $event)"
|
||||
(onSelect)="onAutoCompleteSelect(field.controlName, $event)">
|
||||
</p-autoComplete>
|
||||
<div class="section-content">
|
||||
<div class="field-row cover-field-row">
|
||||
<label class="field-label">Cover</label>
|
||||
<div class="field-content">
|
||||
<div class="field-side current cover-side">
|
||||
<span class="cover-label mobile-only">Current</span>
|
||||
<div class="cover-wrapper">
|
||||
<p-image
|
||||
class="cover-image"
|
||||
[src]="metadataForm.get('thumbnailUrl')?.value"
|
||||
alt="Current cover"
|
||||
appendTo="body"
|
||||
lazyLoad
|
||||
[preview]="true"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="lock-badge"
|
||||
[class.locked]="metadataForm.get('coverLocked')?.value"
|
||||
(click)="toggleLock('thumbnailUrl')"
|
||||
[pTooltip]="metadataForm.get('coverLocked')?.value ? 'Unlock cover' : 'Lock cover'"
|
||||
tooltipPosition="top"
|
||||
>
|
||||
<i [class]="metadataForm.get('coverLocked')?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mobile-field-row mobile-only">
|
||||
<div class="autocomplete-container">
|
||||
<p-autoComplete
|
||||
[ngModel]="fetchedMetadata[field.fetchedKey] ?? []"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
[disabled]="true"
|
||||
[multiple]="true" [typeahead]="false" [dropdown]="false" [forceSelection]="false" class="autocomplete-full-width fetched-input">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-up')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
size="small"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
</div>
|
||||
<!-- Desktop layout -->
|
||||
<div class="desktop-only desktop-field-row">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
<div class="autocomplete-container">
|
||||
<p-autoComplete
|
||||
class="autocomplete-full-width"
|
||||
formControlName="{{field.controlName}}"
|
||||
[multiple]="true"
|
||||
[dropdown]="false"
|
||||
[forceSelection]="false"
|
||||
[showClear]="true"
|
||||
[suggestions]="getFiltered(field.controlName)"
|
||||
(completeMethod)="filterItems($event, field.controlName)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp(field.controlName, $event)"
|
||||
(onSelect)="onAutoCompleteSelect(field.controlName, $event)">
|
||||
</p-autoComplete>
|
||||
</div>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
<div class="autocomplete-container">
|
||||
<p-autoComplete
|
||||
[ngModel]="fetchedMetadata[field.fetchedKey] ?? []"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
[disabled]="true"
|
||||
[multiple]="true" [typeahead]="false" [dropdown]="false" [forceSelection]="false" class="autocomplete-full-width">
|
||||
</p-autoComplete>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="transfer-btn"
|
||||
[class.saved]="isValueSaved('thumbnailUrl')"
|
||||
[class.copied]="isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl']"
|
||||
[class.reset]="isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']"
|
||||
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
|
||||
(mouseenter)="onMouseEnter('thumbnailUrl')"
|
||||
(mouseleave)="onMouseLeave('thumbnailUrl')"
|
||||
>
|
||||
<i [class]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
|
||||
</button>
|
||||
|
||||
<div class="field-side fetched cover-side">
|
||||
<span class="cover-label mobile-only">Fetched</span>
|
||||
<div class="cover-wrapper">
|
||||
<p-image
|
||||
class="cover-image"
|
||||
[src]="fetchedMetadata.thumbnailUrl!"
|
||||
alt="Fetched cover"
|
||||
appendTo="body"
|
||||
lazyLoad
|
||||
[preview]="true"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@for (field of metadataDescription; track field) {
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
<!-- Mobile layout -->
|
||||
<div class="mobile-field-row mobile-only">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success" size="small"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn" size="small"></p-button>
|
||||
}
|
||||
<textarea rows="3" pTextarea id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"></textarea>
|
||||
</div>
|
||||
<div class="mobile-field-row mobile-only">
|
||||
<textarea rows="3" pInputText [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input fetched-input" readonly></textarea>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-up')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
size="small"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
</div>
|
||||
<!-- Desktop layout -->
|
||||
<div class="desktop-only desktop-field-row">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
<textarea rows="3" pTextarea formControlName="{{field.controlName}}" class="input"></textarea>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
<textarea rows="3" pInputText [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input" readonly></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Basic Information Section -->
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
<span>Basic Information</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
@for (field of metadataFieldsBottom; track field) {
|
||||
<div class="form-row">
|
||||
<label for="{{field.controlName}}" class="label">{{ field.label }}</label>
|
||||
<div class="input-container">
|
||||
<!-- Mobile layout -->
|
||||
<div class="mobile-field-row mobile-only">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success" size="small"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn" size="small"></p-button>
|
||||
}
|
||||
<input pInputText pSize="small" id="{{field.controlName}}" formControlName="{{field.controlName}}" class="input"/>
|
||||
<div class="section-content">
|
||||
@for (field of metadataFieldsTop; track field) {
|
||||
<div class="field-row">
|
||||
<label class="field-label">{{ field.label }}</label>
|
||||
<div class="field-content">
|
||||
<div class="field-side current">
|
||||
<button
|
||||
type="button"
|
||||
class="lock-btn"
|
||||
[class.locked]="metadataForm.get(field.lockedKey)?.value"
|
||||
(click)="toggleLock(field.controlName)"
|
||||
>
|
||||
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
|
||||
</button>
|
||||
@if (field.controlName === 'publishedDate') {
|
||||
<input pInputText formControlName="{{field.controlName}}" class="field-input" placeholder="YYYY-MM-DD"/>
|
||||
} @else {
|
||||
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
|
||||
}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="transfer-btn"
|
||||
[class.saved]="isValueSaved(field.controlName)"
|
||||
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
|
||||
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"
|
||||
>
|
||||
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
|
||||
</button>
|
||||
|
||||
<div class="field-side fetched">
|
||||
<input pInputText [value]="fetchedMetadata[field.fetchedKey] ?? ''" class="field-input" readonly/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mobile-field-row mobile-only">
|
||||
<input pInputText pSize="small" [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input fetched-input" readonly/>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-up')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
size="small"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
</div>
|
||||
<!-- Desktop layout -->
|
||||
<div class="desktop-only desktop-field-row">
|
||||
@if (!metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="success"></p-button>
|
||||
}
|
||||
@if (metadataForm.get(field.lockedKey)?.value) {
|
||||
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock(field.controlName)" severity="warn"></p-button>
|
||||
}
|
||||
<input pInputText pSize="small" formControlName="{{field.controlName}}" class="input"/>
|
||||
<p-button
|
||||
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"
|
||||
[outlined]="true"
|
||||
[ngClass]="
|
||||
{
|
||||
'green-outlined-button': isValueSaved(field.controlName),
|
||||
'yellow-outlined-button': isValueCopied(field.controlName) && !hoveredFields[field.controlName],
|
||||
'red-outlined-button': isValueCopied(field.controlName) && hoveredFields[field.controlName]
|
||||
}"
|
||||
class="arrow-button"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"/>
|
||||
<input pInputText pSize="small" [value]="fetchedMetadata[field.fetchedKey] ?? null" class="input" readonly/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="metadata-header desktop-only">
|
||||
<p class="metadata-header-text">Current Metadata</p>
|
||||
<p-button
|
||||
severity="info"
|
||||
icon='pi pi-angle-left'
|
||||
class="button-left"
|
||||
[outlined]="true"
|
||||
pTooltip="Move all missing fields" tooltipPosition="bottom"
|
||||
(onClick)="copyMissing()"></p-button>
|
||||
<p-button
|
||||
severity="info"
|
||||
icon='pi pi-angle-double-left'
|
||||
class="button-double-left"
|
||||
[outlined]="true"
|
||||
pTooltip="Move all fields" tooltipPosition="bottom"
|
||||
(onClick)="copyAll()"></p-button>
|
||||
<p class="metadata-header-text">Fetched Metadata</p>
|
||||
</div>
|
||||
<!-- Tags & Categories Section -->
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-tags"></i>
|
||||
<span>Tags & Categories</span>
|
||||
</div>
|
||||
|
||||
<div class="section-content">
|
||||
@for (field of metadataChips; track field) {
|
||||
<div class="field-row">
|
||||
<label class="field-label">{{ field.label }}</label>
|
||||
<div class="field-content">
|
||||
<div class="field-side current">
|
||||
<button
|
||||
type="button"
|
||||
class="lock-btn"
|
||||
[class.locked]="metadataForm.get(field.lockedKey)?.value"
|
||||
(click)="toggleLock(field.controlName)"
|
||||
>
|
||||
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
|
||||
</button>
|
||||
<p-autoComplete
|
||||
class="chips-input"
|
||||
formControlName="{{field.controlName}}"
|
||||
[multiple]="true"
|
||||
[dropdown]="false"
|
||||
[forceSelection]="false"
|
||||
[showClear]="true"
|
||||
[suggestions]="getFiltered(field.controlName)"
|
||||
(completeMethod)="filterItems($event, field.controlName)"
|
||||
(onKeyUp)="onAutoCompleteKeyUp(field.controlName, $event)"
|
||||
(onSelect)="onAutoCompleteSelect(field.controlName, $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="transfer-btn"
|
||||
[class.saved]="isValueSaved(field.controlName)"
|
||||
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
|
||||
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"
|
||||
>
|
||||
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
|
||||
</button>
|
||||
|
||||
<div class="field-side fetched">
|
||||
<p-autoComplete
|
||||
[ngModel]="fetchedMetadata[field.fetchedKey] ?? []"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
[disabled]="true"
|
||||
[multiple]="true"
|
||||
[typeahead]="false"
|
||||
[dropdown]="false"
|
||||
[forceSelection]="false"
|
||||
class="chips-input readonly"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Description Section -->
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-align-left"></i>
|
||||
<span>Description</span>
|
||||
</div>
|
||||
|
||||
<div class="section-content">
|
||||
@for (field of metadataDescription; track field) {
|
||||
<div class="field-row textarea-row">
|
||||
<label class="field-label">{{ field.label }}</label>
|
||||
<div class="field-content">
|
||||
<div class="field-side current">
|
||||
<button
|
||||
type="button"
|
||||
class="lock-btn"
|
||||
[class.locked]="metadataForm.get(field.lockedKey)?.value"
|
||||
(click)="toggleLock(field.controlName)"
|
||||
>
|
||||
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
|
||||
</button>
|
||||
<textarea pTextarea formControlName="{{field.controlName}}" class="field-textarea" rows="4"></textarea>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="transfer-btn"
|
||||
[class.saved]="isValueSaved(field.controlName)"
|
||||
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
|
||||
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"
|
||||
>
|
||||
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
|
||||
</button>
|
||||
|
||||
<div class="field-side fetched">
|
||||
<textarea pTextarea [value]="fetchedMetadata[field.fetchedKey] ?? ''" class="field-textarea" rows="4" readonly></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Additional Details Section -->
|
||||
@if (metadataFieldsBottom.length > 0) {
|
||||
<section class="form-section">
|
||||
<div class="section-header">
|
||||
<i class="pi pi-list"></i>
|
||||
<span>Additional Details</span>
|
||||
</div>
|
||||
|
||||
<div class="section-content">
|
||||
@for (field of metadataFieldsBottom; track field) {
|
||||
<div class="field-row">
|
||||
<label class="field-label">{{ field.label }}</label>
|
||||
<div class="field-content">
|
||||
<div class="field-side current">
|
||||
<button
|
||||
type="button"
|
||||
class="lock-btn"
|
||||
[class.locked]="metadataForm.get(field.lockedKey)?.value"
|
||||
(click)="toggleLock(field.controlName)"
|
||||
>
|
||||
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
|
||||
</button>
|
||||
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="transfer-btn"
|
||||
[class.saved]="isValueSaved(field.controlName)"
|
||||
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
|
||||
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
|
||||
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
|
||||
(mouseenter)="onMouseEnter(field.controlName)"
|
||||
(mouseleave)="onMouseLeave(field.controlName)"
|
||||
>
|
||||
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
|
||||
</button>
|
||||
|
||||
<div class="field-side fetched">
|
||||
<input pInputText [value]="fetchedMetadata[field.fetchedKey] ?? ''" class="field-input" readonly/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
|
||||
|
||||
@if (!reviewMode) {
|
||||
<div class="form-footer">
|
||||
<p-divider></p-divider>
|
||||
<!-- Mobile footer -->
|
||||
<div class="footer-buttons mobile-only">
|
||||
<p-button icon="pi pi-arrow-left" label="Metadata List" outlined severity="info" (onClick)="goBackClick()"></p-button>
|
||||
<div class="footer-buttons-right">
|
||||
<p-button icon="pi pi-lock-open" [outlined]="true" severity="success" pTooltip="Unlock All" (onClick)="unlockAll()"></p-button>
|
||||
<p-button icon="pi pi-lock" [outlined]="true" severity="warn" pTooltip="Lock All" (onClick)="lockAll()"></p-button>
|
||||
<p-button
|
||||
[icon]="isSaving ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
|
||||
[loading]="isSaving"
|
||||
[disabled]="isSaving"
|
||||
label="Save"
|
||||
type="submit"></p-button>
|
||||
</div>
|
||||
<footer class="dialog-footer">
|
||||
<div class="footer-left">
|
||||
<p-button
|
||||
label="Back to List"
|
||||
icon="pi pi-arrow-left"
|
||||
severity="info"
|
||||
[outlined]="true"
|
||||
(onClick)="goBackClick()"
|
||||
/>
|
||||
</div>
|
||||
<!-- Desktop footer -->
|
||||
<div class="footer-buttons desktop-only">
|
||||
<p-button label="To Metadata List" icon="pi pi-arrow-left" severity="info" (onClick)="goBackClick()"></p-button>
|
||||
<div class="footer-buttons-right">
|
||||
<p-button label="Unlock All" icon="pi pi-lock-open" [outlined]="true" severity="success" (onClick)="unlockAll()"></p-button>
|
||||
<p-button label="Lock All" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()"></p-button>
|
||||
<p-divider layout="vertical"/>
|
||||
<p-button
|
||||
label="Save"
|
||||
[icon]="isSaving ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
|
||||
[loading]="isSaving"
|
||||
[disabled]="isSaving"
|
||||
type="submit"></p-button>
|
||||
</div>
|
||||
<div class="footer-right">
|
||||
<p-button
|
||||
icon="pi pi-lock-open"
|
||||
severity="success"
|
||||
[outlined]="true"
|
||||
pTooltip="Unlock all fields"
|
||||
tooltipPosition="top"
|
||||
(onClick)="unlockAll()"
|
||||
/>
|
||||
<p-button
|
||||
icon="pi pi-lock"
|
||||
severity="warn"
|
||||
[outlined]="true"
|
||||
pTooltip="Lock all fields"
|
||||
tooltipPosition="top"
|
||||
(onClick)="lockAll()"
|
||||
/>
|
||||
<div class="footer-divider"></div>
|
||||
<p-button
|
||||
label="Save Changes"
|
||||
[icon]="isSaving ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
|
||||
[loading]="isSaving"
|
||||
[disabled]="isSaving"
|
||||
severity="primary"
|
||||
type="submit"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
}
|
||||
</form>
|
||||
}
|
||||
|
||||
+425
-201
@@ -1,21 +1,12 @@
|
||||
.form-container {
|
||||
.metadata-picker {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background: var(--card-background);
|
||||
animation: fadeIn 0.3s ease-in;
|
||||
}
|
||||
|
||||
.form-content {
|
||||
flex-grow: 1;
|
||||
overflow: auto;
|
||||
padding: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
padding: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Visibility utilities
|
||||
.mobile-only {
|
||||
display: flex;
|
||||
@@ -33,254 +24,462 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Desktop header
|
||||
.metadata-header {
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding-bottom: 0.75rem;
|
||||
padding-left: 9.25rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.metadata-header-text {
|
||||
margin-left: 0.75rem;
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
// Mobile header
|
||||
.metadata-header-mobile {
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.5rem 0;
|
||||
margin-bottom: 0.5rem;
|
||||
border-bottom: 1px solid var(--p-surface-700);
|
||||
}
|
||||
|
||||
.button-left {
|
||||
padding-left: 3rem;
|
||||
padding-right: 0.5rem;
|
||||
}
|
||||
|
||||
.button-double-left {
|
||||
padding-left: 0.5rem;
|
||||
padding-right: 2rem;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
// Body
|
||||
.dialog-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 0.75rem;
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--p-surface-700);
|
||||
gap: 1.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
padding: 0;
|
||||
border: none;
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--border-color);
|
||||
border-radius: 3px;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.thumbnail-row {
|
||||
@media (max-width: 767px) {
|
||||
// Column Headers - mirrors field-row structure for alignment (desktop only)
|
||||
.column-headers {
|
||||
display: none;
|
||||
align-items: center;
|
||||
padding: 0.875rem 1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
background: var(--overlay-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
// Spacer to match field-label width
|
||||
&::before {
|
||||
content: '';
|
||||
min-width: 120px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.column-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border: none;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
}
|
||||
gap: 0.625rem;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
flex: 1;
|
||||
|
||||
.thumbnail-container {
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: row;
|
||||
i {
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
&.current {
|
||||
color: var(--primary-color);
|
||||
justify-content: flex-end;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
&.fetched {
|
||||
color: var(--p-blue-400);
|
||||
justify-content: flex-start;
|
||||
padding-left: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.column-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
margin-left: 0.75rem;
|
||||
margin-right: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.mobile-thumbnail-row {
|
||||
// Sections
|
||||
.form-section {
|
||||
.section-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
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-content {
|
||||
background: var(--overlay-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
// Cover Image
|
||||
.cover-wrapper {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.cover-image {
|
||||
width: 100px;
|
||||
height: 150px;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
|
||||
|
||||
@media (min-width: 768px) {
|
||||
width: 120px;
|
||||
height: 180px;
|
||||
}
|
||||
|
||||
::ng-deep img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
}
|
||||
|
||||
.lock-badge {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.375rem;
|
||||
width: 100%;
|
||||
}
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
background: var(--p-green-500);
|
||||
border: 2px solid var(--card-background);
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
.label {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
margin-bottom: 0.375rem;
|
||||
font-weight: 600;
|
||||
font-size: 0.8rem;
|
||||
color: var(--p-text-color);
|
||||
i {
|
||||
font-size: 0.625rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
width: 8rem;
|
||||
margin-bottom: 0;
|
||||
font-weight: normal;
|
||||
font-size: 1rem;
|
||||
&.locked {
|
||||
background: var(--p-orange-500);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
.input-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
gap: 0.25rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Mobile field rows - tight two-row layout
|
||||
.mobile-field-row {
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
|
||||
.input {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.autocomplete-container {
|
||||
flex: 1;
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.mobile-field-label {
|
||||
font-size: 0.65rem;
|
||||
.cover-label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
color: var(--p-primary-color);
|
||||
min-width: 3rem;
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
|
||||
&.muted {
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
// Field Rows
|
||||
.field-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.875rem 1rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Desktop field row
|
||||
.desktop-field-row {
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
// Cover field row specific styles
|
||||
.cover-field-row {
|
||||
padding: 1.25rem 1rem;
|
||||
|
||||
.field-label {
|
||||
text-align: center;
|
||||
margin-bottom: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
text-align: left;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.field-content {
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
gap: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
// On mobile, center covers and show labels
|
||||
.field-side {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
flex-direction: row;
|
||||
}
|
||||
}
|
||||
|
||||
// Position covers towards the arrow on desktop only
|
||||
@media (min-width: 768px) {
|
||||
padding: 1.5rem 1rem;
|
||||
|
||||
.field-side.current {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.field-side.fetched {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.thumbnail-row .desktop-field-row {
|
||||
justify-content: center;
|
||||
.field-label {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-color);
|
||||
min-width: 100px;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
min-width: 120px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.input {
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
margin: 0;
|
||||
.field-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
flex: 1;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
width: 50%;
|
||||
margin: 0 1rem;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.fetched-input {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.field-side {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
.autocomplete-container {
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
&.fetched {
|
||||
.field-input,
|
||||
.field-textarea,
|
||||
.chips-input {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.autocomplete-full-width {
|
||||
.lock-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
background: var(--p-green-500);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
i {
|
||||
font-size: 0.75rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
&.locked {
|
||||
background: var(--p-orange-500);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
}
|
||||
|
||||
.field-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.thumbnail {
|
||||
width: 5rem;
|
||||
height: 7rem;
|
||||
border-radius: 0.375rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
|
||||
.field-textarea {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
width: 15.625rem;
|
||||
height: 21.875rem;
|
||||
margin-left: 2.5rem;
|
||||
margin-right: 2.5rem;
|
||||
.chips-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
|
||||
&.readonly {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.arrow-button {
|
||||
.textarea-row {
|
||||
.field-content {
|
||||
@media (min-width: 768px) {
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.field-side {
|
||||
@media (min-width: 768px) {
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.lock-btn {
|
||||
@media (min-width: 768px) {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.transfer-btn {
|
||||
@media (min-width: 768px) {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Transfer Button
|
||||
.transfer-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
i {
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-secondary-color);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: var(--primary-color);
|
||||
|
||||
i {
|
||||
color: var(--primary-contrast-color);
|
||||
}
|
||||
}
|
||||
|
||||
&.saved {
|
||||
border-color: var(--p-green-500);
|
||||
background: var(--p-green-500);
|
||||
|
||||
i {
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
|
||||
&.copied {
|
||||
border-color: var(--p-yellow-500);
|
||||
background: rgba(234, 179, 8, 0.15);
|
||||
|
||||
i {
|
||||
color: var(--p-yellow-500);
|
||||
}
|
||||
}
|
||||
|
||||
&.reset {
|
||||
border-color: var(--p-red-500);
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
|
||||
i {
|
||||
color: var(--p-red-500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Footer
|
||||
.dialog-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.25rem;
|
||||
background: var(--overlay-background);
|
||||
border-top: 1px solid var(--border-color);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.yellow-outlined-button {
|
||||
--p-button-outlined-primary-border-color: yellow;
|
||||
--p-button-outlined-primary-color: yellow;
|
||||
}
|
||||
|
||||
.green-outlined-button {
|
||||
--p-button-outlined-primary-border-color: limegreen;
|
||||
--p-button-outlined-primary-color: limegreen;
|
||||
}
|
||||
|
||||
.red-outlined-button {
|
||||
--p-button-outlined-primary-border-color: #E32636;
|
||||
--p-button-outlined-primary-color: #E32636;
|
||||
}
|
||||
|
||||
.form-footer {
|
||||
margin-top: auto;
|
||||
padding: 0 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-buttons {
|
||||
padding-top: 1rem;
|
||||
|
||||
&.mobile-only {
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
&.desktop-only {
|
||||
justify-content: space-between;
|
||||
padding: 1rem 0.5rem 0;
|
||||
}
|
||||
}
|
||||
|
||||
.footer-buttons-right {
|
||||
.footer-left {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.desktop-only & {
|
||||
gap: 1rem;
|
||||
.footer-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.footer-divider {
|
||||
width: 1px;
|
||||
height: 24px;
|
||||
background: var(--border-color);
|
||||
margin: 0 0.25rem;
|
||||
}
|
||||
|
||||
// AutoComplete overrides
|
||||
::ng-deep .p-autocomplete {
|
||||
width: 100% !important;
|
||||
|
||||
.p-autocomplete-multiple-container {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .p-inputchips {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
// Animation
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
@@ -289,3 +488,28 @@
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Mobile optimizations
|
||||
@media (max-width: 767px) {
|
||||
.dialog-body {
|
||||
padding: 1rem;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
flex-direction: column;
|
||||
padding: 0.875rem 1rem;
|
||||
gap: 0.75rem;
|
||||
|
||||
.footer-left,
|
||||
.footer-right {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.field-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-4
@@ -4,8 +4,7 @@ import {MessageService} from 'primeng/api';
|
||||
import {Button} from 'primeng/button';
|
||||
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {AsyncPipe, NgClass} from '@angular/common';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {Observable} from 'rxjs';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
@@ -29,9 +28,7 @@ import {ALL_METADATA_FIELDS, getArrayFields, getBottomFields, getTextareaFields,
|
||||
Button,
|
||||
FormsModule,
|
||||
InputText,
|
||||
Divider,
|
||||
ReactiveFormsModule,
|
||||
NgClass,
|
||||
Tooltip,
|
||||
AsyncPipe,
|
||||
Textarea,
|
||||
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
<p-tabs lazy class="custom-p-tabs" [value]="defaultTabValue" scrollable>
|
||||
<p-tablist>
|
||||
@if (bookInSeries.length > 1) {
|
||||
<p-tab value="series">
|
||||
<i class="pi pi-ethereum"></i> More in Series
|
||||
</p-tab>
|
||||
}
|
||||
<p-tab value="similar">
|
||||
<i class="pi pi-bookmark"></i> Similar Books
|
||||
</p-tab>
|
||||
<p-tab value="files">
|
||||
<i class="pi pi-folder-open"></i> Files
|
||||
</p-tab>
|
||||
<p-tab value="notes">
|
||||
<i class="pi pi-pen-to-square"></i> Notes
|
||||
</p-tab>
|
||||
<p-tab value="sessions">
|
||||
<i class="pi pi-clock"></i> Reading Sessions
|
||||
</p-tab>
|
||||
<p-tab value="reviews">
|
||||
<i class="pi pi-comments"></i> Reviews
|
||||
</p-tab>
|
||||
</p-tablist>
|
||||
<p-tabpanels>
|
||||
<p-tabpanel value="series">
|
||||
<ng-template #content>
|
||||
<div class="tab-content">
|
||||
@if (bookInSeries.length > 1) {
|
||||
<div class="dashboard-scroller-infinite" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" [horizontal]="true">
|
||||
@for (bookInSeriesItem of bookInSeries; track bookInSeriesItem) {
|
||||
@if (bookInSeriesItem.id !== book.id) {
|
||||
<div class="dashboard-scroller-card">
|
||||
<app-book-card-lite-component [book]="bookInSeriesItem" [showSeriesNumber]="true" [isActive]="bookInSeriesItem.id === book.id"></app-book-card-lite-component>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel value="similar">
|
||||
<ng-template #content>
|
||||
<div class="tab-content">
|
||||
@if (recommendedBooks.length > 0) {
|
||||
<div class="dashboard-scroller-infinite" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" [horizontal]="true">
|
||||
@for (recBook of recommendedBooks; track recBook.book.id) {
|
||||
<div class="dashboard-scroller-card">
|
||||
<app-book-card-lite-component [book]="recBook.book"></app-book-card-lite-component>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel value="notes">
|
||||
<ng-template #content>
|
||||
<app-book-notes-component [bookId]="book.id"></app-book-notes-component>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel value="sessions">
|
||||
<ng-template #content>
|
||||
<app-book-reading-sessions [bookId]="book.id"></app-book-reading-sessions>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel value="reviews">
|
||||
<ng-template #content>
|
||||
<app-book-reviews [bookId]="book.id"></app-book-reviews>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel value="files">
|
||||
<ng-template #content>
|
||||
<div class="files-tab-content">
|
||||
@if (isPhysicalBook()) {
|
||||
<div class="empty-state">
|
||||
<i class="pi pi-book empty-state-icon"></i>
|
||||
<h4 class="empty-state-title">Physical Book</h4>
|
||||
<p class="empty-state-message">This is a physical book. No digital files are associated with this book.</p>
|
||||
<p class="empty-state-hint">You can upload a digital version using the "Upload File" option in the menu.</p>
|
||||
</div>
|
||||
} @else {
|
||||
@if (hasMultipleFiles(book)) {
|
||||
<div class="files-section download-all-section">
|
||||
<p-button
|
||||
label="Download All ({{ getTotalFileCount(book) }} files)"
|
||||
icon="pi pi-download"
|
||||
severity="info"
|
||||
outlined
|
||||
(onClick)="downloadAll(book)"
|
||||
pTooltip="Download all files as a ZIP archive"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
@if (book.primaryFile) {
|
||||
<div class="files-section">
|
||||
<h4 class="files-section-title">Primary File</h4>
|
||||
<div class="files-list">
|
||||
<div class="file-item primary-file">
|
||||
<div class="file-info">
|
||||
<span class="file-type-badge" [style.background-color]="getFileTypeBgColor(book.primaryFile.extension)">
|
||||
{{ book.primaryFile.extension | uppercase }}
|
||||
</span>
|
||||
<span class="file-name" [pTooltip]="book.primaryFile.filePath" tooltipPosition="top">{{ book.primaryFile.fileName }}</span>
|
||||
<span class="file-size">{{ getFileSizeInMB(book.primaryFile) }}</span>
|
||||
</div>
|
||||
<div class="file-actions">
|
||||
@if (book.primaryFile.bookType === 'PDF') {
|
||||
<p-button
|
||||
icon="pi pi-book"
|
||||
size="small"
|
||||
text
|
||||
severity="primary"
|
||||
pTooltip="Read"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id)">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-play"
|
||||
size="small"
|
||||
text
|
||||
severity="info"
|
||||
pTooltip="Streaming Reader"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id, 'pdf-streaming')">
|
||||
</p-button>
|
||||
} @else if (book.primaryFile.bookType === 'EPUB') {
|
||||
<p-button
|
||||
icon="pi pi-book"
|
||||
size="small"
|
||||
text
|
||||
severity="primary"
|
||||
pTooltip="Read"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id)">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-play"
|
||||
size="small"
|
||||
text
|
||||
severity="info"
|
||||
pTooltip="Streaming Reader"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id, 'epub-streaming')">
|
||||
</p-button>
|
||||
} @else if (book.primaryFile.bookType && ['FB2', 'MOBI', 'AZW3', 'CBX'].includes(book.primaryFile.bookType)) {
|
||||
<p-button
|
||||
icon="pi pi-book"
|
||||
size="small"
|
||||
text
|
||||
severity="primary"
|
||||
pTooltip="Read"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id)">
|
||||
</p-button>
|
||||
} @else if (book.primaryFile.bookType === 'AUDIOBOOK') {
|
||||
<p-button
|
||||
icon="pi pi-play"
|
||||
size="small"
|
||||
text
|
||||
severity="primary"
|
||||
pTooltip="Play"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id)">
|
||||
</p-button>
|
||||
}
|
||||
<p-button
|
||||
icon="pi pi-download"
|
||||
size="small"
|
||||
text
|
||||
severity="success"
|
||||
pTooltip="Download"
|
||||
tooltipPosition="top"
|
||||
(onClick)="download(book)">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
text
|
||||
severity="danger"
|
||||
pTooltip="Delete"
|
||||
tooltipPosition="top"
|
||||
(onClick)="deleteFile(book, book.primaryFile!.id, book.primaryFile!.fileName || 'file', true)">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (book.alternativeFormats && book.alternativeFormats.length > 0) {
|
||||
<div class="files-section">
|
||||
<h4 class="files-section-title">Alternative Formats</h4>
|
||||
<div class="files-list">
|
||||
@for (format of book.alternativeFormats; track format.id) {
|
||||
<div class="file-item">
|
||||
<div class="file-info">
|
||||
<span class="file-type-badge" [style.background-color]="getFileTypeBgColor(format.extension)">
|
||||
{{ format.extension | uppercase }}
|
||||
</span>
|
||||
<span class="file-name" [pTooltip]="format.filePath" tooltipPosition="top">{{ format.fileName }}</span>
|
||||
<span class="file-size">{{ getFileSizeInMB(format) }}</span>
|
||||
</div>
|
||||
<div class="file-actions">
|
||||
@if (format.bookType === 'PDF' || format.bookType === 'EPUB') {
|
||||
<p-button
|
||||
icon="pi pi-book"
|
||||
size="small"
|
||||
text
|
||||
severity="primary"
|
||||
pTooltip="Read"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id, undefined, format.bookType)">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-play"
|
||||
size="small"
|
||||
text
|
||||
severity="info"
|
||||
pTooltip="Streaming Reader"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id, format.bookType === 'PDF' ? 'pdf-streaming' : 'epub-streaming', format.bookType)">
|
||||
</p-button>
|
||||
} @else if (format.bookType && ['FB2', 'MOBI', 'AZW3', 'CBX'].includes(format.bookType)) {
|
||||
<p-button
|
||||
icon="pi pi-book"
|
||||
size="small"
|
||||
text
|
||||
severity="primary"
|
||||
pTooltip="Read"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id, undefined, format.bookType)">
|
||||
</p-button>
|
||||
} @else if (format.bookType === 'AUDIOBOOK') {
|
||||
<p-button
|
||||
icon="pi pi-play"
|
||||
size="small"
|
||||
text
|
||||
severity="primary"
|
||||
pTooltip="Play"
|
||||
tooltipPosition="top"
|
||||
(onClick)="read(book.id, undefined, format.bookType)">
|
||||
</p-button>
|
||||
}
|
||||
<p-button
|
||||
icon="pi pi-download"
|
||||
size="small"
|
||||
text
|
||||
severity="success"
|
||||
pTooltip="Download"
|
||||
tooltipPosition="top"
|
||||
(onClick)="downloadAdditionalFile(book, format.id)">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
text
|
||||
severity="danger"
|
||||
pTooltip="Delete"
|
||||
tooltipPosition="top"
|
||||
(onClick)="deleteFile(book, format.id, format.fileName || 'file', false)">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@if (book.supplementaryFiles && book.supplementaryFiles.length > 0) {
|
||||
<div class="files-section">
|
||||
<h4 class="files-section-title">Supplementary Files</h4>
|
||||
<div class="files-list">
|
||||
@for (file of book.supplementaryFiles; track file.id) {
|
||||
<div class="file-item">
|
||||
<div class="file-info">
|
||||
<i [class]="getFileIcon(getFileExtension(file.filePath))" class="file-icon"></i>
|
||||
<span class="file-name" [pTooltip]="file.filePath" tooltipPosition="top">{{ file.fileName }}</span>
|
||||
<span class="file-size">{{ getFileSizeInMB(file) }}</span>
|
||||
</div>
|
||||
<div class="file-actions">
|
||||
<p-button
|
||||
icon="pi pi-download"
|
||||
size="small"
|
||||
text
|
||||
severity="success"
|
||||
pTooltip="Download"
|
||||
tooltipPosition="top"
|
||||
(onClick)="downloadAdditionalFile(book, file.id)">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
size="small"
|
||||
text
|
||||
severity="danger"
|
||||
pTooltip="Delete"
|
||||
tooltipPosition="top"
|
||||
(onClick)="deleteSupplementary(book.id, file.id, file.fileName || 'file')">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
.custom-p-tabs ::ng-deep .p-tabpanels {
|
||||
padding: 0.5rem 0 0 0 !important;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scroll-snap-type: x mandatory;
|
||||
padding: 0.5rem;
|
||||
gap: 1rem;
|
||||
width: 100%;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--border-color) transparent;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar {
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar-thumb {
|
||||
background: var(--border-color);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--text-secondary-color);
|
||||
}
|
||||
|
||||
.dashboard-scroller-card {
|
||||
width: 115px;
|
||||
flex-basis: 115px;
|
||||
flex-shrink: 0;
|
||||
flex-grow: 0;
|
||||
scroll-snap-align: start;
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
position: relative;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dashboard-scroller-card:hover {
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
.dashboard-scroller-card:hover::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.dashboard-scroller-card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -4px;
|
||||
left: 10%;
|
||||
right: 10%;
|
||||
height: 4px;
|
||||
background: linear-gradient(90deg, transparent, var(--primary-color), transparent);
|
||||
border-radius: 50%;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
filter: blur(4px);
|
||||
}
|
||||
|
||||
// Files tab styles
|
||||
.files-tab-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.files-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
|
||||
&.download-all-section {
|
||||
align-items: flex-end;
|
||||
margin-bottom: -1.5rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.files-section-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
margin: 0;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.files-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.file-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.75rem;
|
||||
background: var(--card-background);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 0.5rem;
|
||||
transition: background 0.2s ease, border-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--highlight-background);
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
|
||||
&.primary-file {
|
||||
border-left: 3px solid var(--primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.file-type-badge {
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
font-size: 1.25rem;
|
||||
color: var(--text-color-secondary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-color);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.file-size {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-color-secondary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.file-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
::ng-deep .p-button-sm {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
|
||||
.p-button-icon {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Empty state for physical books
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem 1rem;
|
||||
text-align: center;
|
||||
color: var(--text-color-secondary);
|
||||
}
|
||||
|
||||
.empty-state-icon {
|
||||
font-size: 3rem;
|
||||
color: var(--book-type-physical-color);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.empty-state-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
margin: 0 0 0.5rem 0;
|
||||
}
|
||||
|
||||
.empty-state-message {
|
||||
font-size: 0.9rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.empty-state-hint {
|
||||
font-size: 0.8rem;
|
||||
font-style: italic;
|
||||
margin: 0;
|
||||
opacity: 0.8;
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
import {Component, EventEmitter, Input, Output} from '@angular/core';
|
||||
import {UpperCasePipe} from '@angular/common';
|
||||
import {Book, BookRecommendation, BookType, FileInfo} from '../../../../../book/model/book.model';
|
||||
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
import {BookCardLiteComponent} from '../../../../../book/components/book-card-lite/book-card-lite-component';
|
||||
import {BookReviewsComponent} from '../../../../../book/components/book-reviews/book-reviews.component';
|
||||
import {BookNotesComponent} from '../../../../../book/components/book-notes/book-notes-component';
|
||||
import {BookReadingSessionsComponent} from '../../book-reading-sessions/book-reading-sessions.component';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
|
||||
export interface ReadEvent {
|
||||
bookId: number;
|
||||
reader?: 'pdf-streaming' | 'epub-streaming';
|
||||
bookType?: BookType;
|
||||
}
|
||||
|
||||
export interface DownloadEvent {
|
||||
book: Book;
|
||||
}
|
||||
|
||||
export interface DownloadAdditionalFileEvent {
|
||||
book: Book;
|
||||
fileId: number;
|
||||
}
|
||||
|
||||
export interface DownloadAllFilesEvent {
|
||||
book: Book;
|
||||
}
|
||||
|
||||
export interface DeleteBookFileEvent {
|
||||
book: Book;
|
||||
fileId: number;
|
||||
fileName: string;
|
||||
isPrimary: boolean;
|
||||
isOnlyFormat: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteSupplementaryFileEvent {
|
||||
bookId: number;
|
||||
fileId: number;
|
||||
fileName: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-tabs',
|
||||
standalone: true,
|
||||
imports: [
|
||||
Tab,
|
||||
TabList,
|
||||
TabPanel,
|
||||
TabPanels,
|
||||
Tabs,
|
||||
InfiniteScrollDirective,
|
||||
BookCardLiteComponent,
|
||||
BookReviewsComponent,
|
||||
BookNotesComponent,
|
||||
BookReadingSessionsComponent,
|
||||
Button,
|
||||
Tooltip,
|
||||
UpperCasePipe
|
||||
],
|
||||
templateUrl: './metadata-tabs.component.html',
|
||||
styleUrl: './metadata-tabs.component.scss'
|
||||
})
|
||||
export class MetadataTabsComponent {
|
||||
@Input() book!: Book;
|
||||
@Input() bookInSeries: Book[] = [];
|
||||
@Input() recommendedBooks: BookRecommendation[] = [];
|
||||
|
||||
@Output() readBook = new EventEmitter<ReadEvent>();
|
||||
@Output() downloadBook = new EventEmitter<DownloadEvent>();
|
||||
@Output() downloadFile = new EventEmitter<DownloadAdditionalFileEvent>();
|
||||
@Output() downloadAllFiles = new EventEmitter<DownloadAllFilesEvent>();
|
||||
@Output() deleteBookFile = new EventEmitter<DeleteBookFileEvent>();
|
||||
@Output() deleteSupplementaryFile = new EventEmitter<DeleteSupplementaryFileEvent>();
|
||||
|
||||
get defaultTabValue(): string {
|
||||
return this.bookInSeries && this.bookInSeries.length > 1 ? 'series' : 'similar';
|
||||
}
|
||||
|
||||
read(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming', bookType?: BookType): void {
|
||||
this.readBook.emit({ bookId, reader, bookType });
|
||||
}
|
||||
|
||||
download(book: Book): void {
|
||||
this.downloadBook.emit({ book });
|
||||
}
|
||||
|
||||
downloadAdditionalFile(book: Book, fileId: number): void {
|
||||
this.downloadFile.emit({ book, fileId });
|
||||
}
|
||||
|
||||
downloadAll(book: Book): void {
|
||||
this.downloadAllFiles.emit({ book });
|
||||
}
|
||||
|
||||
deleteFile(book: Book, fileId: number, fileName: string, isPrimary: boolean): void {
|
||||
const isOnlyFormat = !book.alternativeFormats?.length;
|
||||
this.deleteBookFile.emit({ book, fileId, fileName, isPrimary, isOnlyFormat });
|
||||
}
|
||||
|
||||
deleteSupplementary(bookId: number, fileId: number, fileName: string): void {
|
||||
this.deleteSupplementaryFile.emit({ bookId, fileId, fileName });
|
||||
}
|
||||
|
||||
hasMultipleFiles(book: Book): boolean {
|
||||
const primaryCount = book.primaryFile ? 1 : 0;
|
||||
const altCount = book.alternativeFormats?.length ?? 0;
|
||||
return (primaryCount + altCount) > 1;
|
||||
}
|
||||
|
||||
getTotalFileCount(book: Book): number {
|
||||
const primaryCount = book.primaryFile ? 1 : 0;
|
||||
const altCount = book.alternativeFormats?.length ?? 0;
|
||||
return primaryCount + altCount;
|
||||
}
|
||||
|
||||
getFileSizeInMB(fileInfo: FileInfo | null | undefined): string {
|
||||
const sizeKb = fileInfo?.fileSizeKb;
|
||||
return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-';
|
||||
}
|
||||
|
||||
getFileExtension(filePath?: string): string | null {
|
||||
if (!filePath) return null;
|
||||
const parts = filePath.split('.');
|
||||
if (parts.length < 2) return null;
|
||||
return parts.pop()?.toUpperCase() || null;
|
||||
}
|
||||
|
||||
getFileIcon(fileType: string | null): string {
|
||||
if (!fileType) return 'pi pi-file';
|
||||
switch (fileType.toLowerCase()) {
|
||||
case 'pdf':
|
||||
return 'pi pi-file-pdf';
|
||||
case 'epub':
|
||||
case 'mobi':
|
||||
case 'azw3':
|
||||
return 'pi pi-book';
|
||||
case 'cbz':
|
||||
case 'cbr':
|
||||
case 'cbx':
|
||||
return 'pi pi-image';
|
||||
case 'audiobook':
|
||||
case 'm4b':
|
||||
case 'm4a':
|
||||
case 'mp3':
|
||||
return 'pi pi-headphones';
|
||||
default:
|
||||
return 'pi pi-file';
|
||||
}
|
||||
}
|
||||
|
||||
getFileTypeBgColor(fileType: string | null | undefined): string {
|
||||
if (!fileType) return 'var(--p-gray-500)';
|
||||
const type = fileType.toLowerCase();
|
||||
return `var(--book-type-${type}-color, var(--p-gray-500))`;
|
||||
}
|
||||
|
||||
isPhysicalBook(): boolean {
|
||||
return !this.book?.primaryFile && (!this.book?.alternativeFormats || this.book.alternativeFormats.length === 0);
|
||||
}
|
||||
}
|
||||
+71
-121
@@ -346,18 +346,26 @@
|
||||
</div>
|
||||
|
||||
<div class="metadata-item">
|
||||
<span class="metadata-key">File Type:</span>
|
||||
@if (getFileExtension(book?.filePath)) {
|
||||
<span (click)="goToFileType(book?.filePath)" style="cursor: pointer;">
|
||||
<app-tag size="3xs" variant="pill" [customBgColor]="getFileTypeBgColor(getFileExtension(book?.filePath))" customTextColor="#fff">
|
||||
{{ (getFileExtension(book?.filePath) | uppercase) || '-' }}
|
||||
</app-tag>
|
||||
</span>
|
||||
} @else {
|
||||
<app-tag size="3xs" variant="pill" [customBgColor]="getFileTypeBgColor(getFileExtension(book?.filePath))" customTextColor="#fff">
|
||||
-
|
||||
</app-tag>
|
||||
}
|
||||
<span class="metadata-key">Formats:</span>
|
||||
<span class="metadata-value-group format-tags">
|
||||
@if (getDisplayFormat(book?.primaryFile); as displayFormat) {
|
||||
<span (click)="goToFileType(book?.primaryFile?.filePath)" style="cursor: pointer;" [pTooltip]="'Primary: ' + (book?.primaryFile?.fileName ?? '')" tooltipPosition="top">
|
||||
<app-tag size="3xs" variant="pill" [customBgColor]="getFileTypeBgColor(displayFormat)" customTextColor="#fff">
|
||||
{{ displayFormat }}
|
||||
</app-tag>
|
||||
</span>
|
||||
}
|
||||
@for (formatExt of getUniqueAlternativeFormats(book); track formatExt) {
|
||||
<span (click)="goToFileType('.' + formatExt)" style="cursor: pointer;" [pTooltip]="formatExt" tooltipPosition="top">
|
||||
<app-tag size="3xs" variant="pill" [customBgColor]="getFileTypeBgColor(formatExt)" customTextColor="#fff">
|
||||
{{ formatExt }}
|
||||
</app-tag>
|
||||
</span>
|
||||
}
|
||||
@if (!book?.primaryFile?.filePath && !book?.alternativeFormats?.length) {
|
||||
<app-tag size="3xs" variant="pill" [customBgColor]="'var(--book-type-physical-color)'" customTextColor="#fff">PHYSICAL</app-tag>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="metadata-item">
|
||||
@@ -502,25 +510,29 @@
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="metadata-item">
|
||||
<span class="metadata-key">File Size:</span>
|
||||
@if (book?.fileSizeKb) {
|
||||
<span class="metadata-value metadata-link" (click)="goToFileSizeRange(book?.fileSizeKb!)">
|
||||
{{ getFileSizeInMB(book) }}
|
||||
</span>
|
||||
} @else {
|
||||
<span class="metadata-value">-</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="file-path-section">
|
||||
<span class="metadata-key">File Path:</span>
|
||||
<i class="pi eye-icon" [ngClass]="showFilePath ? 'pi-eye-slash' : 'pi-eye'" (click)="showFilePath = !showFilePath"></i>
|
||||
@if (showFilePath) {
|
||||
<code class="file-path-code">{{ book?.filePath }}</code>
|
||||
@if (hasDigitalFile(book)) {
|
||||
<div class="metadata-item">
|
||||
<span class="metadata-key">File Size:</span>
|
||||
@if (book?.primaryFile?.fileSizeKb) {
|
||||
<span class="metadata-value metadata-link" (click)="goToFileSizeRange(book?.primaryFile?.fileSizeKb!)">
|
||||
{{ formatFileSize(book?.primaryFile) }}
|
||||
</span>
|
||||
} @else {
|
||||
<span class="metadata-value">-</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (hasDigitalFile(book)) {
|
||||
<div class="file-path-section">
|
||||
<span class="metadata-key">File Path:</span>
|
||||
<i class="pi eye-icon" [ngClass]="showFilePath ? 'pi-eye-slash' : 'pi-eye'" (click)="showFilePath = !showFilePath"></i>
|
||||
@if (showFilePath) {
|
||||
<code class="file-path-code">{{ book?.primaryFile?.filePath }}</code>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
@@ -554,34 +566,31 @@
|
||||
</div>
|
||||
<p-divider layout="vertical" class="action-divider"></p-divider>
|
||||
}
|
||||
@if (book!.bookType === 'PDF') {
|
||||
@if (pdfReadMenuItems$ | async; as readItems) {
|
||||
<p-splitbutton label="Read" outlined icon="pi pi-book" [model]="readItems" (onClick)="read(book.id)" severity="primary"/>
|
||||
}
|
||||
}
|
||||
@if (book!.bookType === 'EPUB') {
|
||||
@if (epubReadMenuItems$ | async; as readItems) {
|
||||
<p-splitbutton label="Read" outlined icon="pi pi-book" [model]="readItems" (onClick)="read(book.id)" severity="primary"/>
|
||||
}
|
||||
}
|
||||
@if (book!.bookType !== 'PDF' && book!.bookType !== 'EPUB') {
|
||||
<p-button label="Read" outlined icon="pi pi-book" (onClick)="read(book?.metadata!.bookId, undefined)" severity="primary"/>
|
||||
}
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<p-button label="Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(book.id)" class="mobile-icon-only"></p-button>
|
||||
@if (userState.user!.permissions.canDownload || userState.user!.permissions.admin) {
|
||||
@if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) {
|
||||
@if (downloadMenuItems$ | async; as downloadItems) {
|
||||
<p-splitbutton label="Download" icon="pi pi-download" [model]="downloadItems" (onClick)="download(book)" severity="success" outlined class="mobile-icon-only"/>
|
||||
@if (hasDigitalFile(book)) {
|
||||
@if (readMenuItems$ | async; as readItems) {
|
||||
@if (readItems.length > 0) {
|
||||
<p-splitbutton [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" [model]="readItems" (onClick)="read(book.id)" outlined severity="primary" class="read-button-responsive"/>
|
||||
} @else {
|
||||
<p-button [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" (onClick)="read(book.id)" outlined severity="primary" class="read-button-responsive"/>
|
||||
}
|
||||
} @else {
|
||||
<p-button label="Download" icon="pi pi-download" severity="success" outlined (onClick)="download(book)" class="mobile-icon-only"></p-button>
|
||||
<p-button [label]="getReadButtonLabel(book)" [icon]="getReadButtonIcon(book)" (onClick)="read(book.id)" outlined severity="primary" class="read-button-responsive"/>
|
||||
}
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
}
|
||||
@if ((userState.user!.permissions.canDownload || userState.user!.permissions.admin) && hasAnyFiles(book)) {
|
||||
@if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) {
|
||||
@if (downloadMenuItems$ | async; as downloadItems) {
|
||||
<p-splitbutton [label]="(getDisplayFormat(book.primaryFile) ?? 'File') + ' · ' + formatFileSize(book.primaryFile)" icon="pi pi-download" [model]="downloadItems" (onClick)="download(book)" severity="success" outlined class="mobile-icon-only"/>
|
||||
}
|
||||
} @else {
|
||||
<p-button [label]="(getDisplayFormat(book.primaryFile) ?? 'File') + ' · ' + formatFileSize(book.primaryFile)" icon="pi pi-download" severity="success" outlined (onClick)="download(book)" class="mobile-icon-only"></p-button>
|
||||
}
|
||||
}
|
||||
@if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) {
|
||||
@if (refreshMenuItems$ | async; as refreshItems) {
|
||||
<p-splitbutton
|
||||
[label]="isAutoFetching ? 'Fetching...' : 'Fetch'"
|
||||
[label]="isAutoFetching ? 'Fetching...' : 'Fetch Metadata'"
|
||||
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
|
||||
[outlined]="true"
|
||||
[model]="refreshItems"
|
||||
@@ -596,7 +605,7 @@
|
||||
}
|
||||
@if (otherItems$ | async; as otherItems) {
|
||||
@if (otherItems.length > 0) {
|
||||
<p-button icon="pi pi-ellipsis-v" outlined severity="danger" (click)="entitymenu.toggle($event)"></p-button>
|
||||
<p-button icon="pi pi-ellipsis-v" outlined severity="info" (click)="entitymenu.toggle($event)"></p-button>
|
||||
<p-tieredMenu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-tieredMenu>
|
||||
}
|
||||
}
|
||||
@@ -625,76 +634,17 @@
|
||||
}
|
||||
</div>
|
||||
|
||||
<p-tabs lazy class="custom-p-tabs" [value]="defaultTabValue" scrollable>
|
||||
<p-tablist>
|
||||
@if (bookInSeries.length > 1) {
|
||||
<p-tab [value]="1">
|
||||
<i class="pi pi-ethereum"></i> More in Series
|
||||
</p-tab>
|
||||
}
|
||||
<p-tab [value]="2">
|
||||
<i class="pi pi-bookmark"></i> Similar Books
|
||||
</p-tab>
|
||||
<p-tab [value]="3">
|
||||
<i class="pi pi-pen-to-square"></i> Notes
|
||||
</p-tab>
|
||||
<p-tab [value]="4">
|
||||
<i class="pi pi-clock"></i> Reading Sessions
|
||||
</p-tab>
|
||||
<p-tab [value]="5">
|
||||
<i class="pi pi-comments"></i> Reviews
|
||||
</p-tab>
|
||||
</p-tablist>
|
||||
<p-tabpanels>
|
||||
<p-tabpanel [value]="1">
|
||||
<ng-template #content>
|
||||
<div class="tab-content">
|
||||
@if (bookInSeries.length > 1) {
|
||||
<div class="dashboard-scroller-infinite" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" [horizontal]="true">
|
||||
@for (bookInSeriesItem of bookInSeries; track bookInSeriesItem) {
|
||||
@if (bookInSeriesItem.id !== book.id) {
|
||||
<div class="dashboard-scroller-card">
|
||||
<app-book-card-lite-component [book]="bookInSeriesItem" [showSeriesNumber]="true" [isActive]="bookInSeriesItem.id === book.id"></app-book-card-lite-component>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="2">
|
||||
<ng-template #content>
|
||||
<div class="tab-content">
|
||||
@if (recommendedBooks.length > 0) {
|
||||
<div class="dashboard-scroller-infinite" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" [horizontal]="true">
|
||||
@for (book of recommendedBooks; track book.book.id) {
|
||||
<div class="dashboard-scroller-card">
|
||||
<app-book-card-lite-component [book]="book.book"></app-book-card-lite-component>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="3">
|
||||
<ng-template #content>
|
||||
<app-book-notes-component [bookId]="book.id"></app-book-notes-component>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="4">
|
||||
<ng-template #content>
|
||||
<app-book-reading-sessions [bookId]="book.id"></app-book-reading-sessions>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="5">
|
||||
<ng-template #content>
|
||||
<app-book-reviews [bookId]="book.id"></app-book-reviews>
|
||||
</ng-template>
|
||||
</p-tabpanel>
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
<app-metadata-tabs
|
||||
[book]="book"
|
||||
[bookInSeries]="bookInSeries"
|
||||
[recommendedBooks]="recommendedBooks"
|
||||
(readBook)="onReadBook($event)"
|
||||
(downloadBook)="onDownloadBook($event)"
|
||||
(downloadFile)="onDownloadFile($event)"
|
||||
(downloadAllFiles)="onDownloadAllFiles($event)"
|
||||
(deleteBookFile)="onDeleteBookFile($event)"
|
||||
(deleteSupplementaryFile)="onDeleteSupplementaryFile($event)">
|
||||
</app-metadata-tabs>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="loading-state">
|
||||
|
||||
+15
-70
@@ -413,6 +413,10 @@
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.format-tags {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.metadata-link {
|
||||
color: var(--primary-text-color);
|
||||
cursor: pointer;
|
||||
@@ -504,6 +508,17 @@
|
||||
min-width: auto !important;
|
||||
padding: 10px !important;
|
||||
}
|
||||
|
||||
::ng-deep .read-button-responsive .p-button-label,
|
||||
::ng-deep .read-button-responsive.p-splitbutton .p-button-label {
|
||||
font-size: 0 !important;
|
||||
}
|
||||
|
||||
::ng-deep .read-button-responsive .p-button-label::after,
|
||||
::ng-deep .read-button-responsive.p-splitbutton .p-button-label::after {
|
||||
content: "Read";
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
}
|
||||
|
||||
.navigation-buttons-desktop {
|
||||
@@ -586,76 +601,6 @@
|
||||
font-size: 0.875rem !important;
|
||||
}
|
||||
|
||||
.custom-p-tabs ::ng-deep .p-tabpanels {
|
||||
padding: 0.5rem 0 0 0 !important;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scroll-snap-type: x mandatory;
|
||||
padding: 0.5rem;
|
||||
gap: 1rem;
|
||||
width: 100%;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--border-color) transparent;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar {
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar-thumb {
|
||||
background: var(--border-color);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.dashboard-scroller-infinite::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--text-secondary-color);
|
||||
}
|
||||
|
||||
.dashboard-scroller-card {
|
||||
width: 115px;
|
||||
flex-basis: 115px;
|
||||
flex-shrink: 0;
|
||||
flex-grow: 0;
|
||||
scroll-snap-align: start;
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
position: relative;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dashboard-scroller-card:hover {
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
.dashboard-scroller-card:hover::after {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.dashboard-scroller-card::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -4px;
|
||||
left: 10%;
|
||||
right: 10%;
|
||||
height: 4px;
|
||||
background: linear-gradient(90deg, transparent, var(--primary-color), transparent);
|
||||
border-radius: 50%;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
filter: blur(4px);
|
||||
}
|
||||
|
||||
.loading-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
+376
-101
@@ -1,11 +1,11 @@
|
||||
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {AsyncPipe, DecimalPipe, NgClass, UpperCasePipe} from '@angular/common';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AsyncPipe, DecimalPipe, NgClass} from '@angular/common';
|
||||
import {combineLatest, Observable} from 'rxjs';
|
||||
import {BookService} from '../../../../book/service/book.service';
|
||||
import {Rating, RatingRateEvent} from 'primeng/rating';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Book, BookMetadata, BookRecommendation, FileInfo, ReadStatus} from '../../../../book/model/book.model';
|
||||
import {Book, BookFile, BookMetadata, BookRecommendation, BookType, FileInfo, ReadStatus} from '../../../../book/model/book.model';
|
||||
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {SplitButton} from 'primeng/splitbutton';
|
||||
@@ -20,36 +20,28 @@ import {MetadataRefreshType} from '../../../model/request/metadata-refresh-type.
|
||||
import {Router} from '@angular/router';
|
||||
import {filter, map, switchMap, take, tap} from 'rxjs/operators';
|
||||
import {Menu} from 'primeng/menu';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
import {BookCardLiteComponent} from '../../../../book/components/book-card-lite/book-card-lite-component';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type';
|
||||
import {DatePicker} from 'primeng/datepicker';
|
||||
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||
import {BookReviewsComponent} from '../../../../book/components/book-reviews/book-reviews.component';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {TieredMenu} from 'primeng/tieredmenu';
|
||||
import {Image} from 'primeng/image';
|
||||
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
|
||||
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
|
||||
import {BookNotesComponent} from '../../../../book/components/book-notes/book-notes-component';
|
||||
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
|
||||
import {
|
||||
fileSizeRanges,
|
||||
matchScoreRanges,
|
||||
pageCountRanges
|
||||
} from '../../../../book/components/book-browser/book-filter/book-filter.component';
|
||||
import {fileSizeRanges, matchScoreRanges, pageCountRanges} from '../../../../book/components/book-browser/book-filter/book-filter.component';
|
||||
import {BookNavigationService} from '../../../../book/service/book-navigation.service';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service';
|
||||
import { BookReadingSessionsComponent } from '../book-reading-sessions/book-reading-sessions.component';
|
||||
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
|
||||
import {DeleteBookFileEvent, DeleteSupplementaryFileEvent, DownloadAdditionalFileEvent, DownloadAllFilesEvent, DownloadEvent, MetadataTabsComponent, ReadEvent} from './metadata-tabs/metadata-tabs.component';
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-viewer',
|
||||
standalone: true,
|
||||
templateUrl: './metadata-viewer.component.html',
|
||||
styleUrl: './metadata-viewer.component.scss',
|
||||
imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent, DatePicker, Tab, TabList, TabPanel, TabPanels, Tabs, BookReviewsComponent, BookNotesComponent, ProgressSpinner, TieredMenu, Image, TagComponent, UpperCasePipe, Divider, BookReadingSessionsComponent]
|
||||
imports: [Button, AsyncPipe, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, Divider, MetadataTabsComponent]
|
||||
})
|
||||
export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
@Input() book$!: Observable<Book | null>;
|
||||
@@ -70,8 +62,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
private destroyRef = inject(DestroyRef);
|
||||
private dialogRef?: DynamicDialogRef;
|
||||
|
||||
pdfReadMenuItems$!: Observable<MenuItem[]>;
|
||||
epubReadMenuItems$!: Observable<MenuItem[]>;
|
||||
readMenuItems$!: Observable<MenuItem[]>;
|
||||
refreshMenuItems$!: Observable<MenuItem[]>;
|
||||
otherItems$!: Observable<MenuItem[]>;
|
||||
downloadMenuItems$!: Observable<MenuItem[]>;
|
||||
@@ -117,24 +108,72 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
])
|
||||
);
|
||||
|
||||
this.pdfReadMenuItems$ = this.book$.pipe(
|
||||
this.readMenuItems$ = this.book$.pipe(
|
||||
filter((book): book is Book => book !== null),
|
||||
map((book): MenuItem[] => [
|
||||
{
|
||||
label: 'Streaming Reader',
|
||||
command: () => this.read(book.id, 'pdf-streaming')
|
||||
}
|
||||
])
|
||||
);
|
||||
map((book): MenuItem[] => {
|
||||
const items: MenuItem[] = [];
|
||||
const primaryType = book.primaryFile?.bookType;
|
||||
|
||||
this.epubReadMenuItems$ = this.book$.pipe(
|
||||
filter((book): book is Book => book !== null),
|
||||
map((book): MenuItem[] => [
|
||||
{
|
||||
label: 'Streaming Reader (Beta)',
|
||||
command: () => this.read(book.id, 'epub-streaming')
|
||||
// Add streaming reader option for primary file
|
||||
if (primaryType === 'PDF') {
|
||||
items.push({
|
||||
label: 'Streaming Reader',
|
||||
icon: 'pi pi-play',
|
||||
command: () => this.read(book.id, 'pdf-streaming')
|
||||
});
|
||||
} else if (primaryType === 'EPUB') {
|
||||
items.push({
|
||||
label: 'Streaming Reader',
|
||||
icon: 'pi pi-play',
|
||||
command: () => this.read(book.id, 'epub-streaming')
|
||||
});
|
||||
}
|
||||
])
|
||||
|
||||
// Get readable alternative formats and group by type
|
||||
const readableAlternatives = book.alternativeFormats?.filter(f =>
|
||||
f.bookType && ['PDF', 'EPUB', 'FB2', 'MOBI', 'AZW3', 'CBX', 'AUDIOBOOK'].includes(f.bookType)
|
||||
) ?? [];
|
||||
|
||||
// Get unique format types from alternatives
|
||||
const uniqueAltTypes = [...new Set(readableAlternatives.map(f => f.bookType))];
|
||||
|
||||
if (uniqueAltTypes.length > 0) {
|
||||
if (items.length > 0) {
|
||||
items.push({separator: true});
|
||||
}
|
||||
|
||||
uniqueAltTypes.forEach(formatType => {
|
||||
if (formatType === 'PDF' || formatType === 'EPUB') {
|
||||
// For PDF/EPUB, offer both standard and streaming readers
|
||||
items.push({
|
||||
label: formatType,
|
||||
icon: this.getFileIcon(formatType),
|
||||
items: [
|
||||
{
|
||||
label: 'Standard Reader',
|
||||
icon: 'pi pi-book',
|
||||
command: () => this.read(book.id, undefined, formatType)
|
||||
},
|
||||
{
|
||||
label: 'Streaming Reader',
|
||||
icon: 'pi pi-play',
|
||||
command: () => this.read(book.id, formatType === 'PDF' ? 'pdf-streaming' : 'epub-streaming', formatType)
|
||||
}
|
||||
]
|
||||
});
|
||||
} else {
|
||||
// For other formats, just show the type
|
||||
items.push({
|
||||
label: formatType,
|
||||
icon: this.getFileIcon(formatType ?? null),
|
||||
command: () => this.read(book.id, undefined, formatType)
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
})
|
||||
);
|
||||
|
||||
this.downloadMenuItems$ = this.book$.pipe(
|
||||
@@ -144,13 +183,12 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
map((book): MenuItem[] => {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
// Add alternative formats
|
||||
// Add alternative formats with type and size
|
||||
if (book.alternativeFormats && book.alternativeFormats.length > 0) {
|
||||
book.alternativeFormats.forEach(format => {
|
||||
const extension = this.getFileExtension(format.filePath);
|
||||
items.push({
|
||||
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
label: `${format.bookType ?? 'File'} · ${this.formatFileSize(format)}`,
|
||||
icon: this.getFileIcon(format.bookType ?? null),
|
||||
command: () => this.downloadAdditionalFile(book, format.id)
|
||||
});
|
||||
});
|
||||
@@ -167,8 +205,9 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
book.supplementaryFiles.forEach(file => {
|
||||
const extension = this.getFileExtension(file.filePath);
|
||||
items.push({
|
||||
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
|
||||
label: `${this.truncateFileName(file.fileName, 20)} · ${this.formatFileSize(file)}`,
|
||||
icon: this.getFileIcon(extension),
|
||||
tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'},
|
||||
command: () => this.downloadAdditionalFile(book, file.id)
|
||||
});
|
||||
});
|
||||
@@ -181,11 +220,19 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
this.otherItems$ = this.book$.pipe(
|
||||
filter((book): book is Book => book !== null),
|
||||
switchMap(book =>
|
||||
this.userService.userState$.pipe(
|
||||
take(1),
|
||||
map(userState => {
|
||||
combineLatest([
|
||||
this.userService.userState$.pipe(take(1)),
|
||||
this.appSettingsService.appSettings$.pipe(take(1))
|
||||
]).pipe(
|
||||
map(([userState, appSettings]) => {
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
items.push({
|
||||
label: 'Shelf',
|
||||
icon: 'pi pi-folder',
|
||||
command: () => this.assignShelf(book.id)
|
||||
});
|
||||
|
||||
// Add allowed submenus based on user permissions
|
||||
|
||||
if (userState?.user?.permissions.canUpload || userState?.user?.permissions.admin) {
|
||||
@@ -198,7 +245,9 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
});
|
||||
}
|
||||
|
||||
if (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin) {
|
||||
const hasFiles = this.hasAnyFiles(book);
|
||||
|
||||
if (hasFiles && (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin) && appSettings?.diskType === 'LOCAL') {
|
||||
items.push({
|
||||
label: 'Organize Files',
|
||||
icon: 'pi pi-arrows-h',
|
||||
@@ -208,7 +257,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
});
|
||||
}
|
||||
|
||||
if (userState?.user?.permissions.canEmailBook || userState?.user?.permissions.admin) {
|
||||
if (hasFiles && (userState?.user?.permissions.canEmailBook || userState?.user?.permissions.admin)) {
|
||||
items.push({
|
||||
label: 'Send Book',
|
||||
icon: 'pi pi-send',
|
||||
@@ -229,18 +278,113 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
});
|
||||
}
|
||||
|
||||
if (userState?.user?.permissions.canDeleteBook || userState?.user?.permissions.admin) {
|
||||
// Show "Attach to Another Book" for single-file books (detached books) - not for physical books
|
||||
const isSingleFileBook = hasFiles && !book.alternativeFormats?.length;
|
||||
if (isSingleFileBook && (userState?.user?.permissions.canManageLibrary || userState?.user?.permissions.admin)) {
|
||||
items.push({
|
||||
label: 'Delete Book',
|
||||
label: 'Attach to Another Book',
|
||||
icon: 'pi pi-link',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openBookFileAttacherDialog(book);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (userState?.user?.permissions.canDeleteBook || userState?.user?.permissions.admin) {
|
||||
// Delete File Formats submenu - allows deleting individual book format files
|
||||
const deleteFormatItems: MenuItem[] = [];
|
||||
const hasMultipleFormats = (book.alternativeFormats?.length ?? 0) > 0;
|
||||
|
||||
// Add primary file if it exists
|
||||
if (book.primaryFile) {
|
||||
const extension = this.getFileExtension(book.primaryFile.filePath);
|
||||
const isPrimaryOnly = !hasMultipleFormats;
|
||||
const truncatedName = this.truncateFileName(book.primaryFile.fileName, 25);
|
||||
deleteFormatItems.push({
|
||||
label: `${truncatedName} (${this.formatFileSize(book.primaryFile)}) [Primary]`,
|
||||
icon: this.getFileIcon(extension),
|
||||
tooltipOptions: {tooltipLabel: book.primaryFile.fileName, tooltipPosition: 'left'},
|
||||
command: () => this.deleteBookFile(book, book.primaryFile!.id, book.primaryFile!.fileName || 'file', true, isPrimaryOnly)
|
||||
});
|
||||
}
|
||||
|
||||
// Add alternative formats
|
||||
if (book.alternativeFormats && book.alternativeFormats.length > 0) {
|
||||
book.alternativeFormats.forEach(format => {
|
||||
const extension = this.getFileExtension(format.filePath);
|
||||
const truncatedName = this.truncateFileName(format.fileName, 25);
|
||||
deleteFormatItems.push({
|
||||
label: `${truncatedName} (${this.formatFileSize(format)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
tooltipOptions: {tooltipLabel: format.fileName, tooltipPosition: 'left'},
|
||||
command: () => this.deleteBookFile(book, format.id, format.fileName || 'file', false, false)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (deleteFormatItems.length > 0) {
|
||||
items.push({
|
||||
label: 'Delete File Formats',
|
||||
icon: 'pi pi-file',
|
||||
items: deleteFormatItems
|
||||
});
|
||||
}
|
||||
|
||||
// Delete Supplementary Files submenu - for non-book files
|
||||
if (book.supplementaryFiles && book.supplementaryFiles.length > 0) {
|
||||
const deleteSupplementaryItems: MenuItem[] = [];
|
||||
book.supplementaryFiles.forEach(file => {
|
||||
const extension = this.getFileExtension(file.filePath);
|
||||
const truncatedName = this.truncateFileName(file.fileName, 25);
|
||||
deleteSupplementaryItems.push({
|
||||
label: `${truncatedName} (${this.formatFileSize(file)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
tooltipOptions: {tooltipLabel: file.fileName, tooltipPosition: 'left'},
|
||||
command: () => this.deleteAdditionalFile(book.id, file.id, file.fileName || 'file')
|
||||
});
|
||||
});
|
||||
|
||||
items.push({
|
||||
label: 'Delete Supplementary Files',
|
||||
icon: 'pi pi-paperclip',
|
||||
items: deleteSupplementaryItems
|
||||
});
|
||||
}
|
||||
|
||||
// Delete Book & All Files - deletes the entire book entity
|
||||
const allFormats: string[] = [];
|
||||
if (book.primaryFile?.fileName) {
|
||||
allFormats.push(book.primaryFile.fileName);
|
||||
}
|
||||
book.alternativeFormats?.forEach(f => {
|
||||
if (f.fileName) allFormats.push(f.fileName);
|
||||
});
|
||||
book.supplementaryFiles?.forEach(f => {
|
||||
if (f.fileName) allFormats.push(f.fileName);
|
||||
});
|
||||
|
||||
const isPhysical = !hasFiles;
|
||||
const fileListMessage = allFormats.length > 0
|
||||
? `\n\nThe following files will be permanently deleted:\n• ${allFormats.join('\n• ')}`
|
||||
: '';
|
||||
|
||||
const deleteLabel = isPhysical ? 'Delete Book' : 'Delete Book & All Files';
|
||||
const deleteMessage = isPhysical
|
||||
? `Are you sure you want to delete "${book.metadata?.title}"?\n\nThis will permanently remove the book record from your library.\n\nThis action cannot be undone.`
|
||||
: `Are you sure you want to delete "${book.metadata?.title}"?\n\nThis will permanently remove the book record AND all associated files from your filesystem.${fileListMessage}\n\nThis action cannot be undone.`;
|
||||
const deleteAcceptLabel = isPhysical ? 'Delete' : 'Delete Everything';
|
||||
|
||||
items.push({
|
||||
label: deleteLabel,
|
||||
icon: 'pi pi-trash',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete "${book.metadata?.title}"?\n\nThis will permanently remove the book file from your filesystem.\n\nThis action cannot be undone.`,
|
||||
header: 'Confirm Deletion',
|
||||
message: deleteMessage,
|
||||
header: deleteLabel,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptLabel: 'Delete',
|
||||
acceptLabel: deleteAcceptLabel,
|
||||
rejectLabel: 'Cancel',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
rejectButtonStyleClass: 'p-button-outlined',
|
||||
@@ -260,48 +404,6 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Add delete additional files menu if there are any additional files
|
||||
if ((book.alternativeFormats && book.alternativeFormats.length > 0) ||
|
||||
(book.supplementaryFiles && book.supplementaryFiles.length > 0)) {
|
||||
const deleteFileItems: MenuItem[] = [];
|
||||
|
||||
// Add alternative formats
|
||||
if (book.alternativeFormats && book.alternativeFormats.length > 0) {
|
||||
book.alternativeFormats.forEach(format => {
|
||||
const extension = this.getFileExtension(format.filePath);
|
||||
deleteFileItems.push({
|
||||
label: `${format.fileName} (${this.getFileSizeInMB(format)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.deleteAdditionalFile(book.id, format.id, format.fileName || 'file')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Add separator if both types exist
|
||||
if (book.alternativeFormats && book.alternativeFormats.length > 0 &&
|
||||
book.supplementaryFiles && book.supplementaryFiles.length > 0) {
|
||||
deleteFileItems.push({separator: true});
|
||||
}
|
||||
|
||||
// Add supplementary files
|
||||
if (book.supplementaryFiles && book.supplementaryFiles.length > 0) {
|
||||
book.supplementaryFiles.forEach(file => {
|
||||
const extension = this.getFileExtension(file.filePath);
|
||||
deleteFileItems.push({
|
||||
label: `${file.fileName} (${this.getFileSizeInMB(file)})`,
|
||||
icon: this.getFileIcon(extension),
|
||||
command: () => this.deleteAdditionalFile(book.id, file.id, file.fileName || 'file')
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
items.push({
|
||||
label: 'Delete Additional Files',
|
||||
icon: 'pi pi-trash',
|
||||
items: deleteFileItems
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
@@ -375,16 +477,29 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
);
|
||||
}
|
||||
|
||||
get defaultTabValue(): number {
|
||||
return this.bookInSeries && this.bookInSeries.length > 1 ? 1 : 2;
|
||||
}
|
||||
|
||||
toggleExpand(): void {
|
||||
this.isExpanded = !this.isExpanded;
|
||||
}
|
||||
|
||||
read(bookId: number | undefined, reader?: "pdf-streaming" | "epub-streaming"): void {
|
||||
if (bookId) this.bookService.readBook(bookId, reader);
|
||||
read(bookId: number | undefined, reader?: "pdf-streaming" | "epub-streaming", bookType?: BookType): void {
|
||||
if (bookId) this.bookService.readBook(bookId, reader, bookType);
|
||||
}
|
||||
|
||||
isInProgressStatus(): boolean {
|
||||
return [ReadStatus.READING, ReadStatus.PAUSED, ReadStatus.RE_READING].includes(this.selectedReadStatus);
|
||||
}
|
||||
|
||||
getReadButtonLabel(book: Book): string {
|
||||
const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
|
||||
if (this.isInProgressStatus()) {
|
||||
return isAudiobook ? 'Continue' : 'Continue Reading';
|
||||
}
|
||||
return isAudiobook ? 'Play' : 'Read';
|
||||
}
|
||||
|
||||
getReadButtonIcon(book: Book): string {
|
||||
const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
|
||||
return (isAudiobook || this.isInProgressStatus()) ? 'pi pi-play' : 'pi pi-book';
|
||||
}
|
||||
|
||||
download(book: Book) {
|
||||
@@ -395,13 +510,39 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
this.bookService.downloadAdditionalFile(book, fileId);
|
||||
}
|
||||
|
||||
// Event handlers for MetadataTabsComponent
|
||||
onReadBook(event: ReadEvent): void {
|
||||
this.read(event.bookId, event.reader, event.bookType);
|
||||
}
|
||||
|
||||
onDownloadBook(event: DownloadEvent): void {
|
||||
this.download(event.book);
|
||||
}
|
||||
|
||||
onDownloadFile(event: DownloadAdditionalFileEvent): void {
|
||||
this.downloadAdditionalFile(event.book, event.fileId);
|
||||
}
|
||||
|
||||
onDownloadAllFiles(event: DownloadAllFilesEvent): void {
|
||||
this.bookService.downloadAllFiles(event.book);
|
||||
}
|
||||
|
||||
onDeleteBookFile(event: DeleteBookFileEvent): void {
|
||||
this.deleteBookFile(event.book, event.fileId, event.fileName, event.isPrimary, event.isOnlyFormat);
|
||||
}
|
||||
|
||||
onDeleteSupplementaryFile(event: DeleteSupplementaryFileEvent): void {
|
||||
this.deleteAdditionalFile(event.bookId, event.fileId, event.fileName);
|
||||
}
|
||||
|
||||
deleteAdditionalFile(bookId: number, fileId: number, fileName: string) {
|
||||
this.confirmationService.confirm({
|
||||
message: `Are you sure you want to delete the additional file "${fileName}"?`,
|
||||
header: 'Confirm File Deletion',
|
||||
message: `Are you sure you want to delete the supplementary file "${fileName}"?\n\nThis file will be permanently removed from your filesystem.`,
|
||||
header: 'Delete Supplementary File',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
rejectButtonStyleClass: 'p-button-secondary',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
this.bookService.deleteAdditionalFile(bookId, fileId).subscribe({
|
||||
@@ -409,14 +550,63 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: `Additional file "${fileName}" deleted successfully`
|
||||
detail: `Supplementary file "${fileName}" deleted successfully`
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: `Failed to delete additional file: ${error.message || 'Unknown error'}`
|
||||
detail: `Failed to delete supplementary file: ${error.message || 'Unknown error'}`
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteBookFile(book: Book, fileId: number, fileName: string, isPrimary: boolean, isOnlyFormat: boolean) {
|
||||
let message: string;
|
||||
let header: string;
|
||||
|
||||
if (isOnlyFormat) {
|
||||
// This is the only book format file - warn user strongly
|
||||
message = `Are you sure you want to delete "${fileName}"?\n\nThis is the ONLY book format file for this book. After deletion, the book will have no readable content.\n\nConsider using "Delete Book & All Files" instead to completely remove the book.\n\nThis file will be permanently removed from your filesystem.`;
|
||||
header = 'Delete Only Book Format';
|
||||
} else if (isPrimary) {
|
||||
// This is the primary format but there are alternatives
|
||||
message = `Are you sure you want to delete "${fileName}"?\n\nThis is currently the PRIMARY format for this book. After deletion, an alternative format will become the new primary.\n\nThis file will be permanently removed from your filesystem.`;
|
||||
header = 'Delete Primary Format';
|
||||
} else {
|
||||
// This is an alternative format
|
||||
message = `Are you sure you want to delete "${fileName}"?\n\nThis file will be permanently removed from your filesystem.`;
|
||||
header = 'Delete Book Format';
|
||||
}
|
||||
|
||||
this.confirmationService.confirm({
|
||||
message,
|
||||
header,
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'pi pi-trash',
|
||||
rejectIcon: 'pi pi-times',
|
||||
acceptLabel: 'Delete File',
|
||||
rejectLabel: 'Cancel',
|
||||
rejectButtonStyleClass: 'p-button-secondary',
|
||||
acceptButtonStyleClass: 'p-button-danger',
|
||||
accept: () => {
|
||||
this.bookService.deleteBookFile(book.id, fileId, isPrimary).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: `Book format "${fileName}" deleted successfully`
|
||||
});
|
||||
},
|
||||
error: (error) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: `Failed to delete book format: ${error.message || 'Unknown error'}`
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -674,9 +864,42 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
return lockedKeys.length > 0 && lockedKeys.every(k => metadata[k] === true);
|
||||
}
|
||||
|
||||
getFileSizeInMB(fileInfo: FileInfo | null | undefined): string {
|
||||
formatFileSize(fileInfo: FileInfo | null | undefined): string {
|
||||
const sizeKb = fileInfo?.fileSizeKb;
|
||||
return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-';
|
||||
if (sizeKb == null) return '-';
|
||||
|
||||
const units = ['KB', 'MB', 'GB', 'TB'];
|
||||
let size = sizeKb;
|
||||
let unitIndex = 0;
|
||||
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex++;
|
||||
}
|
||||
|
||||
const decimals = size >= 100 ? 0 : size >= 10 ? 1 : 2;
|
||||
return `${size.toFixed(decimals)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
truncateFileName(fileName: string | undefined, maxLength: number = 30): string {
|
||||
if (!fileName) return '';
|
||||
if (fileName.length <= maxLength) return fileName;
|
||||
|
||||
const lastDotIndex = fileName.lastIndexOf('.');
|
||||
if (lastDotIndex === -1) {
|
||||
// No extension - just truncate
|
||||
return fileName.substring(0, maxLength - 3) + '...';
|
||||
}
|
||||
|
||||
const extension = fileName.substring(lastDotIndex);
|
||||
const nameWithoutExt = fileName.substring(0, lastDotIndex);
|
||||
const availableLength = maxLength - extension.length - 3; // 3 for "..."
|
||||
|
||||
if (availableLength <= 0) {
|
||||
return '...' + extension;
|
||||
}
|
||||
|
||||
return nameWithoutExt.substring(0, availableLength) + '...' + extension;
|
||||
}
|
||||
|
||||
getProgressPercent(book: Book): number | null {
|
||||
@@ -689,6 +912,9 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
if (book.cbxProgress?.percentage != null) {
|
||||
return book.cbxProgress.percentage;
|
||||
}
|
||||
if (book.audiobookProgress?.percentage != null) {
|
||||
return book.audiobookProgress.percentage;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -721,6 +947,38 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
return parts.pop()?.toUpperCase() || null;
|
||||
}
|
||||
|
||||
getUniqueAlternativeFormatTypes(book: Book): BookType[] {
|
||||
if (!book.alternativeFormats?.length) return [];
|
||||
const primaryType = book.primaryFile?.bookType;
|
||||
const uniqueTypes = new Set<BookType>();
|
||||
for (const format of book.alternativeFormats) {
|
||||
if (format.bookType && format.bookType !== primaryType) {
|
||||
uniqueTypes.add(format.bookType);
|
||||
}
|
||||
}
|
||||
return [...uniqueTypes];
|
||||
}
|
||||
|
||||
getDisplayFormat(bookFile?: BookFile | null): string | null {
|
||||
if (bookFile?.extension) {
|
||||
return bookFile.extension.toUpperCase();
|
||||
}
|
||||
return this.getFileExtension(bookFile?.filePath);
|
||||
}
|
||||
|
||||
getUniqueAlternativeFormats(book: Book): string[] {
|
||||
if (!book.alternativeFormats?.length) return [];
|
||||
const primaryFormat = this.getDisplayFormat(book.primaryFile);
|
||||
const uniqueFormats = new Set<string>();
|
||||
for (const format of book.alternativeFormats) {
|
||||
const formatType = this.getDisplayFormat(format);
|
||||
if (formatType && formatType !== primaryFormat) {
|
||||
uniqueFormats.add(formatType);
|
||||
}
|
||||
}
|
||||
return [...uniqueFormats];
|
||||
}
|
||||
|
||||
getFileIcon(fileType: string | null): string {
|
||||
if (!fileType) return 'pi pi-file';
|
||||
switch (fileType.toLowerCase()) {
|
||||
@@ -734,6 +992,11 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
case 'cbr':
|
||||
case 'cbx':
|
||||
return 'pi pi-image';
|
||||
case 'audiobook':
|
||||
case 'm4b':
|
||||
case 'm4a':
|
||||
case 'mp3':
|
||||
return 'pi pi-headphones';
|
||||
default:
|
||||
return 'pi pi-file';
|
||||
}
|
||||
@@ -956,4 +1219,16 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
const position = this.bookNavigationService.getCurrentPosition();
|
||||
return position ? `${position.current} of ${position.total}` : '';
|
||||
}
|
||||
|
||||
hasDigitalFile(book: Book): boolean {
|
||||
return !!book?.primaryFile;
|
||||
}
|
||||
|
||||
hasAnyFiles(book: Book): boolean {
|
||||
return !!book?.primaryFile || (book?.alternativeFormats?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
isPhysicalBook(book: Book): boolean {
|
||||
return !this.hasAnyFiles(book);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -1,5 +1,4 @@
|
||||
import {Component, inject, Input, OnInit} from '@angular/core';
|
||||
import {Toast} from 'primeng/toast';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {BookCoverService, CoverFetchRequest, CoverImage} from '../../../../shared/services/book-cover.service';
|
||||
@@ -32,6 +31,7 @@ export class CoverSearchComponent implements OnInit {
|
||||
coverImages: CoverImage[] = [];
|
||||
loading = false;
|
||||
hasSearched = false;
|
||||
isAudiobook = false;
|
||||
|
||||
private fb = inject(FormBuilder);
|
||||
private bookCoverService = inject(BookCoverService);
|
||||
@@ -52,6 +52,7 @@ export class CoverSearchComponent implements OnInit {
|
||||
const book = this.bookService.getBookByIdFromState(this.bookId);
|
||||
|
||||
if (book) {
|
||||
this.isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
|
||||
this.searchForm.patchValue({
|
||||
title: book.metadata?.title || '',
|
||||
author: book.metadata?.authors && book.metadata?.authors.length > 0 ? book.metadata?.authors[0] : ''
|
||||
@@ -68,7 +69,8 @@ export class CoverSearchComponent implements OnInit {
|
||||
this.loading = true;
|
||||
const request: CoverFetchRequest = {
|
||||
title: this.searchForm.value.title,
|
||||
author: this.searchForm.value.author
|
||||
author: this.searchForm.value.author,
|
||||
squareCover: this.isAudiobook
|
||||
};
|
||||
|
||||
this.bookCoverService.fetchBookCovers(request)
|
||||
|
||||
+399
@@ -0,0 +1,399 @@
|
||||
@if (isLoading) {
|
||||
<div class="loading-container">
|
||||
<p-progressSpinner strokeWidth="3" />
|
||||
<span class="loading-text">Loading audiobook...</span>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="audiobook-reader">
|
||||
<!-- Hidden audio element -->
|
||||
<audio
|
||||
#audioElement
|
||||
[src]="audioSrc"
|
||||
(loadedmetadata)="onAudioLoaded()"
|
||||
(timeupdate)="onTimeUpdate()"
|
||||
(progress)="onProgress()"
|
||||
(ended)="onAudioEnded()"
|
||||
(error)="onAudioError()"
|
||||
preload="metadata"
|
||||
></audio>
|
||||
|
||||
<!-- Header -->
|
||||
<header class="reader-header">
|
||||
<p-button
|
||||
icon="pi pi-arrow-left"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="closeReader()"
|
||||
pTooltip="Back"
|
||||
tooltipPosition="bottom"
|
||||
/>
|
||||
<div class="header-info">
|
||||
<h1 class="book-title">{{ audiobookInfo.title || 'Untitled' }}</h1>
|
||||
<span class="book-author">{{ audiobookInfo.author || 'Unknown Author' }}</span>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<p-button
|
||||
icon="pi pi-bookmark"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="toggleBookmarkList()"
|
||||
pTooltip="Bookmarks"
|
||||
tooltipPosition="bottom"
|
||||
/>
|
||||
<p-button
|
||||
icon="pi pi-list"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="toggleTrackList()"
|
||||
pTooltip="Chapters/Tracks"
|
||||
tooltipPosition="bottom"
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Main content -->
|
||||
<main class="reader-main">
|
||||
<!-- Cover art -->
|
||||
<div class="cover-container">
|
||||
<div class="cover-wrapper">
|
||||
@if (coverUrl) {
|
||||
<img
|
||||
[src]="coverUrl"
|
||||
(error)="onCoverError()"
|
||||
alt="Cover"
|
||||
class="cover-image"
|
||||
/>
|
||||
} @else {
|
||||
<div class="cover-placeholder">
|
||||
<i class="pi pi-headphones"></i>
|
||||
</div>
|
||||
}
|
||||
@if (audioLoading) {
|
||||
<div class="cover-loading">
|
||||
<p-progressSpinner strokeWidth="3" />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Track/Chapter info -->
|
||||
<div class="track-info">
|
||||
@if (audiobookInfo.folderBased && currentTrack) {
|
||||
<span class="track-title">{{ currentTrack.title }}</span>
|
||||
<span class="track-number">Track {{ currentTrackIndex + 1 }} of {{ audiobookInfo.tracks?.length }}</span>
|
||||
} @else if (getCurrentChapter()) {
|
||||
<span class="track-title">{{ getCurrentChapter()?.title }}</span>
|
||||
@if (hasMultipleChapters()) {
|
||||
<span class="track-number">Chapter {{ getCurrentChapterIndex() + 1 }} of {{ audiobookInfo.chapters?.length }}</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Progress bar -->
|
||||
<div class="progress-container">
|
||||
<div class="time-display">
|
||||
<span class="current-time">{{ formatTime(currentTime) }}</span>
|
||||
<span class="duration">{{ formatTime(duration) }}</span>
|
||||
</div>
|
||||
<div class="progress-bar-wrapper">
|
||||
<div class="buffered-bar" [style.width.%]="getBufferedPercent()"></div>
|
||||
<p-slider
|
||||
[(ngModel)]="currentTime"
|
||||
[min]="0"
|
||||
[max]="duration || 100"
|
||||
[step]="1"
|
||||
(onChange)="seek($event)"
|
||||
styleClass="progress-slider"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Playback controls -->
|
||||
<div class="playback-controls">
|
||||
@if (audiobookInfo.folderBased) {
|
||||
<p-button
|
||||
icon="pi pi-step-backward"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="previousTrack()"
|
||||
[disabled]="currentTrackIndex === 0"
|
||||
pTooltip="Previous Track"
|
||||
tooltipPosition="top"
|
||||
size="large"
|
||||
/>
|
||||
} @else if (hasMultipleChapters()) {
|
||||
<p-button
|
||||
icon="pi pi-step-backward"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="previousChapter()"
|
||||
[disabled]="!canGoPreviousChapter()"
|
||||
pTooltip="Previous Chapter"
|
||||
tooltipPosition="top"
|
||||
size="large"
|
||||
/>
|
||||
}
|
||||
|
||||
<p-button
|
||||
icon="pi pi-replay"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="seekRelative(-30)"
|
||||
pTooltip="-30s"
|
||||
tooltipPosition="top"
|
||||
size="large"
|
||||
/>
|
||||
|
||||
<p-button
|
||||
[icon]="isPlaying ? 'pi pi-pause' : 'pi pi-play'"
|
||||
[rounded]="true"
|
||||
severity="contrast"
|
||||
(onClick)="togglePlay()"
|
||||
[disabled]="audioLoading"
|
||||
styleClass="play-button"
|
||||
size="large"
|
||||
/>
|
||||
|
||||
<p-button
|
||||
icon="pi pi-forward"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="seekRelative(30)"
|
||||
pTooltip="+30s"
|
||||
tooltipPosition="top"
|
||||
size="large"
|
||||
/>
|
||||
|
||||
@if (audiobookInfo.folderBased) {
|
||||
<p-button
|
||||
icon="pi pi-step-forward"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="nextTrack()"
|
||||
[disabled]="!audiobookInfo.tracks || currentTrackIndex >= audiobookInfo.tracks.length - 1"
|
||||
pTooltip="Next Track"
|
||||
tooltipPosition="top"
|
||||
size="large"
|
||||
/>
|
||||
} @else if (hasMultipleChapters()) {
|
||||
<p-button
|
||||
icon="pi pi-step-forward"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="nextChapter()"
|
||||
[disabled]="!canGoNextChapter()"
|
||||
pTooltip="Next Chapter"
|
||||
tooltipPosition="top"
|
||||
size="large"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Secondary controls -->
|
||||
<div class="secondary-controls">
|
||||
<!-- Volume -->
|
||||
<div class="volume-control">
|
||||
<p-button
|
||||
[icon]="getVolumeIcon()"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="toggleMute()"
|
||||
size="small"
|
||||
/>
|
||||
<p-slider
|
||||
[(ngModel)]="volume"
|
||||
[min]="0"
|
||||
[max]="1"
|
||||
[step]="0.01"
|
||||
(onChange)="setVolume($event)"
|
||||
styleClass="volume-slider"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Playback speed -->
|
||||
<div class="speed-control">
|
||||
<p-selectButton
|
||||
[options]="playbackRates"
|
||||
[ngModel]="playbackRate"
|
||||
(ngModelChange)="setPlaybackRate($event)"
|
||||
optionLabel="label"
|
||||
optionValue="value"
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Extra controls row -->
|
||||
<div class="extra-controls">
|
||||
<!-- Add bookmark button -->
|
||||
<p-button
|
||||
icon="pi pi-bookmark-fill"
|
||||
label="Add Bookmark"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="addBookmark()"
|
||||
size="small"
|
||||
/>
|
||||
|
||||
<!-- Sleep timer -->
|
||||
<p-button
|
||||
#sleepTimerBtn
|
||||
icon="pi pi-moon"
|
||||
[label]="sleepTimerActive ? formatSleepTimerRemaining() : 'Sleep Timer'"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
[styleClass]="sleepTimerActive ? 'sleep-timer-active' : ''"
|
||||
(onClick)="sleepTimerMenu.toggle($event)"
|
||||
size="small"
|
||||
/>
|
||||
<p-menu
|
||||
#sleepTimerMenu
|
||||
[model]="sleepTimerOptions"
|
||||
[popup]="true"
|
||||
appendTo="body"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Audio details -->
|
||||
<div class="audio-details">
|
||||
@if (audiobookInfo.narrator) {
|
||||
<span class="detail-item">
|
||||
<i class="pi pi-user"></i>
|
||||
Narrated by {{ audiobookInfo.narrator }}
|
||||
</span>
|
||||
}
|
||||
@if (audiobookInfo.bitrate) {
|
||||
<span class="detail-item">
|
||||
<i class="pi pi-sliders-h"></i>
|
||||
{{ audiobookInfo.bitrate }} kbps
|
||||
</span>
|
||||
}
|
||||
@if (audiobookInfo.durationMs) {
|
||||
<span class="detail-item">
|
||||
<i class="pi pi-clock"></i>
|
||||
{{ formatDuration(audiobookInfo.durationMs) }} total
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Track/Chapter list sidebar -->
|
||||
@if (showTrackList) {
|
||||
<aside class="track-list-sidebar">
|
||||
<div class="sidebar-header">
|
||||
<h2>{{ audiobookInfo.folderBased ? 'Tracks' : 'Chapters' }}</h2>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="toggleTrackList()"
|
||||
/>
|
||||
</div>
|
||||
<div class="sidebar-content">
|
||||
@if (audiobookInfo.folderBased && audiobookInfo.tracks) {
|
||||
<ul class="track-list">
|
||||
@for (track of audiobookInfo.tracks; track track.index) {
|
||||
<li
|
||||
class="track-item"
|
||||
[class.active]="track.index === currentTrackIndex"
|
||||
(click)="selectTrack(track)"
|
||||
>
|
||||
<span class="track-index">{{ track.index + 1 }}</span>
|
||||
<div class="track-details">
|
||||
<span class="track-name">{{ track.title }}</span>
|
||||
<span class="track-duration">{{ formatDuration(track.durationMs) }}</span>
|
||||
</div>
|
||||
@if (track.index === currentTrackIndex && isPlaying) {
|
||||
<i class="pi pi-volume-up playing-indicator"></i>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
} @else if (audiobookInfo.chapters) {
|
||||
<ul class="track-list">
|
||||
@for (chapter of audiobookInfo.chapters; track chapter.index) {
|
||||
<li
|
||||
class="track-item"
|
||||
[class.active]="getCurrentChapter()?.index === chapter.index"
|
||||
(click)="selectChapter(chapter)"
|
||||
>
|
||||
<span class="track-index">{{ chapter.index + 1 }}</span>
|
||||
<div class="track-details">
|
||||
<span class="track-name">{{ chapter.title }}</span>
|
||||
<span class="track-duration">{{ formatDuration(chapter.durationMs) }}</span>
|
||||
</div>
|
||||
@if (getCurrentChapter()?.index === chapter.index && isPlaying) {
|
||||
<i class="pi pi-volume-up playing-indicator"></i>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
</aside>
|
||||
}
|
||||
|
||||
<!-- Bookmark list sidebar -->
|
||||
@if (showBookmarkList) {
|
||||
<aside class="track-list-sidebar bookmark-sidebar">
|
||||
<div class="sidebar-header">
|
||||
<h2>Bookmarks</h2>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="secondary"
|
||||
(onClick)="toggleBookmarkList()"
|
||||
/>
|
||||
</div>
|
||||
<div class="sidebar-content">
|
||||
@if (bookmarks.length === 0) {
|
||||
<div class="empty-bookmarks">
|
||||
<i class="pi pi-bookmark"></i>
|
||||
<p>No bookmarks yet</p>
|
||||
<span>Add a bookmark to save your place</span>
|
||||
</div>
|
||||
} @else {
|
||||
<ul class="track-list">
|
||||
@for (bookmark of bookmarks; track bookmark.id) {
|
||||
<li
|
||||
class="track-item bookmark-item"
|
||||
(click)="goToBookmark(bookmark)"
|
||||
>
|
||||
<i class="pi pi-bookmark-fill bookmark-icon"></i>
|
||||
<div class="track-details">
|
||||
<span class="track-name">{{ bookmark.title }}</span>
|
||||
<span class="track-duration">{{ formatBookmarkPosition(bookmark) }}</span>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
[rounded]="true"
|
||||
[text]="true"
|
||||
severity="danger"
|
||||
size="small"
|
||||
(onClick)="deleteBookmark($event, bookmark.id)"
|
||||
pTooltip="Delete"
|
||||
tooltipPosition="left"
|
||||
/>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
</aside>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
+805
@@ -0,0 +1,805 @@
|
||||
@use 'sass:color';
|
||||
|
||||
// Variables - More vibrant color palette
|
||||
$bg-primary: #0f0f1a;
|
||||
$bg-secondary: #1a1a2e;
|
||||
$bg-tertiary: #252542;
|
||||
$bg-darker: #0a0a12;
|
||||
$text-primary: #ffffff;
|
||||
$text-secondary: rgba(255, 255, 255, 0.8);
|
||||
$text-tertiary: rgba(255, 255, 255, 0.5);
|
||||
$accent-secondary: #ec4899;
|
||||
$accent-tertiary: #06b6d4;
|
||||
$border-color: rgba(255, 255, 255, 0.1);
|
||||
|
||||
// CSS variable for primary color from theme
|
||||
:host {
|
||||
--accent-color: var(--primary-color, #8b5cf6);
|
||||
--accent-hover: var(--primary-hover-color, #a78bfa);
|
||||
}
|
||||
|
||||
// Gradient mixins
|
||||
@mixin gradient-bg {
|
||||
background: linear-gradient(135deg, $bg-secondary 0%, $bg-primary 50%, $bg-darker 100%);
|
||||
}
|
||||
|
||||
@mixin accent-gradient {
|
||||
background: linear-gradient(135deg, var(--accent-color) 0%, $accent-secondary 100%);
|
||||
}
|
||||
|
||||
@mixin glow-effect($color, $intensity: 0.4) {
|
||||
box-shadow: 0 0 40px rgba($color, $intensity),
|
||||
0 0 80px rgba($color, $intensity * 0.5);
|
||||
}
|
||||
|
||||
// Loading container
|
||||
.loading-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100vh;
|
||||
@include gradient-bg;
|
||||
gap: 1rem;
|
||||
|
||||
.loading-text {
|
||||
color: $text-secondary;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
::ng-deep .p-progress-spinner-circle {
|
||||
stroke: var(--accent-color) !important;
|
||||
}
|
||||
}
|
||||
|
||||
// Main container
|
||||
.audiobook-reader {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
@include gradient-bg;
|
||||
color: $text-primary;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
|
||||
// Subtle animated gradient overlay
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: radial-gradient(ellipse at 20% 0%, color-mix(in srgb, var(--accent-color) 15%, transparent) 0%, transparent 50%),
|
||||
radial-gradient(ellipse at 80% 100%, rgba($accent-secondary, 0.1) 0%, transparent 50%);
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Header
|
||||
.reader-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1rem 1.5rem;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
backdrop-filter: blur(20px);
|
||||
border-bottom: 1px solid $border-color;
|
||||
z-index: 10;
|
||||
position: relative;
|
||||
|
||||
.header-info {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
padding: 0 1rem;
|
||||
overflow: hidden;
|
||||
|
||||
.book-title {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
background: linear-gradient(90deg, $text-primary, var(--accent-color));
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.book-author {
|
||||
font-size: 0.85rem;
|
||||
color: $text-secondary;
|
||||
}
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
::ng-deep .p-button {
|
||||
&.p-button-text {
|
||||
color: $text-secondary;
|
||||
|
||||
&:hover {
|
||||
color: $text-primary;
|
||||
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main content
|
||||
.reader-main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 2rem 1.5rem;
|
||||
overflow-y: auto;
|
||||
gap: 1.5rem;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
// Cover art
|
||||
.cover-container {
|
||||
flex-shrink: 0;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
aspect-ratio: 1;
|
||||
margin-top: 1.5rem;
|
||||
|
||||
.cover-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 16px;
|
||||
overflow: hidden;
|
||||
box-shadow:
|
||||
0 25px 60px -12px rgba(0, 0, 0, 0.6),
|
||||
0 0 0 1px rgba(255, 255, 255, 0.1),
|
||||
0 0 60px color-mix(in srgb, var(--accent-color) 20%, transparent),
|
||||
0 0 100px rgba($accent-secondary, 0.1);
|
||||
transition: transform 0.3s ease, box-shadow 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.02);
|
||||
box-shadow:
|
||||
0 30px 70px -12px rgba(0, 0, 0, 0.7),
|
||||
0 0 0 1px rgba(255, 255, 255, 0.15),
|
||||
0 0 80px color-mix(in srgb, var(--accent-color) 30%, transparent),
|
||||
0 0 120px rgba($accent-secondary, 0.15);
|
||||
}
|
||||
|
||||
.cover-image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.cover-loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.cover-placeholder {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@include accent-gradient;
|
||||
opacity: 0.8;
|
||||
|
||||
i {
|
||||
font-size: 5rem;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
text-shadow: 0 0 30px rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Track info
|
||||
.track-info {
|
||||
text-align: center;
|
||||
min-height: 3rem;
|
||||
|
||||
.track-title {
|
||||
display: block;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
color: $text-primary;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.track-number {
|
||||
font-size: 0.85rem;
|
||||
color: var(--accent-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
// Progress bar
|
||||
.progress-container {
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
|
||||
.time-display {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
color: $text-secondary;
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.progress-bar-wrapper {
|
||||
position: relative;
|
||||
height: 8px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 4px;
|
||||
overflow: visible;
|
||||
|
||||
.buffered-bar {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
height: 100%;
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
border-radius: 4px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
::ng-deep .progress-slider {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
transform: translateY(-50%);
|
||||
|
||||
.p-slider {
|
||||
background: transparent;
|
||||
height: 8px;
|
||||
|
||||
.p-slider-range {
|
||||
@include accent-gradient;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 0 10px color-mix(in srgb, var(--accent-color) 50%, transparent);
|
||||
}
|
||||
|
||||
.p-slider-handle {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
background: $text-primary;
|
||||
border: 3px solid var(--accent-color);
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4),
|
||||
0 0 15px color-mix(in srgb, var(--accent-color) 40%, transparent);
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.2);
|
||||
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.5),
|
||||
0 0 25px color-mix(in srgb, var(--accent-color) 60%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Playback controls
|
||||
.playback-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
|
||||
::ng-deep .play-button {
|
||||
.p-button {
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
font-size: 1.75rem;
|
||||
@include accent-gradient;
|
||||
border: none;
|
||||
box-shadow: 0 8px 30px color-mix(in srgb, var(--accent-color) 40%, transparent),
|
||||
0 0 50px color-mix(in srgb, var(--accent-color) 20%, transparent);
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.05);
|
||||
box-shadow: 0 10px 40px color-mix(in srgb, var(--accent-color) 50%, transparent),
|
||||
0 0 70px color-mix(in srgb, var(--accent-color) 30%, transparent);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.p-button-icon {
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .p-button {
|
||||
&.p-button-text {
|
||||
color: $text-secondary;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: $text-primary;
|
||||
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
color: $text-tertiary;
|
||||
opacity: 0.4;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
&.p-button-lg {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Secondary controls
|
||||
.secondary-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 2rem;
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
.volume-control {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
|
||||
::ng-deep .p-button.p-button-text {
|
||||
color: $text-secondary;
|
||||
|
||||
&:hover {
|
||||
color: var(--accent-color);
|
||||
background: color-mix(in srgb, var(--accent-color) 15%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .volume-slider {
|
||||
width: 100px;
|
||||
|
||||
.p-slider {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
height: 5px;
|
||||
border-radius: 3px;
|
||||
|
||||
.p-slider-range {
|
||||
background: $accent-tertiary;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.p-slider-handle {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
background: $text-primary;
|
||||
border: 2px solid $accent-tertiary;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.speed-control {
|
||||
::ng-deep .p-selectbutton {
|
||||
.p-button {
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
color: $text-secondary;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: $text-primary;
|
||||
border-color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
&.p-highlight {
|
||||
@include accent-gradient;
|
||||
color: $text-primary;
|
||||
border-color: transparent;
|
||||
box-shadow: 0 4px 15px color-mix(in srgb, var(--accent-color) 30%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Audio details
|
||||
.audio-details {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 1.25rem;
|
||||
padding: 1rem 1rem 0;
|
||||
color: $text-tertiary;
|
||||
font-size: 0.8rem;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-radius: 12px;
|
||||
margin-top: 0.5rem;
|
||||
|
||||
.detail-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
white-space: nowrap;
|
||||
|
||||
i {
|
||||
font-size: 0.9rem;
|
||||
color: $accent-tertiary;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extra controls (bookmark, sleep timer)
|
||||
.extra-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
padding-top: 0.5rem;
|
||||
|
||||
::ng-deep .p-button {
|
||||
&.p-button-text {
|
||||
color: $text-secondary;
|
||||
font-size: 0.85rem;
|
||||
|
||||
&:hover {
|
||||
color: $text-primary;
|
||||
background: color-mix(in srgb, var(--accent-color) 15%, transparent);
|
||||
}
|
||||
|
||||
.p-button-icon {
|
||||
font-size: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
&.sleep-timer-active {
|
||||
color: #fbbf24 !important;
|
||||
|
||||
&:hover {
|
||||
background: rgba(251, 191, 36, 0.15) !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Empty bookmarks
|
||||
.empty-bookmarks {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem 1.5rem;
|
||||
text-align: center;
|
||||
color: $text-tertiary;
|
||||
|
||||
i {
|
||||
font-size: 3rem;
|
||||
margin-bottom: 1rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
color: $text-secondary;
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
}
|
||||
|
||||
// Bookmark item
|
||||
.bookmark-item {
|
||||
.bookmark-icon {
|
||||
color: var(--accent-color);
|
||||
font-size: 1.1rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
::ng-deep .p-button {
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
::ng-deep .p-button {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Track list sidebar
|
||||
.track-list-sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
height: 100vh;
|
||||
background: linear-gradient(180deg, $bg-tertiary 0%, $bg-secondary 100%);
|
||||
border-left: 1px solid color-mix(in srgb, var(--accent-color) 20%, transparent);
|
||||
z-index: 100;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
animation: slideIn 0.25s ease-out;
|
||||
box-shadow: -10px 0 40px rgba(0, 0, 0, 0.5);
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateX(100%);
|
||||
opacity: 0.5;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 1.25rem 1.5rem;
|
||||
border-bottom: 1px solid $border-color;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 1.2rem;
|
||||
font-weight: 600;
|
||||
background: linear-gradient(90deg, $text-primary, var(--accent-color));
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
::ng-deep .p-button.p-button-text {
|
||||
color: $text-secondary;
|
||||
|
||||
&:hover {
|
||||
color: $text-primary;
|
||||
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0.5rem 0;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--accent-color) 30%, transparent);
|
||||
border-radius: 3px;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--accent-color) 50%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.track-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
|
||||
.track-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 1rem 1.5rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
gap: 1rem;
|
||||
border-left: 3px solid transparent;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--accent-color) 10%, transparent);
|
||||
border-left-color: color-mix(in srgb, var(--accent-color) 50%, transparent);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: linear-gradient(90deg, color-mix(in srgb, var(--accent-color) 20%, transparent) 0%, transparent 100%);
|
||||
border-left-color: var(--accent-color);
|
||||
|
||||
.track-index {
|
||||
color: var(--accent-color);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.track-name {
|
||||
color: var(--accent-color);
|
||||
}
|
||||
}
|
||||
|
||||
.track-index {
|
||||
width: 2rem;
|
||||
text-align: center;
|
||||
font-size: 0.9rem;
|
||||
color: $text-tertiary;
|
||||
flex-shrink: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.track-details {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
.track-name {
|
||||
display: block;
|
||||
font-size: 0.95rem;
|
||||
color: $text-primary;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.track-duration {
|
||||
font-size: 0.8rem;
|
||||
color: $text-tertiary;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.playing-indicator {
|
||||
color: var(--accent-color);
|
||||
animation: pulse 1.5s ease-in-out infinite;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.6;
|
||||
transform: scale(0.95);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Responsive adjustments
|
||||
@media (max-width: 768px) {
|
||||
.reader-main {
|
||||
padding: 1rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.cover-container {
|
||||
max-width: 360px;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.secondary-controls {
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.volume-control {
|
||||
::ng-deep .volume-slider {
|
||||
width: 150px;
|
||||
}
|
||||
}
|
||||
|
||||
.track-list-sidebar {
|
||||
max-width: 75%;
|
||||
}
|
||||
|
||||
.audio-details {
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem;
|
||||
|
||||
.detail-item {
|
||||
padding: 0.4rem 0.6rem;
|
||||
font-size: 0.75rem;
|
||||
|
||||
i {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.cover-container {
|
||||
max-width: 300px;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.playback-controls {
|
||||
gap: 0.5rem;
|
||||
|
||||
::ng-deep .play-button {
|
||||
.p-button {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .p-button.p-button-lg {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
}
|
||||
|
||||
.audio-details {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
|
||||
.detail-item {
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Landscape mode optimization
|
||||
@media (max-height: 600px) and (orientation: landscape) {
|
||||
.reader-main {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.cover-container {
|
||||
max-width: 180px;
|
||||
}
|
||||
|
||||
.track-info,
|
||||
.progress-container,
|
||||
.playback-controls,
|
||||
.secondary-controls {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.audio-details {
|
||||
flex-direction: row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,966 @@
|
||||
import { Component, ElementRef, inject, OnDestroy, OnInit, ViewChild } from '@angular/core';
|
||||
import { CommonModule, Location } from '@angular/common';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { forkJoin, Subject } from 'rxjs';
|
||||
import { takeUntil } from 'rxjs/operators';
|
||||
|
||||
import { Button } from 'primeng/button';
|
||||
import { Slider, SliderChangeEvent } from 'primeng/slider';
|
||||
import { ProgressSpinner } from 'primeng/progressspinner';
|
||||
import { Tooltip } from 'primeng/tooltip';
|
||||
import { MessageService } from 'primeng/api';
|
||||
import { SelectButton } from 'primeng/selectbutton';
|
||||
import { Menu } from 'primeng/menu';
|
||||
import { MenuItem } from 'primeng/api';
|
||||
|
||||
import { AudiobookService } from './audiobook.service';
|
||||
import { AudiobookInfo, AudiobookChapter, AudiobookTrack, AudiobookProgress } from './audiobook.model';
|
||||
import { BookService } from '../../book/service/book.service';
|
||||
import { BookMarkService, BookMark, CreateBookMarkRequest } from '../../../shared/service/book-mark.service';
|
||||
import { AudiobookSessionService } from '../../../shared/service/audiobook-session.service';
|
||||
import { PageTitleService } from '../../../shared/service/page-title.service';
|
||||
import { AuthService } from '../../../shared/service/auth.service';
|
||||
import { API_CONFIG } from '../../../core/config/api-config';
|
||||
|
||||
@Component({
|
||||
selector: 'app-audiobook-reader',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
Button,
|
||||
Slider,
|
||||
ProgressSpinner,
|
||||
Tooltip,
|
||||
SelectButton,
|
||||
Menu
|
||||
],
|
||||
templateUrl: './audiobook-reader.component.html',
|
||||
styleUrls: ['./audiobook-reader.component.scss']
|
||||
})
|
||||
export class AudiobookReaderComponent implements OnInit, OnDestroy {
|
||||
@ViewChild('audioElement') audioElement!: ElementRef<HTMLAudioElement>;
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private audiobookService = inject(AudiobookService);
|
||||
private bookService = inject(BookService);
|
||||
private bookMarkService = inject(BookMarkService);
|
||||
private authService = inject(AuthService);
|
||||
private route = inject(ActivatedRoute);
|
||||
private router = inject(Router);
|
||||
private location = inject(Location);
|
||||
private messageService = inject(MessageService);
|
||||
private audiobookSessionService = inject(AudiobookSessionService);
|
||||
private pageTitle = inject(PageTitleService);
|
||||
|
||||
// Loading state
|
||||
isLoading = true;
|
||||
audioLoading = true;
|
||||
|
||||
// Book data
|
||||
bookId!: number;
|
||||
audiobookInfo!: AudiobookInfo;
|
||||
coverUrl?: string;
|
||||
bookCoverUrl?: string;
|
||||
|
||||
// Audio state
|
||||
isPlaying = false;
|
||||
currentTime = 0;
|
||||
duration = 0;
|
||||
volume = 1;
|
||||
previousVolume = 1;
|
||||
isMuted = false;
|
||||
playbackRate = 1;
|
||||
buffered = 0;
|
||||
|
||||
// Saved position to restore after audio loads
|
||||
private savedPosition = 0;
|
||||
|
||||
// Track state (for folder-based audiobooks)
|
||||
currentTrackIndex = 0;
|
||||
audioSrc = '';
|
||||
|
||||
// UI state
|
||||
showTrackList = false;
|
||||
showBookmarkList = false;
|
||||
|
||||
// Sleep timer
|
||||
sleepTimerActive = false;
|
||||
sleepTimerRemaining = 0; // seconds remaining
|
||||
sleepTimerEndOfChapter = false;
|
||||
private sleepTimerInterval?: ReturnType<typeof setInterval>;
|
||||
private originalVolume = 1;
|
||||
|
||||
sleepTimerOptions: MenuItem[] = [
|
||||
{ label: '15 minutes', command: () => this.setSleepTimer(15) },
|
||||
{ label: '30 minutes', command: () => this.setSleepTimer(30) },
|
||||
{ label: '45 minutes', command: () => this.setSleepTimer(45) },
|
||||
{ label: '60 minutes', command: () => this.setSleepTimer(60) },
|
||||
{ label: 'End of chapter', command: () => this.setSleepTimerEndOfChapter() },
|
||||
{ separator: true },
|
||||
{ label: 'Cancel timer', command: () => this.cancelSleepTimer(), visible: false }
|
||||
];
|
||||
|
||||
// Bookmarks
|
||||
bookmarks: BookMark[] = [];
|
||||
|
||||
// Playback speed options
|
||||
playbackRates = [
|
||||
{ label: '0.5x', value: 0.5 },
|
||||
{ label: '0.75x', value: 0.75 },
|
||||
{ label: '1x', value: 1 },
|
||||
{ label: '1.25x', value: 1.25 },
|
||||
{ label: '1.5x', value: 1.5 },
|
||||
{ label: '2x', value: 2 }
|
||||
];
|
||||
|
||||
// Progress save interval
|
||||
private progressSaveInterval?: ReturnType<typeof setInterval>;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.paramMap.pipe(takeUntil(this.destroy$)).subscribe(params => {
|
||||
this.bookId = +params.get('bookId')!;
|
||||
this.loadAudiobook();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
|
||||
if (this.progressSaveInterval) {
|
||||
clearInterval(this.progressSaveInterval);
|
||||
}
|
||||
|
||||
if (this.sleepTimerInterval) {
|
||||
clearInterval(this.sleepTimerInterval);
|
||||
}
|
||||
|
||||
this.saveProgress();
|
||||
|
||||
if (this.audiobookSessionService.isSessionActive()) {
|
||||
this.audiobookSessionService.endSession(Math.round(this.currentTime * 1000));
|
||||
}
|
||||
}
|
||||
|
||||
private loadAudiobook(): void {
|
||||
// Reset all state when loading a new audiobook
|
||||
this.resetState();
|
||||
this.isLoading = true;
|
||||
|
||||
const audiobookInfo$ = this.audiobookService.getAudiobookInfo(this.bookId);
|
||||
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false);
|
||||
|
||||
forkJoin([audiobookInfo$, book$]).subscribe({
|
||||
next: ([info, book]) => {
|
||||
this.audiobookInfo = info;
|
||||
this.pageTitle.setBookPageTitle(book);
|
||||
|
||||
// Set cover URL with auth token
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/cover/${this.bookId}?token=${encodeURIComponent(token || '')}`;
|
||||
this.coverUrl = this.audiobookService.getEmbeddedCoverUrl(this.bookId);
|
||||
|
||||
// Restore progress and load audio
|
||||
if (book.audiobookProgress) {
|
||||
// Store saved position - will be applied when audio loads
|
||||
this.savedPosition = book.audiobookProgress.positionMs
|
||||
? book.audiobookProgress.positionMs / 1000
|
||||
: 0;
|
||||
}
|
||||
|
||||
if (info.folderBased && info.tracks && info.tracks.length > 0) {
|
||||
// Folder-based audiobook
|
||||
const trackIndex = book.audiobookProgress?.trackIndex ?? 0;
|
||||
this.currentTrackIndex = trackIndex;
|
||||
this.loadTrack(trackIndex);
|
||||
} else {
|
||||
// Single-file audiobook
|
||||
this.audioSrc = this.audiobookService.getStreamUrl(this.bookId);
|
||||
}
|
||||
|
||||
this.isLoading = false;
|
||||
|
||||
// Load bookmarks
|
||||
this.loadBookmarks();
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to load audiobook'
|
||||
});
|
||||
this.isLoading = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private loadTrack(index: number): void {
|
||||
if (!this.audiobookInfo.tracks || index < 0 || index >= this.audiobookInfo.tracks.length) {
|
||||
return;
|
||||
}
|
||||
this.currentTrackIndex = index;
|
||||
this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, index);
|
||||
this.audioLoading = true;
|
||||
// Reset buffered since it's a new track
|
||||
this.buffered = 0;
|
||||
}
|
||||
|
||||
private resetState(): void {
|
||||
// Stop any existing intervals
|
||||
this.stopProgressSaveInterval();
|
||||
|
||||
// Reset audio state
|
||||
this.isPlaying = false;
|
||||
this.currentTime = 0;
|
||||
this.duration = 0;
|
||||
this.buffered = 0;
|
||||
this.savedPosition = 0;
|
||||
this.currentTrackIndex = 0;
|
||||
this.audioSrc = '';
|
||||
this.audioLoading = true;
|
||||
|
||||
// Reset UI state
|
||||
this.showTrackList = false;
|
||||
this.coverUrl = undefined;
|
||||
this.bookCoverUrl = undefined;
|
||||
}
|
||||
|
||||
// Audio event handlers
|
||||
onAudioLoaded(): void {
|
||||
this.audioLoading = false;
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
this.duration = audio.duration;
|
||||
audio.volume = this.volume;
|
||||
audio.playbackRate = this.playbackRate;
|
||||
|
||||
// Apply saved position now that we know the duration
|
||||
if (this.savedPosition > 0 && this.savedPosition < this.duration) {
|
||||
audio.currentTime = this.savedPosition;
|
||||
this.currentTime = this.savedPosition;
|
||||
}
|
||||
|
||||
// Setup Media Session for background playback
|
||||
this.setupMediaSession();
|
||||
|
||||
// Note: Session will be started when user presses play, not on load
|
||||
}
|
||||
}
|
||||
|
||||
onTimeUpdate(): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
const previousChapterIndex = this.getCurrentChapterIndex();
|
||||
this.currentTime = audio.currentTime;
|
||||
|
||||
// Update audiobook session position
|
||||
this.audiobookSessionService.updatePosition(
|
||||
Math.round(this.currentTime * 1000),
|
||||
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
|
||||
);
|
||||
|
||||
// Update Media Session position state (throttled to every 5 seconds)
|
||||
if (Math.floor(this.currentTime) % 5 === 0) {
|
||||
this.updateMediaSessionPositionState();
|
||||
}
|
||||
|
||||
// Update metadata if chapter changed (for single-file audiobooks)
|
||||
if (!this.audiobookInfo.folderBased && this.getCurrentChapterIndex() !== previousChapterIndex) {
|
||||
this.updateMediaSessionMetadata();
|
||||
}
|
||||
|
||||
// Check sleep timer end of chapter
|
||||
this.checkSleepTimerEndOfChapter();
|
||||
}
|
||||
}
|
||||
|
||||
onProgress(): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio && audio.buffered.length > 0) {
|
||||
this.buffered = audio.buffered.end(audio.buffered.length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
onAudioEnded(): void {
|
||||
// For folder-based audiobooks, play next track
|
||||
if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) {
|
||||
if (this.currentTrackIndex < this.audiobookInfo.tracks.length - 1) {
|
||||
this.nextTrack();
|
||||
} else {
|
||||
this.isPlaying = false;
|
||||
this.stopProgressSaveInterval();
|
||||
this.saveProgress();
|
||||
this.updateMediaSessionPlaybackState();
|
||||
// Pause session when audiobook ends
|
||||
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
|
||||
}
|
||||
} else {
|
||||
this.isPlaying = false;
|
||||
this.stopProgressSaveInterval();
|
||||
this.saveProgress();
|
||||
this.updateMediaSessionPlaybackState();
|
||||
// Pause session when audiobook ends
|
||||
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
|
||||
}
|
||||
}
|
||||
|
||||
onAudioError(): void {
|
||||
this.audioLoading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to load audio'
|
||||
});
|
||||
}
|
||||
|
||||
// Media Session API for background playback
|
||||
private setupMediaSession(): void {
|
||||
if (!('mediaSession' in navigator)) return;
|
||||
|
||||
this.updateMediaSessionMetadata();
|
||||
|
||||
navigator.mediaSession.setActionHandler('play', () => {
|
||||
if (!this.isPlaying) this.togglePlay();
|
||||
});
|
||||
navigator.mediaSession.setActionHandler('pause', () => {
|
||||
if (this.isPlaying) this.togglePlay();
|
||||
});
|
||||
navigator.mediaSession.setActionHandler('seekbackward', () => this.seekRelative(-30));
|
||||
navigator.mediaSession.setActionHandler('seekforward', () => this.seekRelative(30));
|
||||
navigator.mediaSession.setActionHandler('previoustrack', () => {
|
||||
this.audiobookInfo.folderBased ? this.previousTrack() : this.previousChapter();
|
||||
});
|
||||
navigator.mediaSession.setActionHandler('nexttrack', () => {
|
||||
this.audiobookInfo.folderBased ? this.nextTrack() : this.nextChapter();
|
||||
});
|
||||
navigator.mediaSession.setActionHandler('seekto', (details) => {
|
||||
if (details.seekTime !== undefined) {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
audio.currentTime = details.seekTime;
|
||||
this.currentTime = details.seekTime;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private updateMediaSessionMetadata(): void {
|
||||
if (!('mediaSession' in navigator)) return;
|
||||
|
||||
const title = this.audiobookInfo.folderBased
|
||||
? this.currentTrack?.title
|
||||
: this.getCurrentChapter()?.title || this.audiobookInfo.title;
|
||||
|
||||
navigator.mediaSession.metadata = new MediaMetadata({
|
||||
title: title || 'Untitled',
|
||||
artist: this.audiobookInfo.author || 'Unknown Author',
|
||||
album: this.audiobookInfo.title,
|
||||
artwork: this.coverUrl
|
||||
? [{ src: this.coverUrl, sizes: '512x512', type: 'image/png' }]
|
||||
: []
|
||||
});
|
||||
}
|
||||
|
||||
private updateMediaSessionPlaybackState(): void {
|
||||
if ('mediaSession' in navigator) {
|
||||
navigator.mediaSession.playbackState = this.isPlaying ? 'playing' : 'paused';
|
||||
}
|
||||
}
|
||||
|
||||
private updateMediaSessionPositionState(): void {
|
||||
if ('mediaSession' in navigator && 'setPositionState' in navigator.mediaSession) {
|
||||
try {
|
||||
navigator.mediaSession.setPositionState({
|
||||
duration: this.duration,
|
||||
playbackRate: this.playbackRate,
|
||||
position: this.currentTime
|
||||
});
|
||||
} catch {
|
||||
// Ignore errors from invalid position state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Playback controls
|
||||
togglePlay(): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (!audio) return;
|
||||
|
||||
if (this.isPlaying) {
|
||||
audio.pause();
|
||||
this.stopProgressSaveInterval();
|
||||
this.saveProgress();
|
||||
// Pause the listening session
|
||||
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
|
||||
} else {
|
||||
audio.play();
|
||||
this.startProgressSaveInterval();
|
||||
// Start or resume the listening session
|
||||
if (this.audiobookSessionService.isSessionActive()) {
|
||||
this.audiobookSessionService.resumeSession(Math.round(this.currentTime * 1000));
|
||||
} else {
|
||||
this.audiobookSessionService.startSession(
|
||||
this.bookId,
|
||||
Math.round(this.currentTime * 1000),
|
||||
this.playbackRate,
|
||||
this.audiobookInfo?.bookFileId,
|
||||
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
|
||||
);
|
||||
}
|
||||
}
|
||||
this.isPlaying = !this.isPlaying;
|
||||
this.updateMediaSessionPlaybackState();
|
||||
}
|
||||
|
||||
seek(event: SliderChangeEvent): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio && this.duration > 0 && event.value !== undefined) {
|
||||
audio.currentTime = event.value as number;
|
||||
this.currentTime = event.value as number;
|
||||
}
|
||||
}
|
||||
|
||||
seekRelative(seconds: number): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
const newTime = Math.max(0, Math.min(this.duration, audio.currentTime + seconds));
|
||||
audio.currentTime = newTime;
|
||||
this.currentTime = newTime;
|
||||
}
|
||||
}
|
||||
|
||||
// Volume controls
|
||||
setVolume(event: SliderChangeEvent): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (event.value !== undefined) {
|
||||
this.volume = event.value as number;
|
||||
this.isMuted = this.volume === 0;
|
||||
if (audio) {
|
||||
audio.volume = this.volume;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toggleMute(): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (!audio) return;
|
||||
|
||||
if (this.isMuted) {
|
||||
this.volume = this.previousVolume || 0.5;
|
||||
audio.volume = this.volume;
|
||||
this.isMuted = false;
|
||||
} else {
|
||||
this.previousVolume = this.volume;
|
||||
this.volume = 0;
|
||||
audio.volume = 0;
|
||||
this.isMuted = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Playback rate
|
||||
setPlaybackRate(rate: number): void {
|
||||
if (rate === undefined || rate === null) return;
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
this.playbackRate = rate;
|
||||
if (audio) {
|
||||
audio.playbackRate = rate;
|
||||
}
|
||||
this.updateMediaSessionPositionState();
|
||||
// Update session with new playback rate
|
||||
this.audiobookSessionService.updatePlaybackRate(rate);
|
||||
}
|
||||
|
||||
// Track navigation (folder-based)
|
||||
previousTrack(): void {
|
||||
if (this.currentTrackIndex > 0) {
|
||||
this.loadTrack(this.currentTrackIndex - 1);
|
||||
this.currentTime = 0;
|
||||
this.savedPosition = 0; // Reset saved position for new track
|
||||
if (this.isPlaying) {
|
||||
setTimeout(() => {
|
||||
this.audioElement?.nativeElement?.play();
|
||||
this.updateMediaSessionMetadata();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nextTrack(): void {
|
||||
if (this.audiobookInfo.tracks && this.currentTrackIndex < this.audiobookInfo.tracks.length - 1) {
|
||||
this.loadTrack(this.currentTrackIndex + 1);
|
||||
this.currentTime = 0;
|
||||
this.savedPosition = 0; // Reset saved position for new track
|
||||
if (this.isPlaying) {
|
||||
setTimeout(() => {
|
||||
this.audioElement?.nativeElement?.play();
|
||||
this.updateMediaSessionMetadata();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
selectTrack(track: AudiobookTrack): void {
|
||||
this.loadTrack(track.index);
|
||||
this.currentTime = 0;
|
||||
this.savedPosition = 0; // Reset saved position for new track
|
||||
this.showTrackList = false;
|
||||
setTimeout(() => {
|
||||
this.audioElement?.nativeElement?.play();
|
||||
this.isPlaying = true;
|
||||
this.startProgressSaveInterval();
|
||||
this.updateMediaSessionMetadata();
|
||||
this.updateMediaSessionPlaybackState();
|
||||
// Start or resume listening session
|
||||
if (this.audiobookSessionService.isSessionActive()) {
|
||||
this.audiobookSessionService.resumeSession(0);
|
||||
} else {
|
||||
this.audiobookSessionService.startSession(
|
||||
this.bookId, 0, this.playbackRate,
|
||||
this.audiobookInfo?.bookFileId, track.index
|
||||
);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// Chapter navigation (single-file)
|
||||
selectChapter(chapter: AudiobookChapter): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
audio.currentTime = chapter.startTimeMs / 1000;
|
||||
this.currentTime = chapter.startTimeMs / 1000;
|
||||
this.showTrackList = false;
|
||||
this.updateMediaSessionMetadata();
|
||||
if (!this.isPlaying) {
|
||||
audio.play();
|
||||
this.isPlaying = true;
|
||||
this.startProgressSaveInterval();
|
||||
this.updateMediaSessionPlaybackState();
|
||||
// Start or resume listening session
|
||||
if (this.audiobookSessionService.isSessionActive()) {
|
||||
this.audiobookSessionService.resumeSession(chapter.startTimeMs);
|
||||
} else {
|
||||
this.audiobookSessionService.startSession(
|
||||
this.bookId, chapter.startTimeMs, this.playbackRate,
|
||||
this.audiobookInfo?.bookFileId
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getCurrentChapter(): AudiobookChapter | undefined {
|
||||
if (!this.audiobookInfo?.chapters) return undefined;
|
||||
const currentMs = this.currentTime * 1000;
|
||||
return this.audiobookInfo.chapters.find(
|
||||
ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs
|
||||
);
|
||||
}
|
||||
|
||||
getCurrentChapterIndex(): number {
|
||||
const chapter = this.getCurrentChapter();
|
||||
return chapter?.index ?? 0;
|
||||
}
|
||||
|
||||
hasMultipleChapters(): boolean {
|
||||
return (this.audiobookInfo?.chapters?.length ?? 0) > 1;
|
||||
}
|
||||
|
||||
canGoPreviousChapter(): boolean {
|
||||
return this.getCurrentChapterIndex() > 0;
|
||||
}
|
||||
|
||||
canGoNextChapter(): boolean {
|
||||
const chapters = this.audiobookInfo?.chapters;
|
||||
if (!chapters) return false;
|
||||
return this.getCurrentChapterIndex() < chapters.length - 1;
|
||||
}
|
||||
|
||||
previousChapter(): void {
|
||||
const chapters = this.audiobookInfo?.chapters;
|
||||
if (!chapters) return;
|
||||
|
||||
const currentIndex = this.getCurrentChapterIndex();
|
||||
if (currentIndex > 0) {
|
||||
const prevChapter = chapters[currentIndex - 1];
|
||||
this.selectChapter(prevChapter);
|
||||
}
|
||||
}
|
||||
|
||||
nextChapter(): void {
|
||||
const chapters = this.audiobookInfo?.chapters;
|
||||
if (!chapters) return;
|
||||
|
||||
const currentIndex = this.getCurrentChapterIndex();
|
||||
if (currentIndex < chapters.length - 1) {
|
||||
const nextChapter = chapters[currentIndex + 1];
|
||||
this.selectChapter(nextChapter);
|
||||
}
|
||||
}
|
||||
|
||||
// Progress management - save every 5 seconds while playing
|
||||
private startProgressSaveInterval(): void {
|
||||
if (this.progressSaveInterval) return; // Already running
|
||||
|
||||
this.progressSaveInterval = setInterval(() => {
|
||||
if (this.isPlaying) {
|
||||
this.saveProgress();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
private stopProgressSaveInterval(): void {
|
||||
if (this.progressSaveInterval) {
|
||||
clearInterval(this.progressSaveInterval);
|
||||
this.progressSaveInterval = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private saveProgress(): void {
|
||||
if (!this.audiobookInfo) return;
|
||||
|
||||
const totalDuration = this.getTotalDuration();
|
||||
const currentPosition = this.getCurrentTotalPosition();
|
||||
const percentage = totalDuration > 0 ? (currentPosition / totalDuration) * 100 : 0;
|
||||
|
||||
// For folder-based: positionMs = track position (for seeking within track)
|
||||
// For single-file: positionMs = absolute position
|
||||
const positionMs = this.audiobookInfo.folderBased
|
||||
? Math.round(this.currentTime * 1000) // Track position
|
||||
: Math.round(currentPosition * 1000); // Absolute position
|
||||
|
||||
const progress: AudiobookProgress = {
|
||||
positionMs: positionMs,
|
||||
trackIndex: this.audiobookInfo.folderBased ? this.currentTrackIndex : undefined,
|
||||
percentage: Math.round(percentage * 10) / 10
|
||||
};
|
||||
|
||||
this.audiobookService.saveProgress(
|
||||
this.bookId,
|
||||
progress,
|
||||
this.audiobookInfo.bookFileId
|
||||
).subscribe();
|
||||
}
|
||||
|
||||
private getTotalDuration(): number {
|
||||
if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) {
|
||||
return this.audiobookInfo.tracks.reduce((sum, t) => sum + t.durationMs, 0) / 1000;
|
||||
}
|
||||
return this.duration;
|
||||
}
|
||||
|
||||
private getCurrentTotalPosition(): number {
|
||||
if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) {
|
||||
const currentTrack = this.audiobookInfo.tracks[this.currentTrackIndex];
|
||||
return (currentTrack?.cumulativeStartMs || 0) / 1000 + this.currentTime;
|
||||
}
|
||||
return this.currentTime;
|
||||
}
|
||||
|
||||
// Utility methods
|
||||
formatTime(seconds: number): string {
|
||||
if (!seconds || !isFinite(seconds)) return '0:00';
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const s = Math.floor(seconds % 60);
|
||||
|
||||
if (h > 0) {
|
||||
return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
|
||||
}
|
||||
return `${m}:${s.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
formatDuration(ms: number): string {
|
||||
return this.formatTime(ms / 1000);
|
||||
}
|
||||
|
||||
getProgressPercent(): number {
|
||||
return this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0;
|
||||
}
|
||||
|
||||
getBufferedPercent(): number {
|
||||
return this.duration > 0 ? (this.buffered / this.duration) * 100 : 0;
|
||||
}
|
||||
|
||||
onCoverError(): void {
|
||||
// Fallback to book cover if embedded cover fails
|
||||
// Only fallback once to prevent infinite loop
|
||||
if (this.coverUrl !== this.bookCoverUrl) {
|
||||
this.coverUrl = this.bookCoverUrl;
|
||||
} else {
|
||||
// Both covers failed, use a placeholder
|
||||
this.coverUrl = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
toggleTrackList(): void {
|
||||
this.showTrackList = !this.showTrackList;
|
||||
}
|
||||
|
||||
closeReader(): void {
|
||||
this.saveProgress();
|
||||
if (this.audiobookSessionService.isSessionActive()) {
|
||||
this.audiobookSessionService.endSession(Math.round(this.currentTime * 1000));
|
||||
}
|
||||
this.location.back();
|
||||
}
|
||||
|
||||
getVolumeIcon(): string {
|
||||
if (this.isMuted || this.volume === 0) return 'pi pi-volume-off';
|
||||
if (this.volume < 0.5) return 'pi pi-volume-down';
|
||||
return 'pi pi-volume-up';
|
||||
}
|
||||
|
||||
get currentTrack(): AudiobookTrack | undefined {
|
||||
return this.audiobookInfo?.tracks?.[this.currentTrackIndex];
|
||||
}
|
||||
|
||||
// ==================== SLEEP TIMER ====================
|
||||
|
||||
setSleepTimer(minutes: number): void {
|
||||
this.cancelSleepTimer();
|
||||
this.sleepTimerRemaining = minutes * 60;
|
||||
this.sleepTimerActive = true;
|
||||
this.sleepTimerEndOfChapter = false;
|
||||
this.originalVolume = this.volume;
|
||||
this.updateSleepTimerMenuVisibility();
|
||||
|
||||
this.sleepTimerInterval = setInterval(() => {
|
||||
this.sleepTimerRemaining--;
|
||||
|
||||
// Fade out volume in last 30 seconds
|
||||
if (this.sleepTimerRemaining <= 30 && this.sleepTimerRemaining > 0) {
|
||||
const fadeRatio = this.sleepTimerRemaining / 30;
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
audio.volume = this.originalVolume * fadeRatio;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.sleepTimerRemaining <= 0) {
|
||||
this.triggerSleepTimerStop();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: 'Sleep Timer',
|
||||
detail: `Playback will stop in ${minutes} minutes`
|
||||
});
|
||||
}
|
||||
|
||||
setSleepTimerEndOfChapter(): void {
|
||||
this.cancelSleepTimer();
|
||||
this.sleepTimerActive = true;
|
||||
this.sleepTimerEndOfChapter = true;
|
||||
this.sleepTimerRemaining = 0;
|
||||
this.originalVolume = this.volume;
|
||||
this.updateSleepTimerMenuVisibility();
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: 'Sleep Timer',
|
||||
detail: 'Playback will stop at end of chapter'
|
||||
});
|
||||
}
|
||||
|
||||
cancelSleepTimer(): void {
|
||||
if (this.sleepTimerInterval) {
|
||||
clearInterval(this.sleepTimerInterval);
|
||||
this.sleepTimerInterval = undefined;
|
||||
}
|
||||
|
||||
// Restore original volume if we were fading
|
||||
if (this.sleepTimerActive && this.originalVolume > 0) {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
audio.volume = this.originalVolume;
|
||||
this.volume = this.originalVolume;
|
||||
}
|
||||
}
|
||||
|
||||
this.sleepTimerActive = false;
|
||||
this.sleepTimerRemaining = 0;
|
||||
this.sleepTimerEndOfChapter = false;
|
||||
this.updateSleepTimerMenuVisibility();
|
||||
}
|
||||
|
||||
private triggerSleepTimerStop(): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
audio.pause();
|
||||
audio.volume = this.originalVolume;
|
||||
this.volume = this.originalVolume;
|
||||
}
|
||||
this.isPlaying = false;
|
||||
this.stopProgressSaveInterval();
|
||||
this.saveProgress();
|
||||
this.cancelSleepTimer();
|
||||
this.updateMediaSessionPlaybackState();
|
||||
// Pause the listening session
|
||||
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
|
||||
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: 'Sleep Timer',
|
||||
detail: 'Playback stopped by sleep timer'
|
||||
});
|
||||
}
|
||||
|
||||
private updateSleepTimerMenuVisibility(): void {
|
||||
// Show/hide cancel option based on timer state
|
||||
const cancelItem = this.sleepTimerOptions.find(item => item.label === 'Cancel timer');
|
||||
if (cancelItem) {
|
||||
cancelItem.visible = this.sleepTimerActive;
|
||||
}
|
||||
}
|
||||
|
||||
formatSleepTimerRemaining(): string {
|
||||
if (this.sleepTimerEndOfChapter) {
|
||||
return 'End of chapter';
|
||||
}
|
||||
const minutes = Math.floor(this.sleepTimerRemaining / 60);
|
||||
const seconds = this.sleepTimerRemaining % 60;
|
||||
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// Check for end of chapter in onTimeUpdate for sleep timer
|
||||
private checkSleepTimerEndOfChapter(): void {
|
||||
if (!this.sleepTimerEndOfChapter || !this.sleepTimerActive) return;
|
||||
|
||||
const currentChapter = this.getCurrentChapter();
|
||||
if (currentChapter) {
|
||||
const currentMs = this.currentTime * 1000;
|
||||
// If we're within 1 second of chapter end, trigger stop
|
||||
if (currentMs >= currentChapter.endTimeMs - 1000) {
|
||||
this.triggerSleepTimerStop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== BOOKMARKS ====================
|
||||
|
||||
loadBookmarks(): void {
|
||||
this.bookMarkService.getBookmarksForBook(this.bookId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(bookmarks => {
|
||||
this.bookmarks = bookmarks;
|
||||
});
|
||||
}
|
||||
|
||||
toggleBookmarkList(): void {
|
||||
this.showBookmarkList = !this.showBookmarkList;
|
||||
if (this.showBookmarkList && this.bookmarks.length === 0) {
|
||||
this.loadBookmarks();
|
||||
}
|
||||
}
|
||||
|
||||
addBookmark(): void {
|
||||
const currentChapter = this.getCurrentChapter();
|
||||
const currentTrack = this.currentTrack;
|
||||
|
||||
let title: string;
|
||||
if (this.audiobookInfo.folderBased && currentTrack) {
|
||||
title = `${currentTrack.title} - ${this.formatTime(this.currentTime)}`;
|
||||
} else if (currentChapter) {
|
||||
title = `${currentChapter.title} - ${this.formatTime(this.currentTime)}`;
|
||||
} else {
|
||||
title = `Bookmark at ${this.formatTime(this.currentTime)}`;
|
||||
}
|
||||
|
||||
const request: CreateBookMarkRequest = {
|
||||
bookId: this.bookId,
|
||||
title: title,
|
||||
positionMs: Math.round(this.currentTime * 1000),
|
||||
trackIndex: this.audiobookInfo.folderBased ? this.currentTrackIndex : undefined
|
||||
};
|
||||
|
||||
this.bookMarkService.createBookmark(request)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe({
|
||||
next: (bookmark) => {
|
||||
this.bookmarks = [...this.bookmarks, bookmark];
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Bookmark Added',
|
||||
detail: title
|
||||
});
|
||||
},
|
||||
error: (err) => {
|
||||
const isDuplicate = err?.status === 409;
|
||||
this.messageService.add({
|
||||
severity: isDuplicate ? 'warn' : 'error',
|
||||
summary: isDuplicate ? 'Bookmark Exists' : 'Error',
|
||||
detail: isDuplicate ? 'A bookmark already exists at this position' : 'Failed to add bookmark'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
goToBookmark(bookmark: BookMark): void {
|
||||
// Handle track switching for folder-based audiobooks
|
||||
if (this.audiobookInfo.folderBased && bookmark.trackIndex !== undefined && bookmark.trackIndex !== null) {
|
||||
if (bookmark.trackIndex !== this.currentTrackIndex) {
|
||||
this.loadTrack(bookmark.trackIndex);
|
||||
// Wait for track to load, then seek
|
||||
this.savedPosition = (bookmark.positionMs || 0) / 1000;
|
||||
} else {
|
||||
// Same track, just seek
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio && bookmark.positionMs) {
|
||||
audio.currentTime = bookmark.positionMs / 1000;
|
||||
this.currentTime = bookmark.positionMs / 1000;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single-file audiobook
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio && bookmark.positionMs) {
|
||||
audio.currentTime = bookmark.positionMs / 1000;
|
||||
this.currentTime = bookmark.positionMs / 1000;
|
||||
}
|
||||
}
|
||||
|
||||
this.showBookmarkList = false;
|
||||
|
||||
if (!this.isPlaying) {
|
||||
setTimeout(() => {
|
||||
this.audioElement?.nativeElement?.play();
|
||||
this.isPlaying = true;
|
||||
this.startProgressSaveInterval();
|
||||
// Start or resume listening session
|
||||
const positionMs = bookmark.positionMs || 0;
|
||||
if (this.audiobookSessionService.isSessionActive()) {
|
||||
this.audiobookSessionService.resumeSession(positionMs);
|
||||
} else {
|
||||
this.audiobookSessionService.startSession(
|
||||
this.bookId, positionMs, this.playbackRate,
|
||||
this.audiobookInfo?.bookFileId,
|
||||
this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined
|
||||
);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
deleteBookmark(event: MouseEvent, bookmarkId: number): void {
|
||||
event.stopPropagation();
|
||||
this.bookMarkService.deleteBookmark(bookmarkId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(() => {
|
||||
this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId);
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: 'Bookmark Deleted'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
formatBookmarkPosition(bookmark: BookMark): string {
|
||||
if (bookmark.positionMs) {
|
||||
return this.formatTime(bookmark.positionMs / 1000);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
export interface AudiobookInfo {
|
||||
bookId: number;
|
||||
bookFileId: number;
|
||||
title?: string;
|
||||
author?: string;
|
||||
narrator?: string;
|
||||
durationMs: number;
|
||||
bitrate?: number;
|
||||
codec?: string;
|
||||
sampleRate?: number;
|
||||
channels?: number;
|
||||
folderBased: boolean;
|
||||
chapters?: AudiobookChapter[];
|
||||
tracks?: AudiobookTrack[];
|
||||
}
|
||||
|
||||
export interface AudiobookChapter {
|
||||
index: number;
|
||||
title: string;
|
||||
startTimeMs: number;
|
||||
endTimeMs: number;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface AudiobookTrack {
|
||||
index: number;
|
||||
fileName: string;
|
||||
title: string;
|
||||
durationMs: number;
|
||||
fileSizeBytes: number;
|
||||
cumulativeStartMs: number;
|
||||
}
|
||||
|
||||
export interface AudiobookProgress {
|
||||
positionMs: number;
|
||||
trackIndex?: number;
|
||||
trackPositionMs?: number;
|
||||
percentage: number;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { API_CONFIG } from '../../../core/config/api-config';
|
||||
import { AudiobookInfo, AudiobookProgress } from './audiobook.model';
|
||||
import { AuthService } from '../../../shared/service/auth.service';
|
||||
import { BookFileProgress } from '../../book/model/book.model';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AudiobookService {
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/audiobook`;
|
||||
private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
getAudiobookInfo(bookId: number, bookType?: string): Observable<AudiobookInfo> {
|
||||
const params: Record<string, string> = {};
|
||||
if (bookType) {
|
||||
params['bookType'] = bookType;
|
||||
}
|
||||
return this.http.get<AudiobookInfo>(`${this.baseUrl}/${bookId}/info`, { params });
|
||||
}
|
||||
|
||||
getStreamUrl(bookId: number, trackIndex?: number): string {
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
let url = `${this.baseUrl}/${bookId}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
|
||||
if (trackIndex !== undefined && trackIndex !== null) {
|
||||
url += `&trackIndex=${trackIndex}`;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
getTrackStreamUrl(bookId: number, trackIndex: number): string {
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
return `${this.baseUrl}/${bookId}/track/${trackIndex}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
|
||||
}
|
||||
|
||||
getEmbeddedCoverUrl(bookId: number): string {
|
||||
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
|
||||
return `${this.baseUrl}/${bookId}/cover?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
|
||||
}
|
||||
|
||||
saveProgress(bookId: number, progress: AudiobookProgress, bookFileId?: number): Observable<void> {
|
||||
if (bookFileId) {
|
||||
const fileProgress: BookFileProgress = {
|
||||
bookFileId: bookFileId,
|
||||
positionData: progress.positionMs.toString(),
|
||||
positionHref: progress.trackIndex?.toString(),
|
||||
progressPercent: progress.percentage
|
||||
};
|
||||
return this.http.post<void>(`${this.booksUrl}/progress`, {
|
||||
bookId,
|
||||
fileProgress
|
||||
});
|
||||
}
|
||||
return this.http.post<void>(`${this.booksUrl}/progress`, {
|
||||
bookId,
|
||||
audiobookProgress: progress
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './audiobook-reader.component';
|
||||
export * from './audiobook.service';
|
||||
export * from './audiobook.model';
|
||||
@@ -2,7 +2,7 @@ import {Component, HostListener, inject, OnDestroy, OnInit} from '@angular/core'
|
||||
import {ActivatedRoute, Router} from '@angular/router';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {forkJoin, Subject} from 'rxjs';
|
||||
import {filter, first, takeUntil, timeout} from 'rxjs/operators';
|
||||
import {filter, first, map, switchMap, takeUntil, timeout} from 'rxjs/operators';
|
||||
import {PageTitleService} from "../../../shared/service/page-title.service";
|
||||
import {CbxReaderService} from '../../book/service/cbx-reader.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
@@ -55,6 +55,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
bookType!: BookType;
|
||||
bookId!: number;
|
||||
bookFileId?: number;
|
||||
altBookType?: string;
|
||||
pages: number[] = [];
|
||||
currentPage = 0;
|
||||
isLoading = true;
|
||||
@@ -129,34 +131,48 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.route.paramMap.subscribe((params) => {
|
||||
this.isLoading = true;
|
||||
this.bookId = +params.get('bookId')!;
|
||||
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
|
||||
|
||||
this.previousBookInSeries = null;
|
||||
this.nextBookInSeries = null;
|
||||
this.currentBook = null;
|
||||
|
||||
forkJoin([
|
||||
this.bookService.getBookByIdFromAPI(this.bookId, false),
|
||||
this.bookService.getBookSetting(this.bookId),
|
||||
this.userService.getMyself()
|
||||
]).subscribe({
|
||||
next: ([book, bookSettings, myself]) => {
|
||||
const userSettings = myself.userSettings;
|
||||
this.bookType = book.bookType;
|
||||
this.bookService.getBookByIdFromAPI(this.bookId, false).pipe(
|
||||
switchMap((book) => {
|
||||
// Use alternative bookType from query param if provided, otherwise use primary
|
||||
this.bookType = (this.altBookType as BookType) ?? book.primaryFile?.bookType!;
|
||||
this.currentBook = book;
|
||||
|
||||
// Determine which file ID to use for progress tracking
|
||||
if (this.altBookType) {
|
||||
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);
|
||||
this.bookFileId = altFile?.id;
|
||||
} else {
|
||||
this.bookFileId = book.primaryFile?.id;
|
||||
}
|
||||
|
||||
return forkJoin([
|
||||
this.bookService.getBookSetting(this.bookId, this.bookFileId!),
|
||||
this.userService.getMyself()
|
||||
]).pipe(map(([bookSettings, myself]) => ({ book, bookSettings, myself })));
|
||||
})
|
||||
).subscribe({
|
||||
next: ({ book, bookSettings, myself }) => {
|
||||
const userSettings = myself.userSettings;
|
||||
|
||||
this.pageTitle.setBookPageTitle(book);
|
||||
|
||||
const title = book.metadata?.title || book.fileName;
|
||||
this.headerService.initialize(this.bookId, title, this.destroy$);
|
||||
this.sidebarService.initialize(this.bookId, book, this.destroy$);
|
||||
this.sidebarService.initialize(this.bookId, book, this.destroy$, this.altBookType);
|
||||
|
||||
if (book.metadata?.seriesName) {
|
||||
this.loadSeriesNavigationAsync(book);
|
||||
}
|
||||
|
||||
const pagesObservable = this.bookType === CbxReaderComponent.TYPE_PDF
|
||||
? this.pdfReaderService.getAvailablePages(this.bookId)
|
||||
: this.cbxReaderService.getAvailablePages(this.bookId);
|
||||
? this.pdfReaderService.getAvailablePages(this.bookId, this.altBookType)
|
||||
: this.cbxReaderService.getAvailablePages(this.bookId, this.altBookType);
|
||||
|
||||
pagesObservable.subscribe({
|
||||
next: (pages) => {
|
||||
@@ -728,8 +744,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
private getPageImageUrl(pageIndex: number): string {
|
||||
return this.bookType === CbxReaderComponent.TYPE_PDF
|
||||
? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex])
|
||||
: this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex]);
|
||||
? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex], this.altBookType)
|
||||
: this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex], this.altBookType);
|
||||
}
|
||||
|
||||
get infiniteScrollImageUrls(): string[] {
|
||||
@@ -765,10 +781,10 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
: 0;
|
||||
|
||||
if (this.bookType === CbxReaderComponent.TYPE_CBX) {
|
||||
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
|
||||
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage, this.bookFileId).subscribe();
|
||||
}
|
||||
if (this.bookType === CbxReaderComponent.TYPE_PDF) {
|
||||
this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
|
||||
this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage, this.bookFileId).subscribe();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@
|
||||
@if (bookmarks.length > 0) {
|
||||
<ul class="item-list">
|
||||
@for (bookmark of bookmarks; track bookmark.id) {
|
||||
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi)">
|
||||
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi!)">
|
||||
<div class="item-content">
|
||||
<span class="item-title">{{ bookmark.title }}</span>
|
||||
<span class="item-meta">{{ bookmark.createdAt | date: 'MMM d, y' }}</span>
|
||||
|
||||
+6
-4
@@ -27,6 +27,7 @@ export class CbxSidebarService {
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private bookId!: number;
|
||||
private altBookType?: string;
|
||||
private bookType!: BookType;
|
||||
|
||||
private _isOpen = new BehaviorSubject<boolean>(false);
|
||||
@@ -66,9 +67,10 @@ export class CbxSidebarService {
|
||||
return this.bookType === 'PDF';
|
||||
}
|
||||
|
||||
initialize(bookId: number, book: Book, destroy$: Subject<void>): void {
|
||||
initialize(bookId: number, book: Book, destroy$: Subject<void>, altBookType?: string): void {
|
||||
this.bookId = bookId;
|
||||
this.bookType = book.bookType;
|
||||
this.altBookType = altBookType;
|
||||
this.bookType = (altBookType as BookType) ?? book.primaryFile?.bookType!;
|
||||
this.destroy$ = destroy$;
|
||||
|
||||
this._bookInfo.next({
|
||||
@@ -85,7 +87,7 @@ export class CbxSidebarService {
|
||||
|
||||
private loadPageInfo(): void {
|
||||
if (this.bookType === 'PDF') {
|
||||
this.pdfReaderService.getPageInfo(this.bookId)
|
||||
this.pdfReaderService.getPageInfo(this.bookId, this.altBookType)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(pdfInfo => {
|
||||
this._pdfPageCount.next(pdfInfo.pageCount);
|
||||
@@ -99,7 +101,7 @@ export class CbxSidebarService {
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.cbxReaderService.getPageInfo(this.bookId)
|
||||
this.cbxReaderService.getPageInfo(this.bookId, this.altBookType)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(pages => this._pages.next(pages));
|
||||
}
|
||||
|
||||
@@ -43,7 +43,10 @@ export class EpubStreamingService {
|
||||
private http = inject(HttpClient);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
getBookInfo(bookId: number): Observable<EpubBookInfo> {
|
||||
getBookInfo(bookId: number, bookType?: string): Observable<EpubBookInfo> {
|
||||
if (bookType) {
|
||||
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`, { params: { bookType } });
|
||||
}
|
||||
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`);
|
||||
}
|
||||
|
||||
|
||||
@@ -79,26 +79,26 @@ export class ReaderViewManagerService {
|
||||
);
|
||||
}
|
||||
|
||||
loadEpubStreaming(bookId: number): Observable<void> {
|
||||
loadEpubStreaming(bookId: number, bookType?: string): Observable<void> {
|
||||
if (!this.view) {
|
||||
return throwError(() => new Error('View not created'));
|
||||
}
|
||||
|
||||
return this.epubStreamingService.getBookInfo(bookId).pipe(
|
||||
switchMap(bookInfo => from(this.openStreamingBook(bookId, bookInfo))),
|
||||
return this.epubStreamingService.getBookInfo(bookId, bookType).pipe(
|
||||
switchMap(bookInfo => from(this.openStreamingBook(bookId, bookInfo, bookType))),
|
||||
map(() => undefined),
|
||||
catchError(err => throwError(() => err))
|
||||
);
|
||||
}
|
||||
|
||||
private async openStreamingBook(bookId: number, bookInfo: EpubBookInfo): Promise<void> {
|
||||
private async openStreamingBook(bookId: number, bookInfo: EpubBookInfo, bookType?: string): Promise<void> {
|
||||
const makeStreamingBook = (window as any).makeStreamingBook;
|
||||
if (!makeStreamingBook) {
|
||||
throw new Error('makeStreamingBook not available - Foliate script may not be loaded');
|
||||
}
|
||||
const baseUrl = this.epubStreamingService.getBaseUrl();
|
||||
const authToken = this.epubStreamingService.getAuthToken();
|
||||
const book = await makeStreamingBook(bookId, baseUrl, bookInfo, authToken);
|
||||
const book = await makeStreamingBook(bookId, baseUrl, bookInfo, authToken, bookType);
|
||||
await this.view.open(book);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {CommonModule} from '@angular/common';
|
||||
import {forkJoin, Observable, of, Subject, throwError} from 'rxjs';
|
||||
import {catchError, switchMap, takeUntil, tap} from 'rxjs/operators';
|
||||
import {catchError, map, switchMap, takeUntil, tap} from 'rxjs/operators';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {ReaderLoaderService} from './core/loader.service';
|
||||
import {ReaderViewManagerService} from './core/view-manager.service';
|
||||
@@ -17,7 +17,7 @@ import {ReaderHeaderService} from './layout/header/header.service';
|
||||
import {ReaderNoteService} from './features/notes/note.service';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {Book, BookType} from '../../book/model/book.model';
|
||||
import {ReaderHeaderComponent} from './layout/header/header.component';
|
||||
import {ReaderSidebarComponent} from './layout/sidebar/sidebar.component';
|
||||
import {ReaderLeftSidebarComponent} from './layout/panel/panel.component';
|
||||
@@ -83,6 +83,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
|
||||
public stateService = inject(ReaderStateService);
|
||||
|
||||
protected bookId!: number;
|
||||
protected altBookType?: string;
|
||||
|
||||
private hasLoadedOnce = false;
|
||||
private _fileUrl: string | null = null;
|
||||
@@ -207,23 +208,39 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
private loadBookFromAPI(): Observable<void> {
|
||||
this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
|
||||
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
|
||||
|
||||
return this.stateService.initializeState(this.bookId).pipe(
|
||||
switchMap(() => forkJoin({
|
||||
state: this.stateService.initializeState(this.bookId),
|
||||
book: this.bookService.getBookByIdFromAPI(this.bookId, false)
|
||||
})),
|
||||
switchMap(({book}) => {
|
||||
return this.bookService.getBookByIdFromAPI(this.bookId, false).pipe(
|
||||
switchMap((book) => {
|
||||
this.book = book;
|
||||
|
||||
this.progressService.initialize(this.bookId, book.bookType!);
|
||||
// Use alternative bookType from query param if provided, otherwise use primary
|
||||
const bookType = (this.altBookType as BookType) ?? book.primaryFile?.bookType!;
|
||||
|
||||
// Determine which file ID to use for progress tracking
|
||||
let bookFileId: number | undefined;
|
||||
if (this.altBookType) {
|
||||
// Look for the alternative format file with matching type
|
||||
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);
|
||||
bookFileId = altFile?.id;
|
||||
} else {
|
||||
// Use the primary file
|
||||
bookFileId = book.primaryFile?.id;
|
||||
}
|
||||
|
||||
return this.stateService.initializeState(this.bookId, bookFileId!).pipe(
|
||||
map(() => ({ book, bookType, bookFileId }))
|
||||
);
|
||||
}),
|
||||
switchMap(({book, bookType, bookFileId}) => {
|
||||
this.progressService.initialize(this.bookId, bookType, bookFileId);
|
||||
this.selectionService.initialize(this.bookId, this.destroy$);
|
||||
this.headerService.initialize(this.bookId, book.metadata?.title || '', this.destroy$);
|
||||
|
||||
// Use streaming for EPUB if query param is set, blob loading otherwise (default)
|
||||
const useStreaming = this.route.snapshot.queryParamMap.get('streaming') === 'true';
|
||||
const loadBook$ = book.bookType === 'EPUB' && useStreaming
|
||||
? this.viewManager.loadEpubStreaming(this.bookId)
|
||||
const loadBook$ = bookType === 'EPUB' && useStreaming
|
||||
? this.viewManager.loadEpubStreaming(this.bookId, this.altBookType)
|
||||
: this.loadBookBlob();
|
||||
|
||||
return loadBook$.pipe(
|
||||
@@ -237,7 +254,12 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
|
||||
switchMap(() => {
|
||||
if (!this.hasLoadedOnce) {
|
||||
this.hasLoadedOnce = true;
|
||||
return this.viewManager.goTo(book.epubProgress!.cfi);
|
||||
// Navigate to saved position if progress exists, otherwise go to first page
|
||||
if (book.epubProgress?.cfi) {
|
||||
return this.viewManager.goTo(book.epubProgress.cfi);
|
||||
} else {
|
||||
return this.viewManager.goTo(0);
|
||||
}
|
||||
}
|
||||
return of(undefined);
|
||||
})
|
||||
@@ -247,7 +269,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private loadBookBlob(): Observable<void> {
|
||||
return this.bookService.getFileContent(this.bookId).pipe(
|
||||
return this.bookService.getFileContent(this.bookId, this.altBookType).pipe(
|
||||
switchMap(fileBlob => {
|
||||
const fileUrl = URL.createObjectURL(fileBlob);
|
||||
this._fileUrl = fileUrl;
|
||||
|
||||
+1
-1
@@ -96,7 +96,7 @@
|
||||
@if (bookmarks.length > 0) {
|
||||
<ul class="item-list">
|
||||
@for (bookmark of bookmarks; track bookmark.id) {
|
||||
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi)">
|
||||
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi!)">
|
||||
<div class="item-content">
|
||||
<span class="item-title">{{ bookmark.title }}</span>
|
||||
<span class="item-meta">{{ bookmark.createdAt | date: 'MMM d, y' }}</span>
|
||||
|
||||
@@ -30,6 +30,7 @@ export class ReaderProgressService {
|
||||
|
||||
private bookId!: number;
|
||||
private bookType!: BookType;
|
||||
private bookFileId?: number;
|
||||
private hasStartedSession = false;
|
||||
|
||||
private _currentCfi: string | null = null;
|
||||
@@ -61,9 +62,10 @@ export class ReaderProgressService {
|
||||
return this._currentPageInfo;
|
||||
}
|
||||
|
||||
initialize(bookId: number, bookType: BookType): void {
|
||||
initialize(bookId: number, bookType: BookType, bookFileId?: number): void {
|
||||
this.bookId = bookId;
|
||||
this.bookType = bookType;
|
||||
this.bookFileId = bookFileId;
|
||||
this.hasStartedSession = false;
|
||||
}
|
||||
|
||||
@@ -80,7 +82,7 @@ export class ReaderProgressService {
|
||||
}
|
||||
|
||||
if (cfi && percentage !== null) {
|
||||
this.bookPatchService.saveEpubProgress(this.bookId, cfi, href, percentage);
|
||||
this.bookPatchService.saveEpubProgress(this.bookId, cfi, href, percentage, this.bookFileId);
|
||||
this.readingSessionService.updateProgress(cfi, percentage);
|
||||
}
|
||||
|
||||
|
||||
@@ -93,10 +93,10 @@ export class ReaderStateService {
|
||||
this.loadCustomFontsIntoList();
|
||||
}
|
||||
|
||||
initializeState(bookId: number): Observable<void> {
|
||||
initializeState(bookId: number, bookFileId: number): Observable<void> {
|
||||
return forkJoin([
|
||||
this.userService.getMyself(),
|
||||
this.bookService.getBookSetting(bookId)
|
||||
this.bookService.getBookSetting(bookId, bookFileId)
|
||||
]).pipe(
|
||||
tap(([myself, bookSetting]) => {
|
||||
const settingScope = myself.userSettings.perBookSetting.epub;
|
||||
|
||||
@@ -4,6 +4,7 @@ import {NgxExtendedPdfViewerModule, ZoomType} from 'ngx-extended-pdf-viewer';
|
||||
import {PageTitleService} from "../../../shared/service/page-title.service";
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {forkJoin, Subscription} from 'rxjs';
|
||||
import {map, switchMap} from 'rxjs/operators';
|
||||
import {BookSetting} from '../../book/model/book.model';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
|
||||
@@ -31,6 +32,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
bookData!: string | Blob;
|
||||
bookId!: number;
|
||||
bookFileId?: number;
|
||||
private appSettingsSubscription!: Subscription;
|
||||
|
||||
private bookService = inject(BookService);
|
||||
@@ -46,17 +48,21 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
||||
this.isLoading = true;
|
||||
this.bookId = +params.get('bookId')!;
|
||||
|
||||
const myself$ = this.userService.getMyself();
|
||||
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false);
|
||||
const bookSetting$ = this.bookService.getBookSetting(this.bookId);
|
||||
const pdfData$ = this.bookService.getFileContent(this.bookId);
|
||||
this.bookService.getBookByIdFromAPI(this.bookId, false).pipe(
|
||||
switchMap((book) => {
|
||||
// Set the book file ID for progress tracking
|
||||
this.bookFileId = book.primaryFile?.id;
|
||||
|
||||
forkJoin([book$, bookSetting$, pdfData$, myself$]).subscribe({
|
||||
next: (results) => {
|
||||
const pdfMeta = results[0];
|
||||
const pdfPrefs = results[1];
|
||||
const pdfData = results[2];
|
||||
const myself = results[3];
|
||||
return forkJoin([
|
||||
this.bookService.getBookSetting(this.bookId, this.bookFileId!),
|
||||
this.bookService.getFileContent(this.bookId),
|
||||
this.userService.getMyself()
|
||||
]).pipe(map(([bookSetting, pdfData, myself]) => ({ book, bookSetting, pdfData, myself })));
|
||||
})
|
||||
).subscribe({
|
||||
next: ({ book, bookSetting, pdfData, myself }) => {
|
||||
const pdfMeta = book;
|
||||
const pdfPrefs = bookSetting;
|
||||
|
||||
this.pageTitle.setBookPageTitle(pdfMeta);
|
||||
|
||||
@@ -115,7 +121,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
updateProgress(): void {
|
||||
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
|
||||
this.bookService.savePdfProgress(this.bookId, this.page, percentage).subscribe();
|
||||
this.bookService.savePdfProgress(this.bookId, this.page, percentage, this.bookFileId).subscribe();
|
||||
}
|
||||
|
||||
onPdfPagesLoaded(event: { pagesCount: number }): void {
|
||||
|
||||
@@ -1,25 +1,19 @@
|
||||
@use '../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.main-container {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
height: calc(100dvh - 10.5rem);
|
||||
overflow-y: auto;
|
||||
border-width: 1px;
|
||||
border-radius: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
height: calc(100dvh - 11.65rem);
|
||||
}
|
||||
}
|
||||
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
@include settings.settings-page-header;
|
||||
|
||||
.settings-header {
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<p-toast position="top-right"></p-toast>
|
||||
|
||||
<div class="main-container enclosing-container">
|
||||
<div class="main-container">
|
||||
<div class="settings-header">
|
||||
<h2 class="settings-title">
|
||||
<i class="pi pi-book"></i>
|
||||
|
||||
+16
-50
@@ -1,45 +1,27 @@
|
||||
@use '../../../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.main-container {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
|
||||
.settings-header {
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
@include settings.settings-page-header;
|
||||
|
||||
.settings-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.75rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
@include settings.settings-page-title;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.settings-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 1rem;
|
||||
@include settings.settings-page-description;
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
margin-top: 1.5rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding-left: 0;
|
||||
@@ -53,42 +35,26 @@
|
||||
}
|
||||
|
||||
.section-header {
|
||||
@include settings.settings-section-header;
|
||||
margin-bottom: 1rem;
|
||||
margin-left: 1rem;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
@include settings.settings-section-title;
|
||||
margin: 0 0 0.5rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.section-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.settings-card {
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
background: var(--p-content-background);
|
||||
@include settings.settings-card;
|
||||
padding: 1rem 1.5rem 1.5rem 1.5rem;
|
||||
margin-left: 1rem;
|
||||
margin-right: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 1rem;
|
||||
@@ -121,7 +87,7 @@
|
||||
|
||||
.setting-label {
|
||||
display: block;
|
||||
font-weight: 600;
|
||||
font-weight: settings.$settings-section-title-weight;
|
||||
color: var(--p-text-color);
|
||||
font-size: 1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
@@ -154,7 +120,7 @@
|
||||
|
||||
.setting-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
font-size: settings.$settings-section-description-size;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -181,7 +147,7 @@
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
border-radius: settings.$settings-card-border-radius;
|
||||
background: rgba(220, 38, 38, 0.1);
|
||||
border: 1px solid rgba(220, 38, 38, 0.3);
|
||||
color: var(--p-red-400);
|
||||
@@ -203,13 +169,13 @@
|
||||
h3 {
|
||||
margin: 0 0 0.5rem 0;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
font-weight: settings.$settings-section-title-weight;
|
||||
color: var(--p-red-300);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
font-size: settings.$settings-section-description-size;
|
||||
line-height: 1.5;
|
||||
color: var(--p-red-400);
|
||||
}
|
||||
|
||||
-107
@@ -1,107 +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 {HardcoverSyncSettingsService, HardcoverSyncSettings} from './hardcover-sync-settings.service';
|
||||
|
||||
describe('HardcoverSyncSettingsService', () => {
|
||||
let service: HardcoverSyncSettingsService;
|
||||
let httpClientMock: any;
|
||||
|
||||
const mockSettings: HardcoverSyncSettings = {
|
||||
hardcoverApiKey: 'hardcover-key',
|
||||
hardcoverSyncEnabled: true
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
put: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
HardcoverSyncSettingsService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(HardcoverSyncSettingsService));
|
||||
});
|
||||
|
||||
it('should get Hardcover sync settings', () => {
|
||||
httpClientMock.get.mockReturnValue(of(mockSettings));
|
||||
service.getSettings().subscribe(settings => {
|
||||
expect(settings).toEqual(mockSettings);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v1/hardcover-sync-settings'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should update Hardcover sync settings', () => {
|
||||
httpClientMock.put.mockReturnValue(of(mockSettings));
|
||||
service.updateSettings(mockSettings).subscribe(settings => {
|
||||
expect(settings).toEqual(mockSettings);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/hardcover-sync-settings'), mockSettings);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle getSettings error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.getSettings().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle updateSettings error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.updateSettings(mockSettings).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('HardcoverSyncSettingsService - API Contract Tests', () => {
|
||||
let service: HardcoverSyncSettingsService;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
put: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
HardcoverSyncSettingsService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(HardcoverSyncSettingsService));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for getSettings', () => {
|
||||
httpClientMock.get.mockReturnValue(of({}));
|
||||
service.getSettings().subscribe();
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/hardcover-sync-settings$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for updateSettings', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
const settings: HardcoverSyncSettings = {
|
||||
hardcoverApiKey: 'key',
|
||||
hardcoverSyncEnabled: false
|
||||
};
|
||||
service.updateSettings(settings).subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/hardcover-sync-settings$/), settings);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
<p-toast position="top-right"></p-toast>
|
||||
<p-confirmDialog></p-confirmDialog>
|
||||
|
||||
<div class="main-container enclosing-container">
|
||||
<div class="main-container">
|
||||
<div class="settings-header">
|
||||
<h2 class="settings-title">
|
||||
<i class="pi pi-tablet"></i>
|
||||
|
||||
+16
-50
@@ -1,45 +1,27 @@
|
||||
@use '../../../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.main-container {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
|
||||
.settings-header {
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
@include settings.settings-page-header;
|
||||
|
||||
.settings-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.75rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
@include settings.settings-page-title;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.settings-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 1rem;
|
||||
@include settings.settings-page-description;
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.preferences-section {
|
||||
@@ -49,38 +31,22 @@
|
||||
}
|
||||
|
||||
.section-header {
|
||||
@include settings.settings-section-header;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
@include settings.settings-section-title;
|
||||
margin: 0 0 0.5rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.section-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.settings-card {
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
background: var(--p-content-background);
|
||||
@include settings.settings-card;
|
||||
padding: 1.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.setting-item {
|
||||
@@ -100,7 +66,7 @@
|
||||
|
||||
.setting-label {
|
||||
display: block;
|
||||
font-weight: 600;
|
||||
font-weight: settings.$settings-section-title-weight;
|
||||
color: var(--p-text-color);
|
||||
font-size: 1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
@@ -144,7 +110,7 @@
|
||||
|
||||
.setting-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
font-size: settings.$settings-section-description-size;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -188,7 +154,7 @@
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
border-radius: settings.$settings-card-border-radius;
|
||||
background: rgba(220, 38, 38, 0.1);
|
||||
border: 1px solid rgba(220, 38, 38, 0.3);
|
||||
color: var(--p-red-400);
|
||||
@@ -203,13 +169,13 @@
|
||||
h3 {
|
||||
margin: 0 0 0.5rem 0;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
font-weight: settings.$settings-section-title-weight;
|
||||
color: var(--p-red-300);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
font-size: settings.$settings-section-description-size;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
-203
@@ -1,203 +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 {KoboService, KoboSyncSettings} from './kobo.service';
|
||||
|
||||
describe('KoboService', () => {
|
||||
let service: KoboService;
|
||||
let httpClientMock: any;
|
||||
|
||||
const mockSettings: KoboSyncSettings = {
|
||||
token: 'abc123',
|
||||
syncEnabled: true,
|
||||
progressMarkAsReadingThreshold: 10,
|
||||
progressMarkAsFinishedThreshold: 90,
|
||||
autoAddToShelf: false,
|
||||
hardcoverApiKey: 'hardcover-key',
|
||||
hardcoverSyncEnabled: true
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
put: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
KoboService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(KoboService));
|
||||
});
|
||||
|
||||
it('should get user Kobo settings', () => {
|
||||
httpClientMock.get.mockReturnValue(of(mockSettings));
|
||||
service.getUser().subscribe(settings => {
|
||||
expect(settings).toEqual(mockSettings);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should create or update token', () => {
|
||||
httpClientMock.put.mockReturnValue(of(mockSettings));
|
||||
service.createOrUpdateToken().subscribe(settings => {
|
||||
expect(settings).toEqual(mockSettings);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings/token'), null);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update settings', () => {
|
||||
httpClientMock.put.mockReturnValue(of(mockSettings));
|
||||
service.updateSettings(mockSettings).subscribe(settings => {
|
||||
expect(settings).toEqual(mockSettings);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings'), mockSettings);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle getUser error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.getUser().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle createOrUpdateToken error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.createOrUpdateToken().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle updateSettings error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.updateSettings(mockSettings).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('KoboService - API Contract Tests', () => {
|
||||
let service: KoboService;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
put: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
KoboService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(KoboService));
|
||||
});
|
||||
|
||||
it('should validate all required KoboSyncSettings fields exist', () => {
|
||||
const requiredFields: (keyof KoboSyncSettings)[] = [
|
||||
'token', 'syncEnabled', 'autoAddToShelf'
|
||||
];
|
||||
|
||||
const mockResponse: KoboSyncSettings = {
|
||||
token: 'abc',
|
||||
syncEnabled: true,
|
||||
autoAddToShelf: false,
|
||||
progressMarkAsReadingThreshold: 10,
|
||||
progressMarkAsFinishedThreshold: 90,
|
||||
hardcoverApiKey: 'hardcover-key',
|
||||
hardcoverSyncEnabled: true
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||
|
||||
service.getUser().subscribe(settings => {
|
||||
requiredFields.forEach(field => {
|
||||
expect(settings).toHaveProperty(field);
|
||||
expect(settings[field]).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns KoboSyncSettings without required token field', () => {
|
||||
const invalidResponse = {
|
||||
syncEnabled: true,
|
||||
autoAddToShelf: false
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
|
||||
service.getUser().subscribe(settings => {
|
||||
expect(settings).not.toHaveProperty('token');
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns KoboSyncSettings without required syncEnabled field', () => {
|
||||
const invalidResponse = {
|
||||
token: 'abc',
|
||||
autoAddToShelf: false
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
|
||||
service.getUser().subscribe(settings => {
|
||||
expect(settings).not.toHaveProperty('syncEnabled');
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns KoboSyncSettings without required autoAddToShelf field', () => {
|
||||
const invalidResponse = {
|
||||
token: 'abc',
|
||||
syncEnabled: true
|
||||
};
|
||||
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
|
||||
service.getUser().subscribe(settings => {
|
||||
expect(settings).not.toHaveProperty('autoAddToShelf');
|
||||
});
|
||||
});
|
||||
|
||||
it('should call correct endpoint for getUser', () => {
|
||||
httpClientMock.get.mockReturnValue(of({}));
|
||||
service.getUser().subscribe();
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for createOrUpdateToken', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
service.createOrUpdateToken().subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings\/token$/), null);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for updateSettings', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
const settings: KoboSyncSettings = {
|
||||
token: 'abc',
|
||||
syncEnabled: true,
|
||||
autoAddToShelf: false
|
||||
};
|
||||
service.updateSettings(settings).subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings$/), settings);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<p-toast position="top-right"></p-toast>
|
||||
|
||||
<div class="main-container enclosing-container">
|
||||
<div class="main-container">
|
||||
<div class="settings-header">
|
||||
<h2 class="settings-title">
|
||||
<i class="pi pi-mobile"></i>
|
||||
|
||||
+20
-69
@@ -1,101 +1,52 @@
|
||||
@use '../../../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.main-container {
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
|
||||
.settings-header {
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
@include settings.settings-page-header;
|
||||
|
||||
.settings-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.75rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
@include settings.settings-page-title;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.settings-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 1rem;
|
||||
@include settings.settings-page-description;
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding-left: 0;
|
||||
}
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.preferences-section {
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 0;
|
||||
@media (min-width: 768px) {
|
||||
padding: 0 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
.section-header {
|
||||
@include settings.settings-section-header;
|
||||
margin-top: 1.25rem;
|
||||
margin-bottom: 1rem;
|
||||
margin-left: 1rem;
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
@include settings.settings-section-title;
|
||||
margin: 0 0 0.5rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.section-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.settings-card {
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
background: var(--p-content-background);
|
||||
padding: 1rem 1.5rem 1.5rem 1.5rem;
|
||||
margin-left: 1rem;
|
||||
margin-right: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@include settings.settings-card;
|
||||
gap: 2rem;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 1rem;
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-item {
|
||||
@@ -122,9 +73,9 @@
|
||||
|
||||
.setting-label {
|
||||
display: block;
|
||||
font-weight: 600;
|
||||
font-weight: settings.$settings-section-title-weight;
|
||||
color: var(--p-text-color);
|
||||
font-size: 1rem;
|
||||
font-size: settings.$settings-label-size;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
@@ -155,7 +106,7 @@
|
||||
|
||||
.setting-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
font-size: settings.$settings-description-size;
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -213,7 +164,7 @@
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
border-radius: settings.$settings-card-border-radius;
|
||||
background: rgba(220, 38, 38, 0.1);
|
||||
border: 1px solid rgba(220, 38, 38, 0.3);
|
||||
color: var(--p-red-400);
|
||||
@@ -228,13 +179,13 @@
|
||||
h3 {
|
||||
margin: 0 0 0.5rem 0;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
font-weight: settings.$settings-section-title-weight;
|
||||
color: var(--p-red-300);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
font-size: settings.$settings-section-description-size;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
-195
@@ -1,195 +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 {KoreaderService, KoreaderUser} from './koreader.service';
|
||||
|
||||
describe('KoreaderService', () => {
|
||||
let service: KoreaderService;
|
||||
let httpClientMock: any;
|
||||
|
||||
const mockUser: KoreaderUser = {
|
||||
username: 'testuser',
|
||||
password: 'secret',
|
||||
syncEnabled: true,
|
||||
syncWithBookloreReader: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
KoreaderService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(KoreaderService));
|
||||
});
|
||||
|
||||
it('should create user', () => {
|
||||
httpClientMock.put.mockReturnValue(of(mockUser));
|
||||
service.createUser('testuser', 'secret').subscribe(user => {
|
||||
expect(user).toEqual(mockUser);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/me'),
|
||||
{username: 'testuser', password: 'secret'}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should get user', () => {
|
||||
httpClientMock.get.mockReturnValue(of(mockUser));
|
||||
service.getUser().subscribe(user => {
|
||||
expect(user).toEqual(mockUser);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/me'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should toggle sync', () => {
|
||||
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||
service.toggleSync(true).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.patch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/me/sync'),
|
||||
null,
|
||||
{params: {enabled: 'true'}}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle createUser error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.createUser('testuser', 'secret').subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle getUser error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.getUser().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle toggleSync error', () => {
|
||||
httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.toggleSync(false).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('KoreaderService - API Contract Tests', () => {
|
||||
let service: KoreaderService;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
patch: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
KoreaderService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
const injector = TestBed.inject(EnvironmentInjector);
|
||||
service = runInInjectionContext(injector, () => TestBed.inject(KoreaderService));
|
||||
});
|
||||
|
||||
it('should validate all required KoreaderUser fields exist', () => {
|
||||
const requiredFields: (keyof KoreaderUser)[] = ['username', 'password', 'syncEnabled', 'syncWithBookloreReader'];
|
||||
const mockResponse: KoreaderUser = {
|
||||
username: 'test',
|
||||
password: 'pw',
|
||||
syncEnabled: true,
|
||||
syncWithBookloreReader: false
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of(mockResponse));
|
||||
service.getUser().subscribe(user => {
|
||||
requiredFields.forEach(field => {
|
||||
expect(user).toHaveProperty(field);
|
||||
expect(user[field]).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns KoreaderUser without required username field', () => {
|
||||
const invalidResponse = {
|
||||
password: 'pw',
|
||||
syncEnabled: true
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
service.getUser().subscribe(user => {
|
||||
expect(user).not.toHaveProperty('username');
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns KoreaderUser without required password field', () => {
|
||||
const invalidResponse = {
|
||||
username: 'test',
|
||||
syncEnabled: true
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
service.getUser().subscribe(user => {
|
||||
expect(user).not.toHaveProperty('password');
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns KoreaderUser without required syncEnabled field', () => {
|
||||
const invalidResponse = {
|
||||
username: 'test',
|
||||
password: 'pw'
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
service.getUser().subscribe(user => {
|
||||
expect(user).not.toHaveProperty('syncEnabled');
|
||||
});
|
||||
});
|
||||
|
||||
it('should call correct endpoint for createUser', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
service.createUser('u', 'p').subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/koreader-users\/me$/),
|
||||
{username: 'u', password: 'p'}
|
||||
);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for getUser', () => {
|
||||
httpClientMock.get.mockReturnValue(of({}));
|
||||
service.getUser().subscribe();
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/koreader-users\/me$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for toggleSync', () => {
|
||||
httpClientMock.patch.mockReturnValue(of({}));
|
||||
service.toggleSync(true).subscribe();
|
||||
expect(httpClientMock.patch).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/api\/v1\/koreader-users\/me\/sync$/),
|
||||
null,
|
||||
{params: {enabled: 'true'}}
|
||||
);
|
||||
});
|
||||
});
|
||||
+10
-10
@@ -1,13 +1,13 @@
|
||||
<div class="device-settings-container">
|
||||
<div class="koreader-section">
|
||||
<app-koreader-settings-component></app-koreader-settings-component>
|
||||
</div>
|
||||
<p-divider></p-divider>
|
||||
<div class="hardcover-section">
|
||||
<app-hardcover-settings-component></app-hardcover-settings-component>
|
||||
</div>
|
||||
<p-divider></p-divider>
|
||||
<div class="kobo-section">
|
||||
<app-kobo-sync-setting-component></app-kobo-sync-setting-component>
|
||||
<div class="settings-content">
|
||||
<div class="preferences-section">
|
||||
<app-koreader-settings-component></app-koreader-settings-component>
|
||||
</div>
|
||||
<div class="preferences-section">
|
||||
<app-hardcover-settings-component></app-hardcover-settings-component>
|
||||
</div>
|
||||
<div class="preferences-section">
|
||||
<app-kobo-sync-setting-component></app-kobo-sync-setting-component>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+7
-17
@@ -1,21 +1,11 @@
|
||||
@use '../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.device-settings-container {
|
||||
width: 100%;
|
||||
height: calc(100dvh - 10.5rem);
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 0.5rem;
|
||||
|
||||
@media (min-width: 768px) {
|
||||
height: calc(100dvh - 11.65rem);
|
||||
}
|
||||
@include settings.settings-page-container;
|
||||
}
|
||||
|
||||
.koreader-section {
|
||||
padding-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.hardcover-section,
|
||||
.kobo-section {
|
||||
padding-top: 1rem;
|
||||
padding-bottom: 1rem;
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {Component} from '@angular/core';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {KoreaderSettingsComponent} from './component/koreader-settings/koreader-settings-component';
|
||||
import {KoboSyncSettingsComponent} from './component/kobo-sync-settings/kobo-sync-settings-component';
|
||||
import {HardcoverSettingsComponent} from './component/hardcover-settings/hardcover-settings-component';
|
||||
@@ -9,8 +8,7 @@ import {HardcoverSettingsComponent} from './component/hardcover-settings/hardcov
|
||||
imports: [
|
||||
KoreaderSettingsComponent,
|
||||
KoboSyncSettingsComponent,
|
||||
HardcoverSettingsComponent,
|
||||
Divider
|
||||
HardcoverSettingsComponent
|
||||
],
|
||||
templateUrl: './device-settings-component.html',
|
||||
styleUrl: './device-settings-component.scss'
|
||||
|
||||
+177
-233
@@ -1,18 +1,18 @@
|
||||
<div class="main-container enclosing-container">
|
||||
<div class="settings-header">
|
||||
<div class="section-title-group">
|
||||
<div>
|
||||
<h2 class="settings-title">
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-server"></i>
|
||||
Email Providers
|
||||
</h2>
|
||||
<p class="settings-description">
|
||||
Configure email-sending services like Gmail, Outlook, or custom SMTP servers for sending books via email. The default email provider will be used for 'Quick Book Send' located in the Book Card menu.
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Configure email-sending services like Gmail, Outlook, or custom SMTP servers. The default provider is used for 'Quick Book Send' in the Book Card menu.
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-plus"
|
||||
label="Create Provider"
|
||||
label="Add Provider"
|
||||
severity="success"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
@@ -21,179 +21,42 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-content">
|
||||
<div class="preferences-section">
|
||||
<div class="table-card">
|
||||
<p-table [value]="emailProviders" [scrollable]="true" scrollHeight="flex">
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th style="width: 5%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-star"></i>
|
||||
<span>Default</span>
|
||||
<div class="section-body">
|
||||
@if (emailProviders.length === 0) {
|
||||
<div class="empty-state">
|
||||
<i class="pi pi-envelope"></i>
|
||||
<p class="empty-title">No email providers configured</p>
|
||||
<p class="empty-subtitle">Create your first email provider to start sending books</p>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="providers-list">
|
||||
@for (provider of emailProviders; track provider.id) {
|
||||
<div class="provider-item" [class.is-default]="provider.id === defaultProviderId">
|
||||
<div class="provider-header">
|
||||
<div class="provider-info">
|
||||
<div class="provider-name-row">
|
||||
<p-radioButton
|
||||
name="defaultProvider"
|
||||
[value]="provider.id"
|
||||
[(ngModel)]="defaultProviderId"
|
||||
(onClick)="setDefaultProvider(provider)">
|
||||
</p-radioButton>
|
||||
@if (provider.isEditing) {
|
||||
<input type="text" pInputText [(ngModel)]="provider.name" placeholder="Provider name" class="name-input"/>
|
||||
} @else {
|
||||
<span class="provider-name">{{ provider.name }}</span>
|
||||
@if (provider.shared) {
|
||||
<span class="shared-badge" pTooltip="Shared with all users">
|
||||
<i class="pi pi-share-alt"></i>
|
||||
</span>
|
||||
}
|
||||
@if (provider.id === defaultProviderId) {
|
||||
<span class="default-badge">Default</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 20%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-tag"></i>
|
||||
<span>Name</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 14%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-server"></i>
|
||||
<span>Host</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 5%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-link"></i>
|
||||
<span>Port</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 13%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-user"></i>
|
||||
<span>Username</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 11%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-lock"></i>
|
||||
<span>Password</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 11%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-envelope"></i>
|
||||
<span>From Address</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 4%;" class="permission-header">Auth</th>
|
||||
<th style="width: 5%;" class="permission-header">StartTLS</th>
|
||||
@if (isAdmin) {
|
||||
<th style="width: 5%;" class="permission-header">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-share-alt"></i>
|
||||
<span>Shared</span>
|
||||
</div>
|
||||
</th>
|
||||
}
|
||||
<th style="width: 7%;" class="actions-header">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-pencil"></i>
|
||||
<span>Edit</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 8%;" class="actions-header">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-trash"></i>
|
||||
<span>Delete</span>
|
||||
</div>
|
||||
</th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="body" let-provider>
|
||||
<tr>
|
||||
<td class="cell-center">
|
||||
<p-radioButton
|
||||
name="defaultProvider"
|
||||
[value]="provider.id"
|
||||
[(ngModel)]="defaultProviderId"
|
||||
(onClick)="setDefaultProvider(provider)">
|
||||
</p-radioButton>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
@if (provider.isEditing) {
|
||||
<input type="text" [(ngModel)]="provider.name" class="p-inputtext input-full-width" size="small"/>
|
||||
}
|
||||
@if (!provider.isEditing) {
|
||||
<div class="provider-name-cell">
|
||||
<span>
|
||||
{{ provider.name }}
|
||||
@if (provider.shared) {
|
||||
<span class="shared-badge" pTooltip="Shared provider">S</span>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
@if (provider.isEditing) {
|
||||
<input type="text" [(ngModel)]="provider.host" class="p-inputtext input-full-width" size="small"/>
|
||||
}
|
||||
@if (!provider.isEditing) {
|
||||
<span>{{ provider.host }}</span>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
@if (provider.isEditing) {
|
||||
<input type="number" [(ngModel)]="provider.port" class="p-inputtext input-full-width" size="small"/>
|
||||
}
|
||||
@if (!provider.isEditing) {
|
||||
<span>{{ provider.port }}</span>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
@if (provider.isEditing) {
|
||||
<input type="text" [(ngModel)]="provider.username" class="p-inputtext input-full-width" size="small"/>
|
||||
}
|
||||
@if (!provider.isEditing) {
|
||||
<span>{{ provider.username }}</span>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
@if (provider.isEditing) {
|
||||
<input [(ngModel)]="provider.password" class="p-inputtext input-full-width" size="small"/>
|
||||
}
|
||||
@if (!provider.isEditing) {
|
||||
<span class="password-hidden">Hidden</span>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
@if (provider.isEditing) {
|
||||
<input type="text" [(ngModel)]="provider.fromAddress" class="p-inputtext input-full-width" size="small"/>
|
||||
}
|
||||
@if (!provider.isEditing) {
|
||||
<span>{{ provider.fromAddress }}</span>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td class="cell-center">
|
||||
<p-checkbox
|
||||
[(ngModel)]="provider.auth"
|
||||
[binary]="true"
|
||||
[disabled]="!provider.isEditing">
|
||||
</p-checkbox>
|
||||
</td>
|
||||
|
||||
<td class="cell-center">
|
||||
<p-checkbox
|
||||
[(ngModel)]="provider.startTls"
|
||||
[binary]="true"
|
||||
[disabled]="!provider.isEditing">
|
||||
</p-checkbox>
|
||||
</td>
|
||||
|
||||
@if (isAdmin) {
|
||||
<td class="cell-center">
|
||||
<p-checkbox
|
||||
[(ngModel)]="provider.shared"
|
||||
[binary]="true"
|
||||
(onChange)="toggleShared(provider)"
|
||||
pTooltip="Share this provider with all users">
|
||||
</p-checkbox>
|
||||
</td>
|
||||
}
|
||||
|
||||
<td class="actions-cell">
|
||||
</div>
|
||||
<div class="provider-actions">
|
||||
@if (!provider.isEditing) {
|
||||
<p-button
|
||||
[icon]="canModifyProvider(provider) ? 'pi pi-pencil' : 'pi pi-lock'"
|
||||
@@ -203,63 +66,144 @@
|
||||
[rounded]="true"
|
||||
[disabled]="!canModifyProvider(provider)"
|
||||
(onClick)="canModifyProvider(provider) && toggleEdit(provider)"
|
||||
[pTooltip]="canModifyProvider(provider) ? 'Edit provider' : 'Cannot edit shared provider from another user'"
|
||||
[pTooltip]="canModifyProvider(provider) ? 'Edit provider' : 'Cannot edit shared provider'"
|
||||
tooltipPosition="left">
|
||||
</p-button>
|
||||
<p-button
|
||||
[icon]="canModifyProvider(provider) ? 'pi pi-trash' : 'pi pi-lock'"
|
||||
[severity]="canModifyProvider(provider) ? 'danger' : 'secondary'"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
[disabled]="!canModifyProvider(provider)"
|
||||
(onClick)="canModifyProvider(provider) && deleteProvider(provider)"
|
||||
[pTooltip]="canModifyProvider(provider) ? 'Delete provider' : 'Cannot delete shared provider'"
|
||||
tooltipPosition="left">
|
||||
</p-button>
|
||||
} @else {
|
||||
<p-button
|
||||
icon="pi pi-check"
|
||||
severity="success"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="saveProvider(provider)"
|
||||
pTooltip="Save changes">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
severity="secondary"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="toggleEdit(provider)"
|
||||
pTooltip="Cancel">
|
||||
</p-button>
|
||||
}
|
||||
@if (provider.isEditing) {
|
||||
<div class="edit-actions">
|
||||
<p-button
|
||||
icon="pi pi-check"
|
||||
severity="success"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="saveProvider(provider)"
|
||||
pTooltip="Save changes">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="toggleEdit(provider)"
|
||||
pTooltip="Cancel">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="provider-details">
|
||||
<div class="detail-grid">
|
||||
<div class="detail-item">
|
||||
<label class="detail-label">
|
||||
<i class="pi pi-server"></i>
|
||||
Host
|
||||
</label>
|
||||
@if (provider.isEditing) {
|
||||
<input type="text" pInputText [(ngModel)]="provider.host" placeholder="smtp.example.com"/>
|
||||
} @else {
|
||||
<span class="detail-value">{{ provider.host }}</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="detail-item">
|
||||
<label class="detail-label">
|
||||
<i class="pi pi-link"></i>
|
||||
Port
|
||||
</label>
|
||||
@if (provider.isEditing) {
|
||||
<input type="number" pInputText [(ngModel)]="provider.port" placeholder="587"/>
|
||||
} @else {
|
||||
<span class="detail-value">{{ provider.port }}</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="detail-item">
|
||||
<label class="detail-label">
|
||||
<i class="pi pi-user"></i>
|
||||
Username
|
||||
</label>
|
||||
@if (provider.isEditing) {
|
||||
<input type="text" pInputText [(ngModel)]="provider.username" placeholder="user@example.com"/>
|
||||
} @else {
|
||||
<span class="detail-value">{{ provider.username }}</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="detail-item">
|
||||
<label class="detail-label">
|
||||
<i class="pi pi-lock"></i>
|
||||
Password
|
||||
</label>
|
||||
@if (provider.isEditing) {
|
||||
<input type="password" pInputText [(ngModel)]="provider.password" placeholder="Enter password"/>
|
||||
} @else {
|
||||
<span class="detail-value password-hidden">********</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="detail-item detail-item-wide">
|
||||
<label class="detail-label">
|
||||
<i class="pi pi-envelope"></i>
|
||||
From Address
|
||||
</label>
|
||||
@if (provider.isEditing) {
|
||||
<input type="email" pInputText [(ngModel)]="provider.fromAddress" placeholder="noreply@example.com"/>
|
||||
} @else {
|
||||
<span class="detail-value">{{ provider.fromAddress }}</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toggle-options">
|
||||
<div class="toggle-item">
|
||||
<p-checkbox
|
||||
[(ngModel)]="provider.auth"
|
||||
[binary]="true"
|
||||
[disabled]="!provider.isEditing"
|
||||
inputId="auth-{{provider.id}}">
|
||||
</p-checkbox>
|
||||
<label [for]="'auth-' + provider.id" class="toggle-label">Authentication</label>
|
||||
</div>
|
||||
|
||||
<div class="toggle-item">
|
||||
<p-checkbox
|
||||
[(ngModel)]="provider.startTls"
|
||||
[binary]="true"
|
||||
[disabled]="!provider.isEditing"
|
||||
inputId="starttls-{{provider.id}}">
|
||||
</p-checkbox>
|
||||
<label [for]="'starttls-' + provider.id" class="toggle-label">StartTLS</label>
|
||||
</div>
|
||||
|
||||
@if (isAdmin) {
|
||||
<div class="toggle-item">
|
||||
<p-checkbox
|
||||
[(ngModel)]="provider.shared"
|
||||
[binary]="true"
|
||||
(onChange)="toggleShared(provider)"
|
||||
inputId="shared-{{provider.id}}"
|
||||
pTooltip="Share this provider with all users">
|
||||
</p-checkbox>
|
||||
<label [for]="'shared-' + provider.id" class="toggle-label">Shared</label>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td class="actions-cell">
|
||||
<p-button
|
||||
[icon]="canModifyProvider(provider) ? 'pi pi-trash' : 'pi pi-lock'"
|
||||
[severity]="canModifyProvider(provider) ? 'danger' : 'secondary'"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
[disabled]="!canModifyProvider(provider)"
|
||||
(onClick)="canModifyProvider(provider) && deleteProvider(provider)"
|
||||
[pTooltip]="canModifyProvider(provider) ? 'Delete provider' : 'Cannot delete shared provider from another user'"
|
||||
tooltipPosition="left">
|
||||
</p-button>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="emptymessage">
|
||||
<tr>
|
||||
<td [attr.colspan]="isAdmin ? 12 : 11">
|
||||
<div class="empty-message">
|
||||
<i class="pi pi-envelope"></i>
|
||||
<p class="empty-title">No email providers found</p>
|
||||
<p class="empty-subtitle">Create your first email provider to start sending books</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+212
-179
@@ -1,223 +1,256 @@
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
@use '../../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.settings-header {
|
||||
margin-top: 2.5rem;
|
||||
padding: 0 1rem;
|
||||
|
||||
.section-title-group {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.settings-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.75rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.preferences-section {
|
||||
@media (min-width: 768px) {
|
||||
padding: 0 1rem;
|
||||
}
|
||||
.settings-card {
|
||||
@include settings.settings-card;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 1rem;
|
||||
@include settings.settings-section-header;
|
||||
}
|
||||
|
||||
.section-title-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1rem;
|
||||
.section-header-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.section-header-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
@include settings.settings-section-title;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.section-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
// Empty state
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
justify-content: center;
|
||||
padding: 3rem 2rem;
|
||||
text-align: center;
|
||||
color: var(--p-text-muted-color);
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border-radius: 6px;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.table-card {
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
|
||||
.p-datatable {
|
||||
.p-datatable-table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
}
|
||||
|
||||
.p-datatable-thead > tr > th {
|
||||
background: var(--p-surface-100);
|
||||
border-bottom: 2px solid var(--p-content-border-color);
|
||||
padding: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.p-datatable-tbody > tr {
|
||||
transition: background-color 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: var(--p-surface-50);
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.p-datatable-tbody > tr > td {
|
||||
padding: 1rem;
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
.p-datatable th .header-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.permission-header {
|
||||
text-align: center;
|
||||
font-size: 0.875rem;
|
||||
padding: 0.75rem 0.5rem !important;
|
||||
min-width: 80px;
|
||||
width: 80px;
|
||||
|
||||
.header-content {
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.actions-header {
|
||||
text-align: center;
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.actions-cell {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.password-hidden {
|
||||
color: var(--p-text-muted-color);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
text-align: center;
|
||||
padding: 2rem 1rem;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
.pi {
|
||||
font-size: 2rem;
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--p-surface-400);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.empty-title {
|
||||
font-size: 1.125rem;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
.empty-subtitle {
|
||||
font-size: 0.875rem;
|
||||
font-size: settings.$settings-section-description-size;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Provider list
|
||||
.providers-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.provider-item {
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-left: 3px solid var(--p-content-border-color);
|
||||
border-radius: 6px;
|
||||
padding: 1rem;
|
||||
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%);
|
||||
}
|
||||
|
||||
&.is-default {
|
||||
border-left-color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.provider-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
padding-bottom: 0.75rem;
|
||||
border-bottom: 1px dashed var(--p-content-border-color);
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.provider-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.provider-name-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.provider-name {
|
||||
font-weight: 600;
|
||||
font-size: 1rem;
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
.name-input {
|
||||
width: 200px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.shared-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.1rem;
|
||||
height: 1.1rem;
|
||||
background-color: var(--p-green-600);
|
||||
color: white;
|
||||
border-radius: 0.25rem;
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
background: color-mix(in srgb, var(--p-green-600) 20%, transparent);
|
||||
color: var(--p-green-400);
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
cursor: default;
|
||||
vertical-align: text-bottom;
|
||||
margin-left: 0.25rem;
|
||||
|
||||
.pi {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.cell-center {
|
||||
text-align: center;
|
||||
.default-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.125rem 0.5rem;
|
||||
background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
|
||||
color: var(--p-primary-color);
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.input-full-width {
|
||||
width: 100%;
|
||||
.provider-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
.provider-name-cell {
|
||||
// Provider details grid
|
||||
.provider-details {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.detail-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.detail-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.375rem;
|
||||
|
||||
&.detail-item-wide {
|
||||
grid-column: span 2;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
grid-column: span 1;
|
||||
}
|
||||
}
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.detail-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
font-size: settings.$settings-description-size;
|
||||
font-weight: 500;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
.pi {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.detail-value {
|
||||
font-size: settings.$settings-section-description-size;
|
||||
color: var(--p-text-color);
|
||||
word-break: break-word;
|
||||
|
||||
&.password-hidden {
|
||||
color: var(--p-text-muted-color);
|
||||
font-style: italic;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle options
|
||||
.toggle-options {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1.5rem;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px dashed var(--p-content-border-color);
|
||||
}
|
||||
|
||||
.toggle-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.edit-actions {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
.toggle-label {
|
||||
font-size: settings.$settings-description-size;
|
||||
color: var(--p-text-color);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
+1
-2
@@ -1,7 +1,7 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {MessageService, PrimeTemplate} from 'primeng/api';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {RadioButton} from 'primeng/radiobutton';
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {TableModule} from 'primeng/table';
|
||||
@@ -17,7 +17,6 @@ import {DialogLauncherService} from '../../../../shared/services/dialog-launcher
|
||||
imports: [
|
||||
Button,
|
||||
Checkbox,
|
||||
PrimeTemplate,
|
||||
RadioButton,
|
||||
ReactiveFormsModule,
|
||||
TableModule,
|
||||
|
||||
-271
@@ -1,271 +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 {EmailV2ProviderService} from './email-v2-provider.service';
|
||||
import {EmailProvider} from '../email-provider.model';
|
||||
|
||||
describe('EmailV2ProviderService', () => {
|
||||
let service: EmailV2ProviderService;
|
||||
let httpClientMock: any;
|
||||
|
||||
const mockProvider: EmailProvider = {
|
||||
isEditing: false,
|
||||
id: 1,
|
||||
userId: 2,
|
||||
name: 'Provider1',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
fromAddress: 'from@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: false,
|
||||
shared: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
patch: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
EmailV2ProviderService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(EmailV2ProviderService);
|
||||
});
|
||||
|
||||
it('should get email providers', () => {
|
||||
httpClientMock.get.mockReturnValue(of([mockProvider]));
|
||||
service.getEmailProviders().subscribe(providers => {
|
||||
expect(providers).toEqual([mockProvider]);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should create email provider', () => {
|
||||
httpClientMock.post.mockReturnValue(of(mockProvider));
|
||||
service.createEmailProvider(mockProvider).subscribe(provider => {
|
||||
expect(provider).toEqual(mockProvider);
|
||||
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers'), mockProvider);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update provider', () => {
|
||||
httpClientMock.put.mockReturnValue(of(mockProvider));
|
||||
service.updateProvider(mockProvider).subscribe(provider => {
|
||||
expect(provider).toEqual(mockProvider);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining(`/api/v2/email/providers/${mockProvider.id}`), mockProvider);
|
||||
});
|
||||
});
|
||||
|
||||
it('should delete provider', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
service.deleteProvider(1).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers/1'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should set default provider', () => {
|
||||
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||
service.setDefaultProvider(1).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers/1/set-default'), {});
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle getEmailProviders error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.getEmailProviders().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle createEmailProvider error', () => {
|
||||
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.createEmailProvider(mockProvider).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle updateProvider error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.updateProvider(mockProvider).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle deleteProvider error', () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.deleteProvider(1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle setDefaultProvider error', () => {
|
||||
httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.setDefaultProvider(1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('EmailV2ProviderService - API Contract Tests', () => {
|
||||
let service: EmailV2ProviderService;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
patch: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
EmailV2ProviderService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(EmailV2ProviderService);
|
||||
});
|
||||
|
||||
it('should validate all required EmailProvider fields exist', () => {
|
||||
const requiredFields: (keyof EmailProvider)[] = [
|
||||
'isEditing', 'id', 'userId', 'name', 'host', 'port', 'username', 'password',
|
||||
'fromAddress', 'auth', 'startTls', 'defaultProvider', 'shared'
|
||||
];
|
||||
const mockResponse: EmailProvider = {
|
||||
isEditing: false,
|
||||
id: 1,
|
||||
userId: 2,
|
||||
name: 'Provider1',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
fromAddress: 'from@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: false,
|
||||
shared: false
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of([mockResponse]));
|
||||
service.getEmailProviders().subscribe(providers => {
|
||||
requiredFields.forEach(field => {
|
||||
expect(providers[0]).toHaveProperty(field);
|
||||
expect(providers[0][field]).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns EmailProvider without required id field', () => {
|
||||
const invalidResponse = [{
|
||||
isEditing: false,
|
||||
userId: 2,
|
||||
name: 'Provider1',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
fromAddress: 'from@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: false,
|
||||
shared: false
|
||||
}];
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
service.getEmailProviders().subscribe(providers => {
|
||||
expect(providers[0]).not.toHaveProperty('id');
|
||||
});
|
||||
});
|
||||
|
||||
it('should call correct endpoint for getEmailProviders', () => {
|
||||
httpClientMock.get.mockReturnValue(of([]));
|
||||
service.getEmailProviders().subscribe();
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for createEmailProvider', () => {
|
||||
httpClientMock.post.mockReturnValue(of({}));
|
||||
const provider = {
|
||||
isEditing: false,
|
||||
id: 1,
|
||||
userId: 2,
|
||||
name: 'Provider1',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
fromAddress: 'from@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: false,
|
||||
shared: false
|
||||
};
|
||||
service.createEmailProvider(provider).subscribe();
|
||||
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers$/), provider);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for updateProvider', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
const provider = {
|
||||
isEditing: false,
|
||||
id: 1,
|
||||
userId: 2,
|
||||
name: 'Provider1',
|
||||
host: 'smtp.example.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pass',
|
||||
fromAddress: 'from@example.com',
|
||||
auth: true,
|
||||
startTls: true,
|
||||
defaultProvider: false,
|
||||
shared: false
|
||||
};
|
||||
service.updateProvider(provider).subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1$/), provider);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for deleteProvider', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
service.deleteProvider(1).subscribe();
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for setDefaultProvider', () => {
|
||||
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||
service.setDefaultProvider(1).subscribe();
|
||||
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1\/set-default$/), {});
|
||||
});
|
||||
});
|
||||
|
||||
+91
-119
@@ -1,18 +1,18 @@
|
||||
<div class="main-container enclosing-container">
|
||||
<div class="settings-header">
|
||||
<div class="section-title-group">
|
||||
<div>
|
||||
<h2 class="settings-title">
|
||||
<div class="settings-card">
|
||||
<div class="section-header">
|
||||
<div class="section-header-row">
|
||||
<div class="section-header-text">
|
||||
<h3 class="section-title">
|
||||
<i class="pi pi-users"></i>
|
||||
Recipient Emails
|
||||
</h2>
|
||||
<p class="settings-description">
|
||||
Manage the list of recipients who will receive books via email. The 'Default' recipient will be used for 'Quick Book Send,' located in the Book Card menu.
|
||||
</h3>
|
||||
<p class="section-description">
|
||||
Manage recipient email addresses for sending books. The default recipient is used for 'Quick Book Send' in the Book Card menu.
|
||||
</p>
|
||||
</div>
|
||||
<p-button
|
||||
icon="pi pi-plus"
|
||||
label="Create Recipient"
|
||||
label="Add Recipient"
|
||||
severity="success"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
@@ -21,75 +21,65 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-content">
|
||||
<div class="preferences-section">
|
||||
<div class="table-card">
|
||||
<p-table [value]="recipientEmails" [scrollable]="true" scrollHeight="flex">
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th style="width: 10%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-star"></i>
|
||||
<span>Default</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 45%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-envelope"></i>
|
||||
<span>Email Address</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 30%;">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-user"></i>
|
||||
<span>Name</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 8%;" class="actions-header">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-pencil"></i>
|
||||
<span>Edit</span>
|
||||
</div>
|
||||
</th>
|
||||
<th style="width: 7%;" class="actions-header">
|
||||
<div class="header-content">
|
||||
<i class="pi pi-trash"></i>
|
||||
<span>Delete</span>
|
||||
</div>
|
||||
</th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="body" let-recipient>
|
||||
<tr>
|
||||
<td class="text-center">
|
||||
<div class="section-body">
|
||||
@if (recipientEmails.length === 0) {
|
||||
<div class="empty-state">
|
||||
<i class="pi pi-users"></i>
|
||||
<p class="empty-title">No recipients configured</p>
|
||||
<p class="empty-subtitle">Add your first email recipient to start sending books</p>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="recipients-list">
|
||||
@for (recipient of recipientEmails; track recipient.id) {
|
||||
<div class="recipient-item" [class.is-default]="recipient.id === defaultRecipientId">
|
||||
<div class="recipient-content">
|
||||
<div class="recipient-select">
|
||||
<p-radioButton
|
||||
name="defaultRecipient"
|
||||
[value]="recipient.id"
|
||||
[(ngModel)]="defaultRecipientId"
|
||||
(onClick)="setDefaultRecipient(recipient)">
|
||||
</p-radioButton>
|
||||
</td>
|
||||
</div>
|
||||
|
||||
<td>
|
||||
<div class="recipient-info">
|
||||
@if (recipient.isEditing) {
|
||||
<input type="email" [(ngModel)]="recipient.email" class="p-inputtext full-width" size="small"/>
|
||||
<div class="edit-form">
|
||||
<div class="form-field">
|
||||
<label class="field-label">
|
||||
<i class="pi pi-envelope"></i>
|
||||
Email
|
||||
</label>
|
||||
<input type="email" pInputText [(ngModel)]="recipient.email" placeholder="recipient@example.com"/>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label class="field-label">
|
||||
<i class="pi pi-user"></i>
|
||||
Name
|
||||
</label>
|
||||
<input type="text" pInputText [(ngModel)]="recipient.name" placeholder="Recipient name"/>
|
||||
</div>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="recipient-details">
|
||||
<div class="recipient-email">
|
||||
<i class="pi pi-envelope"></i>
|
||||
<span>{{ recipient.email }}</span>
|
||||
@if (recipient.id === defaultRecipientId) {
|
||||
<span class="default-badge">Default</span>
|
||||
}
|
||||
</div>
|
||||
@if (recipient.name) {
|
||||
<div class="recipient-name">
|
||||
<i class="pi pi-user"></i>
|
||||
<span>{{ recipient.name }}</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (!recipient.isEditing) {
|
||||
<span>{{ recipient.email }}</span>
|
||||
}
|
||||
</td>
|
||||
</div>
|
||||
|
||||
<td>
|
||||
@if (recipient.isEditing) {
|
||||
<input type="text" [(ngModel)]="recipient.name" class="p-inputtext full-width" size="small"/>
|
||||
}
|
||||
@if (!recipient.isEditing) {
|
||||
<span>{{ recipient.name }}</span>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td class="actions-cell">
|
||||
<div class="recipient-actions">
|
||||
@if (!recipient.isEditing) {
|
||||
<p-button
|
||||
icon="pi pi-pencil"
|
||||
@@ -100,58 +90,40 @@
|
||||
(onClick)="toggleEditRecipient(recipient)"
|
||||
pTooltip="Edit recipient">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="deleteRecipient(recipient)"
|
||||
pTooltip="Delete recipient">
|
||||
</p-button>
|
||||
} @else {
|
||||
<p-button
|
||||
icon="pi pi-check"
|
||||
severity="success"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="saveRecipient(recipient)"
|
||||
pTooltip="Save changes">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
severity="secondary"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="toggleEditRecipient(recipient)"
|
||||
pTooltip="Cancel">
|
||||
</p-button>
|
||||
}
|
||||
@if (recipient.isEditing) {
|
||||
<div class="edit-actions">
|
||||
<p-button
|
||||
icon="pi pi-check"
|
||||
severity="success"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="saveRecipient(recipient)"
|
||||
pTooltip="Save changes">
|
||||
</p-button>
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="toggleEditRecipient(recipient)"
|
||||
pTooltip="Cancel">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
</td>
|
||||
|
||||
<td class="actions-cell">
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
size="small"
|
||||
[outlined]="true"
|
||||
[rounded]="true"
|
||||
(onClick)="deleteRecipient(recipient)"
|
||||
pTooltip="Delete recipient">
|
||||
</p-button>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
|
||||
<ng-template pTemplate="emptymessage">
|
||||
<tr>
|
||||
<td colspan="5">
|
||||
<div class="empty-message">
|
||||
<i class="pi pi-users"></i>
|
||||
<p class="empty-title">No recipients found</p>
|
||||
<p class="empty-subtitle">Add your first email recipient to start sending books</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+176
-147
@@ -1,184 +1,213 @@
|
||||
.enclosing-container {
|
||||
border-color: var(--p-content-border-color);
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
@use '../../../../shared/styles/settings-shared' as settings;
|
||||
|
||||
.settings-header {
|
||||
margin-top: 2rem;
|
||||
padding: 0 1rem;
|
||||
|
||||
.section-title-group {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.settings-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
margin: 0 0 0.75rem 0;
|
||||
|
||||
.pi {
|
||||
color: var(--p-primary-color);
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.settings-description {
|
||||
color: var(--p-text-muted-color);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.preferences-section {
|
||||
@media (min-width: 768px) {
|
||||
padding: 0 1rem;
|
||||
}
|
||||
.settings-card {
|
||||
@include settings.settings-card;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
margin-bottom: 1rem;
|
||||
@include settings.settings-section-header;
|
||||
}
|
||||
|
||||
.section-title-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 1rem;
|
||||
.section-header-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
p-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.section-header-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
@include settings.settings-section-title;
|
||||
}
|
||||
|
||||
.section-description {
|
||||
@include settings.settings-section-description;
|
||||
}
|
||||
|
||||
.section-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
// Empty state
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem 2rem;
|
||||
text-align: center;
|
||||
color: var(--p-text-muted-color);
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border-radius: 6px;
|
||||
|
||||
.pi {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.empty-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: var(--p-text-color);
|
||||
}
|
||||
|
||||
.empty-subtitle {
|
||||
font-size: settings.$settings-section-description-size;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Recipients list
|
||||
.recipients-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.recipient-item {
|
||||
background: color-mix(in srgb, var(--ground-background) 50%, var(--p-surface-800) 50%);
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-left: 3px solid var(--p-content-border-color);
|
||||
border-radius: 6px;
|
||||
padding: 0.875rem 1rem;
|
||||
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%);
|
||||
}
|
||||
|
||||
&.is-default {
|
||||
border-left-color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.recipient-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
}
|
||||
|
||||
.recipient-select {
|
||||
flex-shrink: 0;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.recipient-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.recipient-details {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.recipient-email {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
color: var(--p-text-color);
|
||||
|
||||
.pi {
|
||||
font-size: 0.875rem;
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.table-card {
|
||||
border: 1px solid var(--p-content-border-color);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--p-content-background);
|
||||
}
|
||||
|
||||
.p-datatable {
|
||||
.p-datatable-table {
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
}
|
||||
|
||||
.p-datatable-thead > tr > th {
|
||||
background: var(--p-surface-100);
|
||||
border-bottom: 2px solid var(--p-content-border-color);
|
||||
padding: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--p-text-color);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.p-datatable-tbody > tr {
|
||||
transition: background-color 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: var(--p-surface-50);
|
||||
}
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.p-datatable-tbody > tr > td {
|
||||
padding: 1rem;
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
.p-datatable th .header-content {
|
||||
.recipient-name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.actions-header {
|
||||
text-align: center;
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.actions-cell {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
text-align: center;
|
||||
padding: 2rem 1rem;
|
||||
font-size: settings.$settings-description-size;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
.pi {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 1rem;
|
||||
color: var(--p-surface-400);
|
||||
}
|
||||
|
||||
.empty-title {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.empty-subtitle {
|
||||
font-size: 0.875rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-text-muted-color);
|
||||
}
|
||||
}
|
||||
|
||||
.full-width {
|
||||
width: 100%;
|
||||
.default-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 0.125rem 0.5rem;
|
||||
background: color-mix(in srgb, var(--p-primary-color) 15%, transparent);
|
||||
color: var(--p-primary-color);
|
||||
border-radius: 4px;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.edit-actions {
|
||||
// Edit form
|
||||
.edit-form {
|
||||
display: flex;
|
||||
gap: 0.25rem;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.text-center {
|
||||
text-align: center;
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.field-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
font-size: settings.$settings-description-size;
|
||||
font-weight: 500;
|
||||
color: var(--p-text-muted-color);
|
||||
|
||||
.pi {
|
||||
font-size: 0.75rem;
|
||||
color: var(--p-primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.recipient-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
|
||||
@media (max-width: 767px) {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -1,6 +1,6 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {MessageService, PrimeTemplate} from 'primeng/api';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {RadioButton} from 'primeng/radiobutton';
|
||||
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {TableModule} from 'primeng/table';
|
||||
@@ -14,7 +14,6 @@ import {DialogLauncherService} from '../../../../shared/services/dialog-launcher
|
||||
selector: 'app-email-v2-recipient',
|
||||
imports: [
|
||||
Button,
|
||||
PrimeTemplate,
|
||||
RadioButton,
|
||||
ReactiveFormsModule,
|
||||
TableModule,
|
||||
|
||||
-230
@@ -1,230 +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 {EmailV2RecipientService} from './email-v2-recipient.service';
|
||||
import {EmailRecipient} from '../email-recipient.model';
|
||||
|
||||
describe('EmailV2RecipientService', () => {
|
||||
let service: EmailV2RecipientService;
|
||||
let httpClientMock: any;
|
||||
|
||||
const mockRecipient: EmailRecipient = {
|
||||
id: 1,
|
||||
email: 'to@example.com',
|
||||
name: 'Recipient1',
|
||||
defaultRecipient: false,
|
||||
isEditing: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
patch: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
EmailV2RecipientService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(EmailV2RecipientService);
|
||||
});
|
||||
|
||||
it('should get recipients', () => {
|
||||
httpClientMock.get.mockReturnValue(of([mockRecipient]));
|
||||
service.getRecipients().subscribe(recipients => {
|
||||
expect(recipients).toEqual([mockRecipient]);
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should create recipient', () => {
|
||||
httpClientMock.post.mockReturnValue(of(mockRecipient));
|
||||
service.createRecipient(mockRecipient).subscribe(recipient => {
|
||||
expect(recipient).toEqual(mockRecipient);
|
||||
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients'), mockRecipient);
|
||||
});
|
||||
});
|
||||
|
||||
it('should update recipient', () => {
|
||||
httpClientMock.put.mockReturnValue(of(mockRecipient));
|
||||
service.updateRecipient(mockRecipient).subscribe(recipient => {
|
||||
expect(recipient).toEqual(mockRecipient);
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining(`/api/v2/email/recipients/${mockRecipient.id}`), mockRecipient);
|
||||
});
|
||||
});
|
||||
|
||||
it('should delete recipient', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
service.deleteRecipient(1).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients/1'));
|
||||
});
|
||||
});
|
||||
|
||||
it('should set default recipient', () => {
|
||||
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||
service.setDefaultRecipient(1).subscribe(result => {
|
||||
expect(result).toBeUndefined();
|
||||
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients/1/set-default'), {});
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle getRecipients error', () => {
|
||||
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.getRecipients().subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle createRecipient error', () => {
|
||||
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.createRecipient(mockRecipient).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle updateRecipient error', () => {
|
||||
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.updateRecipient(mockRecipient).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle deleteRecipient error', () => {
|
||||
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.deleteRecipient(1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle setDefaultRecipient error', () => {
|
||||
httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail')));
|
||||
service.setDefaultRecipient(1).subscribe({
|
||||
error: (err: any) => {
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.message).toBe('fail');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('EmailV2RecipientService - API Contract Tests', () => {
|
||||
let service: EmailV2RecipientService;
|
||||
let httpClientMock: any;
|
||||
|
||||
beforeEach(() => {
|
||||
httpClientMock = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
patch: vi.fn()
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
EmailV2RecipientService,
|
||||
{provide: HttpClient, useValue: httpClientMock}
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(EmailV2RecipientService);
|
||||
});
|
||||
|
||||
it('should validate all required EmailRecipient fields exist', () => {
|
||||
const requiredFields: (keyof EmailRecipient)[] = [
|
||||
'id', 'email', 'name', 'defaultRecipient', 'isEditing'
|
||||
];
|
||||
const mockResponse: EmailRecipient = {
|
||||
id: 1,
|
||||
email: 'to@example.com',
|
||||
name: 'Recipient1',
|
||||
defaultRecipient: false,
|
||||
isEditing: false
|
||||
};
|
||||
httpClientMock.get.mockReturnValue(of([mockResponse]));
|
||||
service.getRecipients().subscribe(recipients => {
|
||||
requiredFields.forEach(field => {
|
||||
expect(recipients[0]).toHaveProperty(field);
|
||||
expect(recipients[0][field]).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should fail if API returns EmailRecipient without required id field', () => {
|
||||
const invalidResponse = [{
|
||||
email: 'to@example.com',
|
||||
name: 'Recipient1',
|
||||
defaultRecipient: false,
|
||||
isEditing: false
|
||||
}];
|
||||
httpClientMock.get.mockReturnValue(of(invalidResponse));
|
||||
service.getRecipients().subscribe(recipients => {
|
||||
expect(recipients[0]).not.toHaveProperty('id');
|
||||
});
|
||||
});
|
||||
|
||||
it('should call correct endpoint for getRecipients', () => {
|
||||
httpClientMock.get.mockReturnValue(of([]));
|
||||
service.getRecipients().subscribe();
|
||||
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for createRecipient', () => {
|
||||
httpClientMock.post.mockReturnValue(of({}));
|
||||
const recipient = {
|
||||
id: 1,
|
||||
email: 'to@example.com',
|
||||
name: 'Recipient1',
|
||||
defaultRecipient: false,
|
||||
isEditing: false
|
||||
};
|
||||
service.createRecipient(recipient).subscribe();
|
||||
expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients$/), recipient);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for updateRecipient', () => {
|
||||
httpClientMock.put.mockReturnValue(of({}));
|
||||
const recipient = {
|
||||
id: 1,
|
||||
email: 'to@example.com',
|
||||
name: 'Recipient1',
|
||||
defaultRecipient: false,
|
||||
isEditing: false
|
||||
};
|
||||
service.updateRecipient(recipient).subscribe();
|
||||
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1$/), recipient);
|
||||
});
|
||||
|
||||
it('should call correct endpoint for deleteRecipient', () => {
|
||||
httpClientMock.delete.mockReturnValue(of(void 0));
|
||||
service.deleteRecipient(1).subscribe();
|
||||
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1$/));
|
||||
});
|
||||
|
||||
it('should call correct endpoint for setDefaultRecipient', () => {
|
||||
httpClientMock.patch.mockReturnValue(of(void 0));
|
||||
service.setDefaultRecipient(1).subscribe();
|
||||
expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1\/set-default$/), {});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<div class="email-settings-container enclosing-container">
|
||||
<div class="email-settings-container">
|
||||
<div class="settings-header">
|
||||
<h2 class="settings-title">
|
||||
<i class="pi pi-envelope"></i>
|
||||
@@ -11,13 +11,9 @@
|
||||
</div>
|
||||
|
||||
@if (hasPermission) {
|
||||
<div class="provider-section">
|
||||
<app-email-v2-provider></app-email-v2-provider>
|
||||
</div>
|
||||
<p-divider></p-divider>
|
||||
<div class="recipient-section">
|
||||
<app-email-v2-recipient></app-email-v2-recipient>
|
||||
</div>
|
||||
<app-email-v2-provider></app-email-v2-provider>
|
||||
<div class="section-divider"><hr></div>
|
||||
<app-email-v2-recipient></app-email-v2-recipient>
|
||||
} @else {
|
||||
<div class="access-denied-card">
|
||||
<i class="pi pi-lock"></i>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user