chore: mechanical lint fixes (#2933)

This commit is contained in:
Alex
2026-10-16 19:26:34 +01:00
committed by GitHub
parent ad119b483a
commit bb0e6cc1a7
447 changed files with 2935 additions and 6862 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -48,13 +48,13 @@
</svg> </svg>
<h1>{{ t('offline') }}</h1> <h1>{{ t('offline') }}</h1>
<p>{{ t('connectionLost') }}</p> <p>{{ t('connectionLost') }}</p>
<button class="retry-btn" (click)="reload()">{{ 'common.retry' | transloco }}</button> <button type="button" class="retry-btn" (click)="reload()">{{ 'common.retry' | transloco }}</button>
</div> </div>
</div> </div>
} @else { } @else {
<p-confirmDialog /> <p-confirmDialog />
<p-toast></p-toast> <p-toast />
<app-command-palette /> <app-command-palette />
<router-outlet></router-outlet> <router-outlet />
} }
</ng-container> </ng-container>
+22 -23
View File
@@ -31,28 +31,27 @@ import {RxStompState} from '@stomp/rx-stomp';
imports: [ConfirmDialog, Toast, RouterOutlet, TranslocoDirective, TranslocoPipe, CommandPaletteComponent] imports: [ConfirmDialog, Toast, RouterOutlet, TranslocoDirective, TranslocoPipe, CommandPaletteComponent]
}) })
export class AppComponent implements OnInit, OnDestroy { export class AppComponent implements OnInit, OnDestroy {
private readonly appThemeService = inject(AppThemeService); // DO NOT REMOVE: Used to initialize app theme on startup
loading = signal(true); private readonly authInit = inject(AuthInitializationService);
offline = signal(false); private readonly bookService = inject(BookService);
private subscriptions: Subscription[] = []; private readonly authorService = inject(AuthorService);
private subscriptionsInitialized = false; private readonly rxStompService = inject(RxStompService);
private readonly notificationEventService = inject(NotificationEventService);
private appThemeService = inject(AppThemeService); // DO NOT REMOVE: Used to initialize app theme on startup private readonly metadataProgressService = inject(MetadataProgressService);
private authInit = inject(AuthInitializationService); private readonly bookdropFileService = inject(BookdropFileService);
private bookService = inject(BookService); private readonly taskService = inject(TaskService);
private authorService = inject(AuthorService); private readonly metadataRefreshSubmissionService = inject(MetadataRefreshSubmissionService);
private rxStompService = inject(RxStompService); private readonly libraryHealthService = inject(LibraryHealthService);
private notificationEventService = inject(NotificationEventService); private readonly authService = inject(AuthService);
private metadataProgressService = inject(MetadataProgressService); private readonly commandPaletteService = inject(CommandPaletteService);
private bookdropFileService = inject(BookdropFileService);
private taskService = inject(TaskService);
private metadataRefreshSubmissionService = inject(MetadataRefreshSubmissionService);
private libraryHealthService = inject(LibraryHealthService);
private authService = inject(AuthService);
private commandPaletteService = inject(CommandPaletteService);
private readonly libraryImportProgressService = inject(LibraryImportProgressService); private readonly libraryImportProgressService = inject(LibraryImportProgressService);
private readonly translocoService = inject(TranslocoService); private readonly translocoService = inject(TranslocoService);
private destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
readonly loading = signal(true);
readonly offline = signal(false);
private readonly subscriptions: Subscription[] = [];
private subscriptionsInitialized = false;
private readonly syncAuthInitializationEffect = effect(() => { private readonly syncAuthInitializationEffect = effect(() => {
const ready = this.authInit.initialized(); const ready = this.authInit.initialized();
this.loading.set(!ready); this.loading.set(!ready);
@@ -79,7 +78,7 @@ export class AppComponent implements OnInit, OnDestroy {
this.destroyRef.onDestroy(() => document.removeEventListener('keydown', this.onGlobalKeydown)); this.destroyRef.onDestroy(() => document.removeEventListener('keydown', this.onGlobalKeydown));
} }
private onGlobalKeydown = (event: KeyboardEvent): void => { private readonly onGlobalKeydown = (event: KeyboardEvent): void => {
if (event.repeat) return; if (event.repeat) return;
const combo = (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey; const combo = (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey;
if (!combo) return; if (!combo) return;
@@ -88,11 +87,11 @@ export class AppComponent implements OnInit, OnDestroy {
this.commandPaletteService.toggle(); this.commandPaletteService.toggle();
}; };
private onOnline = () => { private readonly onOnline = () => {
this.offline.set(false); this.offline.set(false);
}; };
private onOffline = () => { private readonly onOffline = () => {
this.checkServerReachable().then(reachable => { this.checkServerReachable().then(reachable => {
this.offline.set(!reachable); this.offline.set(!reachable);
}); });
@@ -11,7 +11,7 @@ describe('TranslocoInlineLoader', () => {
const translation = await firstValueFrom(loader.getTranslation('en')); const translation = await firstValueFrom(loader.getTranslation('en'));
expect(translation).toBe(EN_TRANSLATIONS); expect(translation).toBe(EN_TRANSLATIONS);
expect(translation['auth']['login']['sessionRevoked']).toBe(en['auth']['login']['sessionRevoked']); expect(translation['auth']['login']['sessionRevoked']).toBe(en.auth.login.sessionRevoked);
}); });
it('falls back to english for unsupported languages', async () => { it('falls back to english for unsupported languages', async () => {
@@ -25,9 +25,9 @@ describe('TranslocoInlineLoader', () => {
const loader = new TranslocoInlineLoader(); const loader = new TranslocoInlineLoader();
const translation = await firstValueFrom(loader.getTranslation('de')); const translation = await firstValueFrom(loader.getTranslation('de'));
expect(translation['auth']['login']['oidcInitError']).toBe(de['auth']['login']['oidcInitError']); expect(translation['auth']['login']['oidcInitError']).toBe(de.auth.login.oidcInitError);
expect(translation['auth']['login']['sessionRevoked']).toBe(de['auth']['login']['sessionRevoked']); expect(translation['auth']['login']['sessionRevoked']).toBe(de.auth.login.sessionRevoked);
expect(translation['auth']['login']['oidcErrors']['providerUnreachable']).toBe(de['auth']['login']['oidcErrors']['providerUnreachable']); expect(translation['auth']['login']['oidcErrors']['providerUnreachable']).toBe(de.auth.login.oidcErrors.providerUnreachable);
}); });
it('exposes the available language metadata', () => { it('exposes the available language metadata', () => {
@@ -1,4 +1,4 @@
import {Injectable} from '@angular/core'; import {Service} from '@angular/core';
import {Translation, TranslocoLoader} from '@jsverse/transloco'; import {Translation, TranslocoLoader} from '@jsverse/transloco';
import {from, of, Observable} from 'rxjs'; import {from, of, Observable} from 'rxjs';
import en from '../../../i18n/en.json'; import en from '../../../i18n/en.json';
@@ -68,7 +68,7 @@ function deepMerge(base: Record<string, Translation>, override: Record<string, T
return result; return result;
} }
@Injectable({providedIn: 'root'}) @Service()
export class TranslocoInlineLoader implements TranslocoLoader { export class TranslocoInlineLoader implements TranslocoLoader {
getTranslation(lang: string): Observable<Translation> { getTranslation(lang: string): Observable<Translation> {
if (lang === 'en') { if (lang === 'en') {
@@ -1,4 +1,4 @@
import {Injectable} from '@angular/core'; import {Service} from '@angular/core';
import {ActivatedRouteSnapshot, BaseRouteReuseStrategy, Params} from '@angular/router'; import {ActivatedRouteSnapshot, BaseRouteReuseStrategy, Params} from '@angular/router';
function paramsMatch(a: Params, b: Params): boolean { function paramsMatch(a: Params, b: Params): boolean {
@@ -7,9 +7,7 @@ function paramsMatch(a: Params, b: Params): boolean {
return aKeys.length === bKeys.length && aKeys.every(key => a[key] === b[key]); return aKeys.length === bKeys.length && aKeys.every(key => a[key] === b[key]);
} }
@Injectable({ @Service()
providedIn: 'root',
})
export class CustomReuseStrategy extends BaseRouteReuseStrategy { export class CustomReuseStrategy extends BaseRouteReuseStrategy {
override shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { override shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig && paramsMatch(future.params, curr.params); return future.routeConfig === curr.routeConfig && paramsMatch(future.params, curr.params);
@@ -1,6 +1,6 @@
import {Injectable, signal} from '@angular/core'; import {Service, signal} from '@angular/core';
@Injectable({providedIn: 'root'}) @Service()
export class AuthInitializationService { export class AuthInitializationService {
private readonly _initialized = signal(false); private readonly _initialized = signal(false);
readonly initialized = this._initialized.asReadonly(); readonly initialized = this._initialized.asReadonly();
@@ -20,7 +20,7 @@ describe('initializeAuthFactory', () => {
}; };
const queryClient = { const queryClient = {
fetchQuery: vi.fn(), query: vi.fn(),
}; };
const appSettingsService = { const appSettingsService = {
@@ -40,13 +40,13 @@ describe('initializeAuthFactory', () => {
authService.getInternalAccessToken.mockReset(); authService.getInternalAccessToken.mockReset();
authService.remoteLogin.mockReset(); authService.remoteLogin.mockReset();
authService.initializeWebSocketConnection.mockReset(); authService.initializeWebSocketConnection.mockReset();
queryClient.fetchQuery.mockReset(); queryClient.query.mockReset();
appSettingsService.getPublicSettingsQueryOptions.mockClear(); appSettingsService.getPublicSettingsQueryOptions.mockClear();
}); });
it('marks auth initialized when public settings are unavailable', async () => { it('marks auth initialized when public settings are unavailable', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
queryClient.fetchQuery.mockResolvedValue(null); queryClient.query.mockResolvedValue(null);
const injector = Injector.create({ const injector = Injector.create({
providers: [ providers: [
@@ -65,7 +65,7 @@ describe('initializeAuthFactory', () => {
}); });
it('initializes websocket auth when local auth is active and a token exists', async () => { it('initializes websocket auth when local auth is active and a token exists', async () => {
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: false}); queryClient.query.mockResolvedValue({...settingsBase, remoteAuthEnabled: false});
authService.getInternalAccessToken.mockReturnValue('access-token'); authService.getInternalAccessToken.mockReturnValue('access-token');
const injector = Injector.create({ const injector = Injector.create({
@@ -84,7 +84,7 @@ describe('initializeAuthFactory', () => {
}); });
it('skips websocket initialization when local auth is active and no token exists', async () => { it('skips websocket initialization when local auth is active and no token exists', async () => {
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: false}); queryClient.query.mockResolvedValue({...settingsBase, remoteAuthEnabled: false});
authService.getInternalAccessToken.mockReturnValue(null); authService.getInternalAccessToken.mockReturnValue(null);
const injector = Injector.create({ const injector = Injector.create({
@@ -103,7 +103,7 @@ describe('initializeAuthFactory', () => {
}); });
it('performs remote login when remote auth is enabled', async () => { it('performs remote login when remote auth is enabled', async () => {
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: true}); queryClient.query.mockResolvedValue({...settingsBase, remoteAuthEnabled: true});
authService.remoteLogin.mockReturnValue(of({ authService.remoteLogin.mockReturnValue(of({
accessToken: 'access', accessToken: 'access',
refreshToken: 'refresh', refreshToken: 'refresh',
@@ -127,7 +127,7 @@ describe('initializeAuthFactory', () => {
it('marks auth initialized even when remote login fails', async () => { it('marks auth initialized even when remote login fails', async () => {
const error = new Error('remote login failed'); const error = new Error('remote login failed');
queryClient.fetchQuery.mockResolvedValue({...settingsBase, remoteAuthEnabled: true}); queryClient.query.mockResolvedValue({...settingsBase, remoteAuthEnabled: true});
authService.remoteLogin.mockReturnValue(throwError(() => error)); authService.remoteLogin.mockReturnValue(throwError(() => error));
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
@@ -13,7 +13,7 @@ export function initializeAuthFactory() {
const authInitService = inject(AuthInitializationService); const authInitService = inject(AuthInitializationService);
const queryClient = inject(QueryClient); const queryClient = inject(QueryClient);
const settingsPromise = queryClient.fetchQuery(appSettingsService.getPublicSettingsQueryOptions()); const settingsPromise = queryClient.query(appSettingsService.getPublicSettingsQueryOptions());
const timeoutPromise = new Promise<null>(resolve => const timeoutPromise = new Promise<null>(resolve =>
setTimeout(() => resolve(null), SETTINGS_TIMEOUT_MS) setTimeout(() => resolve(null), SETTINGS_TIMEOUT_MS)
); );
@@ -41,8 +41,7 @@
<p-checkbox <p-checkbox
[(ngModel)]="internalAuthEnabled" [(ngModel)]="internalAuthEnabled"
[binary]="true" [binary]="true"
[disabled]="true"> [disabled]="true" />
</p-checkbox>
</div> </div>
<div class="auth-method-item border-l-(--p-content-border-color) [&.is-active]:border-l-emerald-500 dark:[&.is-active]:border-l-emerald-300" [class.is-active]="oidcEnabled"> <div class="auth-method-item border-l-(--p-content-border-color) [&.is-active]:border-l-emerald-500 dark:[&.is-active]:border-l-emerald-300" [class.is-active]="oidcEnabled">
@@ -62,7 +61,7 @@
</div> </div>
<p class="auth-method-description"> <p class="auth-method-description">
{{ t('oidc.description') }} {{ t('oidc.description') }}
<app-external-doc-link docType="authentication"></app-external-doc-link> <app-external-doc-link docType="authentication" />
@if (!isOidcFormComplete() && !oidcEnabled) { @if (!isOidcFormComplete() && !oidcEnabled) {
<span class="config-hint">{{ t('oidc.configHint') }}</span> <span class="config-hint">{{ t('oidc.configHint') }}</span>
} }
@@ -71,8 +70,7 @@
<p-toggleswitch <p-toggleswitch
[(ngModel)]="oidcEnabled" [(ngModel)]="oidcEnabled"
[disabled]="!isOidcFormComplete()" [disabled]="!isOidcFormComplete()"
(onChange)="toggleOidcEnabled()"> (onChange)="toggleOidcEnabled()" />
</p-toggleswitch>
</div> </div>
</div> </div>
</div> </div>
@@ -158,8 +156,7 @@
[showButtons]="true" [showButtons]="true"
[placeholder]="t('providerConfig.sessionDurationPlaceholder')" [placeholder]="t('providerConfig.sessionDurationPlaceholder')"
mode="decimal" mode="decimal"
[useGrouping]="false"> [useGrouping]="false" />
</p-inputNumber>
<span class="field-hint">{{ t('providerConfig.sessionDurationHint') }}</span> <span class="field-hint">{{ t('providerConfig.sessionDurationHint') }}</span>
</div> </div>
</div> </div>
@@ -225,8 +222,7 @@
[label]="redirectUri" [label]="redirectUri"
[removable]="true" [removable]="true"
[attr.aria-label]="t('mobileRedirectUris.removeLabel', {uri: redirectUri})" [attr.aria-label]="t('mobileRedirectUris.removeLabel', {uri: redirectUri})"
(onRemove)="removeMobileRedirectUri(index)"> (onRemove)="removeMobileRedirectUri(index)" />
</p-chip>
} }
<input <input
pInputText pInputText
@@ -279,8 +275,7 @@
severity="info" severity="info"
size="small" size="small"
(click)="testConnection()" (click)="testConnection()"
[disabled]="!oidcProvider.issuerUri || isTestingConnection()"> [disabled]="!oidcProvider.issuerUri || isTestingConnection()" />
</p-button>
<p-button <p-button
[outlined]="true" [outlined]="true"
[label]="'common.save' | transloco" [label]="'common.save' | transloco"
@@ -288,8 +283,7 @@
severity="success" severity="success"
size="small" size="small"
(click)="saveOidcProvider()" (click)="saveOidcProvider()"
[disabled]="!isOidcFormComplete()"> [disabled]="!isOidcFormComplete()" />
</p-button>
</div> </div>
</div> </div>
@if (testConnectionResult() && showTestDetails()) { @if (testConnectionResult() && showTestDetails()) {
@@ -309,6 +303,7 @@
@case ('SKIP') { @case ('SKIP') {
<i class="pi pi-minus-circle text-(--color-text-muted)"></i> <i class="pi pi-minus-circle text-(--color-text-muted)"></i>
} }
@default never;
} }
<span class="check-name">{{ check.name }}</span> <span class="check-name">{{ check.name }}</span>
<span class="check-message">{{ check.message }}</span> <span class="check-message">{{ check.message }}</span>
@@ -342,8 +337,7 @@
severity="secondary" severity="secondary"
size="small" size="small"
[style]="{'min-width': '2rem'}" [style]="{'min-width': '2rem'}"
(click)="copyToClipboard(item.value)"> (click)="copyToClipboard(item.value)" />
</p-button>
</div> </div>
</div> </div>
} }
@@ -384,8 +378,7 @@
</div> </div>
<p-toggleswitch <p-toggleswitch
[(ngModel)]="oidcForceOnlyMode" [(ngModel)]="oidcForceOnlyMode"
(onChange)="toggleOidcForceOnlyMode()"> (onChange)="toggleOidcForceOnlyMode()" />
</p-toggleswitch>
</div> </div>
</div> </div>
</div> </div>
@@ -421,8 +414,7 @@
<p-toggleswitch <p-toggleswitch
[(ngModel)]="autoUserProvisioningEnabled" [(ngModel)]="autoUserProvisioningEnabled"
inputId="autoProvision" inputId="autoProvision"
(onChange)="saveOidcAutoProvisionSettings()"> (onChange)="saveOidcAutoProvisionSettings()" />
</p-toggleswitch>
</div> </div>
<div class="provisioning-toggle"> <div class="provisioning-toggle">
@@ -446,8 +438,7 @@
<p-toggleswitch <p-toggleswitch
[(ngModel)]="allowLocalAccountLinking" [(ngModel)]="allowLocalAccountLinking"
inputId="linkLocal" inputId="linkLocal"
(onChange)="saveOidcAutoProvisionSettings()"> (onChange)="saveOidcAutoProvisionSettings()" />
</p-toggleswitch>
</div> </div>
@if (autoUserProvisioningEnabled) { @if (autoUserProvisioningEnabled) {
@@ -460,8 +451,7 @@
[binary]="true" [binary]="true"
[disabled]="true" [disabled]="true"
[ngModel]="true" [ngModel]="true"
inputId="permissionRead"> inputId="permissionRead" />
</p-checkbox>
<label for="permissionRead">{{ t('provisioning.readBooks') }}</label> <label for="permissionRead">{{ t('provisioning.readBooks') }}</label>
</div> </div>
<ng-container *transloco="let a; prefix: 'settingsUsers'"> <ng-container *transloco="let a; prefix: 'settingsUsers'">
@@ -470,8 +460,7 @@
<p-checkbox <p-checkbox
[(ngModel)]="perm.selected" [(ngModel)]="perm.selected"
[binary]="true" [binary]="true"
[inputId]="perm.value"> [inputId]="perm.value" />
</p-checkbox>
<label [for]="perm.value">{{ a(perm.translationKey) }}</label> <label [for]="perm.value">{{ a(perm.translationKey) }}</label>
</div> </div>
} }
@@ -490,16 +479,14 @@
[placeholder]="t('provisioning.selectLibraries')" [placeholder]="t('provisioning.selectLibraries')"
appendTo="body" appendTo="body"
class="libraries-select" class="libraries-select"
style="flex: 1;"> style="flex: 1;" />
</p-multiSelect>
<p-button <p-button
icon="pi pi-save" icon="pi pi-save"
[label]="'common.save' | transloco" [label]="'common.save' | transloco"
[outlined]="true" [outlined]="true"
severity="success" severity="success"
size="small" size="small"
(click)="saveOidcAutoProvisionSettings()"> (click)="saveOidcAutoProvisionSettings()" />
</p-button>
</div> </div>
</div> </div>
@@ -526,8 +513,7 @@
[outlined]="true" [outlined]="true"
severity="success" severity="success"
size="small" size="small"
(click)="openNewGroupMapping()"> (click)="openNewGroupMapping()" />
</p-button>
</div> </div>
</div> </div>
@@ -542,8 +528,7 @@
[options]="groupSyncModeOptions" [options]="groupSyncModeOptions"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
appendTo="body"> appendTo="body" />
</p-select>
<span class="field-hint">{{ t('groupMapping.syncModeHint') }}</span> <span class="field-hint">{{ t('groupMapping.syncModeHint') }}</span>
</div> </div>
<div class="config-item" style="display: flex; align-items: flex-end;"> <div class="config-item" style="display: flex; align-items: flex-end;">
@@ -553,8 +538,7 @@
icon="pi pi-save" icon="pi pi-save"
severity="success" severity="success"
size="small" size="small"
(click)="saveGroupSyncMode()"> (click)="saveGroupSyncMode()" />
</p-button>
</div> </div>
</div> </div>
@@ -591,8 +575,8 @@
<td>{{ mapping.description }}</td> <td>{{ mapping.description }}</td>
<td> <td>
<div style="display: flex; gap: 0.4375rem;"> <div style="display: flex; gap: 0.4375rem;">
<p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" size="small" (click)="openEditGroupMapping(mapping)"></p-button> <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" size="small" (click)="openEditGroupMapping(mapping)" />
<p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (click)="deleteGroupMapping(mapping)"></p-button> <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (click)="deleteGroupMapping(mapping)" />
</div> </div>
</td> </td>
</tr> </tr>
@@ -634,7 +618,7 @@
<h4 class="group-title">{{ t('groupMapping.permissionsLabel') }}</h4> <h4 class="group-title">{{ t('groupMapping.permissionsLabel') }}</h4>
<div class="permissions-grid"> <div class="permissions-grid">
<div class="permission-item"> <div class="permission-item">
<p-checkbox [binary]="true" [disabled]="true" [ngModel]="true" inputId="gmPermRead"></p-checkbox> <p-checkbox [binary]="true" [disabled]="true" [ngModel]="true" inputId="gmPermRead" />
<label for="gmPermRead">{{ t('provisioning.readBooks') }}</label> <label for="gmPermRead">{{ t('provisioning.readBooks') }}</label>
</div> </div>
<ng-container *transloco="let a; prefix: 'settingsUsers'"> <ng-container *transloco="let a; prefix: 'settingsUsers'">
@@ -663,8 +647,7 @@
(ngModelChange)="updateGroupMappingDraft({libraryIds: $event})" (ngModelChange)="updateGroupMappingDraft({libraryIds: $event})"
[placeholder]="t('provisioning.selectLibraries')" [placeholder]="t('provisioning.selectLibraries')"
appendTo="body" appendTo="body"
class="libraries-select"> class="libraries-select" />
</p-multiSelect>
</div> </div>
</div> </div>
} }
@@ -673,8 +656,7 @@
[label]="'common.save' | transloco" [label]="'common.save' | transloco"
icon="pi pi-check" icon="pi pi-check"
(click)="saveGroupMapping()" (click)="saveGroupMapping()"
[disabled]="!groupMappingDraft()?.oidcGroupClaim"> [disabled]="!groupMappingDraft()?.oidcGroupClaim" />
</p-button>
</ng-template> </ng-template>
</p-dialog> </p-dialog>
} }
@@ -45,6 +45,11 @@ import {Chip} from '@openng/optimus-ui/chip';
styleUrls: ['./authentication-settings.component.scss'] styleUrls: ['./authentication-settings.component.scss']
}) })
export class AuthenticationSettingsComponent { export class AuthenticationSettingsComponent {
private readonly appSettingsService = inject(AppSettingsService);
private readonly messageService = inject(MessageService);
private readonly libraryService = inject(LibraryService);
private readonly groupMappingService = inject(OidcGroupMappingService);
private readonly t = inject(TranslocoService);
readonly defaultMobileRedirectUri = 'grimmory://oauth2-callback'; readonly defaultMobileRedirectUri = 'grimmory://oauth2-callback';
readonly wildcardMobileRedirectUri = '*'; readonly wildcardMobileRedirectUri = '*';
availablePermissions = [ availablePermissions = [
@@ -127,12 +132,6 @@ export class AuthenticationSettingsComponent {
groups: '' groups: ''
} }
}; };
private appSettingsService = inject(AppSettingsService);
private messageService = inject(MessageService);
private libraryService = inject(LibraryService);
private groupMappingService = inject(OidcGroupMappingService);
private t = inject(TranslocoService);
get allLibraries() { return this.libraryService.libraries(); } get allLibraries() { return this.libraryService.libraries(); }
private readonly loadSettingsEffect = effect(() => { private readonly loadSettingsEffect = effect(() => {
@@ -11,9 +11,9 @@ import {AuthService} from '../../../shared/service/auth.service';
imports: [TranslocoPipe] imports: [TranslocoPipe]
}) })
export class OidcCallbackComponent implements OnInit { export class OidcCallbackComponent implements OnInit {
private router = inject(Router); private readonly router = inject(Router);
private oidcService = inject(OidcService); private readonly oidcService = inject(OidcService);
private authService = inject(AuthService); private readonly authService = inject(AuthService);
ngOnInit(): void { ngOnInit(): void {
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {firstValueFrom, Observable} from 'rxjs'; import {firstValueFrom, Observable} from 'rxjs';
import {API_CONFIG} from '../config/api-config'; import {API_CONFIG} from '../config/api-config';
@@ -17,11 +17,11 @@ interface OidcTokenResponse {
expires?: number expires?: number
} }
@Injectable({providedIn: 'root'}) @Service()
export class OidcService { export class OidcService {
private http = inject(HttpClient); private readonly http = inject(HttpClient);
private appSettingsService = inject(AppSettingsService); private readonly appSettingsService = inject(AppSettingsService);
async generatePkce(): Promise<{codeVerifier: string; codeChallenge: string}> { async generatePkce(): Promise<{codeVerifier: string; codeChallenge: string}> {
const array = new Uint8Array(32); const array = new Uint8Array(32);
@@ -9,8 +9,8 @@ import { map } from 'rxjs/operators';
pure: true pure: true
}) })
export class SecurePipe implements PipeTransform { export class SecurePipe implements PipeTransform {
private http = inject(HttpClient); private readonly http = inject(HttpClient);
private sanitizer = inject(DomSanitizer); private readonly sanitizer = inject(DomSanitizer);
transform(url: string): Observable<SafeUrl> { transform(url: string): Observable<SafeUrl> {
return this.http.get(url, { responseType: 'blob' }).pipe( return this.http.get(url, { responseType: 'blob' }).pipe(
@@ -1,8 +1,6 @@
import { Injectable } from '@angular/core'; import { Service } from '@angular/core';
@Injectable({ @Service()
providedIn: 'root'
})
export class LoadingService { export class LoadingService {
private activeLoaders: HTMLElement[] = []; private activeLoaders: HTMLElement[] = [];
@@ -48,7 +46,7 @@ export class LoadingService {
} }
hide(loader: HTMLElement): void { hide(loader: HTMLElement): void {
if (loader && loader.parentNode) { if (loader?.parentNode) {
loader.parentNode.removeChild(loader); loader.parentNode.removeChild(loader);
const index = this.activeLoaders.indexOf(loader); const index = this.activeLoaders.indexOf(loader);
@@ -64,7 +62,7 @@ export class LoadingService {
hideAll(): void { hideAll(): void {
this.activeLoaders.forEach(loader => { this.activeLoaders.forEach(loader => {
if (loader && loader.parentNode) { if (loader?.parentNode) {
loader.parentNode.removeChild(loader); loader.parentNode.removeChild(loader);
} }
}); });
@@ -1,10 +1,8 @@
import {Injectable, inject, Injector} from '@angular/core'; import {Service, inject, Injector} from '@angular/core';
import {defer, from, Observable} from 'rxjs'; import {defer, from, Observable} from 'rxjs';
import {StartupService} from '../../shared/service/startup.service'; import {StartupService} from '../../shared/service/startup.service';
@Injectable({ @Service()
providedIn: 'root'
})
export class PostLoginInitializerService { export class PostLoginInitializerService {
private readonly injector = inject(Injector); private readonly injector = inject(Injector);
@@ -1,12 +1,10 @@
import { inject, Injectable } from '@angular/core'; import { inject, Service } from '@angular/core';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker'; import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter } from 'rxjs/operators'; import { filter } from 'rxjs/operators';
@Injectable({ @Service()
providedIn: 'root'
})
export class PwaUpdateService { export class PwaUpdateService {
private swUpdate = inject(SwUpdate); private readonly swUpdate = inject(SwUpdate);
constructor() { constructor() {
if (this.swUpdate.isEnabled) { if (this.swUpdate.isEnabled) {
@@ -36,7 +34,7 @@ export class PwaUpdateService {
const guardStr = sessionStorage.getItem(key); const guardStr = sessionStorage.getItem(key);
const guard = guardStr ? JSON.parse(guardStr) : null; const guard = guardStr ? JSON.parse(guardStr) : null;
if (guard && guard.reason === reason && now - guard.timestamp < 10000) { if (guard?.reason === reason && now - guard.timestamp < 10000) {
console.error(`PWA reload guard triggered for reason: ${reason}. Stopped reloading to avoid loop.`); console.error(`PWA reload guard triggered for reason: ${reason}. Stopped reloading to avoid loop.`);
return false; return false;
} }
@@ -40,7 +40,7 @@ export function createQueryClientHarness(): QueryClientHarness {
} }
export function flushSignalAndQueryEffects(): void { export function flushSignalAndQueryEffects(): void {
TestBed.flushEffects(); TestBed.tick();
} }
export function observeActiveQuery(queryClient: QueryClient, queryKey: readonly unknown[], data: unknown) { export function observeActiveQuery(queryClient: QueryClient, queryKey: readonly unknown[], data: unknown) {
@@ -82,12 +82,12 @@ export function observeActiveQuery(queryClient: QueryClient, queryKey: readonly
export async function flushQueryAsync(rounds = 5): Promise<void> { export async function flushQueryAsync(rounds = 5): Promise<void> {
const appRef = TestBed.inject(ApplicationRef); const appRef = TestBed.inject(ApplicationRef);
for (let i = 0; i < rounds; i++) { for (let i = 0; i < rounds; i++) {
TestBed.flushEffects(); TestBed.tick();
appRef.tick(); appRef.tick();
await Promise.resolve(); await Promise.resolve();
await new Promise(resolve => setTimeout(resolve, 0)); await new Promise(resolve => setTimeout(resolve, 0));
} }
TestBed.flushEffects(); TestBed.tick();
appRef.tick(); appRef.tick();
} }
@@ -6,12 +6,11 @@
[style]="{'width': '60px', 'height': '60px'}" [style]="{'width': '60px', 'height': '60px'}"
strokeWidth="3" strokeWidth="3"
fill="transparent" fill="transparent"
animationDuration="1.5s"> animationDuration="1.5s" />
</p-progressSpinner>
</div> </div>
} }
@if (!loading()) { @else {
<div class="browse-header"> <div class="browse-header">
<h2 class="browse-title">{{ t('browseAllAuthors') }}</h2> <h2 class="browse-title">{{ t('browseAllAuthors') }}</h2>
@@ -35,14 +34,13 @@
(ngModelChange)="onSortChange($event)" (ngModelChange)="onSortChange($event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="sort-dropdown"> class="sort-dropdown" />
</p-select>
<button class="sort-direction-btn" (click)="toggleSortDirection()"> <button type="button" class="sort-direction-btn" (click)="toggleSortDirection()">
<i class="pi" [class.pi-arrow-up]="sortDirection() === 'asc'" [class.pi-arrow-down]="sortDirection() === 'desc'"></i> <i class="pi" [class.pi-arrow-up]="sortDirection() === 'asc'" [class.pi-arrow-down]="sortDirection() === 'desc'"></i>
</button> </button>
<button class="filter-btn" (click)="filterPopover.toggle($event)"> <button type="button" class="filter-btn" (click)="filterPopover.toggle($event)">
<i class="pi pi-filter"></i> <i class="pi pi-filter"></i>
@if (activeFilterCount() > 0) { @if (activeFilterCount() > 0) {
<span class="filter-badge"></span> <span class="filter-badge"></span>
@@ -84,8 +82,7 @@
(ngModelChange)="onFilterChange('matchStatus', $event)" (ngModelChange)="onFilterChange('matchStatus', $event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="filter-dropdown"> class="filter-dropdown" />
</p-select>
</div> </div>
<div class="filter-group"> <div class="filter-group">
@@ -100,8 +97,7 @@
(ngModelChange)="onFilterChange('photoStatus', $event)" (ngModelChange)="onFilterChange('photoStatus', $event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="filter-dropdown"> class="filter-dropdown" />
</p-select>
</div> </div>
<div class="filter-group"> <div class="filter-group">
@@ -118,8 +114,7 @@
(ngModelChange)="onFilterChange('readStatus', $event)" (ngModelChange)="onFilterChange('readStatus', $event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="filter-dropdown"> class="filter-dropdown" />
</p-select>
</div> </div>
<div class="filter-group"> <div class="filter-group">
@@ -142,8 +137,7 @@
(ngModelChange)="onFilterChange('bookCount', $event)" (ngModelChange)="onFilterChange('bookCount', $event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="filter-dropdown"> class="filter-dropdown" />
</p-select>
</div> </div>
<div class="filter-group"> <div class="filter-group">
@@ -154,8 +148,7 @@
(ngModelChange)="onFilterChange('library', $event)" (ngModelChange)="onFilterChange('library', $event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="filter-dropdown"> class="filter-dropdown" />
</p-select>
</div> </div>
<div class="filter-group"> <div class="filter-group">
@@ -166,8 +159,7 @@
(ngModelChange)="onFilterChange('genre', $event)" (ngModelChange)="onFilterChange('genre', $event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="filter-dropdown"> class="filter-dropdown" />
</p-select>
</div> </div>
@if (activeFilterCount() > 0) { @if (activeFilterCount() > 0) {
@@ -178,8 +170,7 @@
[outlined]="true" [outlined]="true"
size="small" size="small"
(onClick)="resetFilters()" (onClick)="resetFilters()"
class="filter-reset-btn"> class="filter-reset-btn" />
</p-button>
} }
</div> </div>
</p-popover> </p-popover>
@@ -214,8 +205,7 @@
(editAuthor)="navigateToAuthorEdit($event)" (editAuthor)="navigateToAuthorEdit($event)"
(deleteAuthor)="deleteAuthor($event)" (deleteAuthor)="deleteAuthor($event)"
(quickMatched)="onAuthorQuickMatched($event)" (quickMatched)="onAuthorQuickMatched($event)"
(checkboxClick)="onCheckboxClicked($event)"> (checkboxClick)="onCheckboxClicked($event)" />
</app-author-card>
</div> </div>
} }
} }
@@ -233,7 +223,7 @@
<span class="selected-label">{{ t('footer.selected') }}</span> <span class="selected-label">{{ t('footer.selected') }}</span>
</div> </div>
@if (canEditMetadata || canDeleteBook) { @if (canEditMetadata || canDeleteBook) {
<p-divider layout="vertical"></p-divider> <p-divider layout="vertical" />
<div class="action-buttons-group"> <div class="action-buttons-group">
@if (canEditMetadata) { @if (canEditMetadata) {
<p-button <p-button
@@ -242,8 +232,7 @@
severity="info" severity="info"
(onClick)="autoMatchSelected()" (onClick)="autoMatchSelected()"
[pTooltip]="t('footer.autoMatch')" [pTooltip]="t('footer.autoMatch')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
} }
@if (canDeleteBook) { @if (canDeleteBook) {
<p-button <p-button
@@ -252,12 +241,11 @@
severity="danger" severity="danger"
(onClick)="deleteSelected()" (onClick)="deleteSelected()"
[pTooltip]="t('footer.deleteSelected')" [pTooltip]="t('footer.deleteSelected')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
} }
</div> </div>
} }
<p-divider layout="vertical"></p-divider> <p-divider layout="vertical" />
<div class="action-buttons-group"> <div class="action-buttons-group">
<p-button <p-button
outlined="true" outlined="true"
@@ -265,16 +253,14 @@
severity="success" severity="success"
(click)="selectAllAuthors()" (click)="selectAllAuthors()"
[pTooltip]="t('footer.selectAll')" [pTooltip]="t('footer.selectAll')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
<p-button <p-button
outlined="true" outlined="true"
icon="pi pi-times" icon="pi pi-times"
severity="warn" severity="warn"
(click)="deselectAllAuthors()" (click)="deselectAllAuthors()"
[pTooltip]="t('footer.deselectAll')" [pTooltip]="t('footer.deselectAll')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -84,17 +84,17 @@ export class AuthorBrowserComponent implements OnInit {
private static readonly MIN_SCALE = 0.7; private static readonly MIN_SCALE = 0.7;
private static readonly MAX_SCALE = 1.3; private static readonly MAX_SCALE = 1.3;
private authorService = inject(AuthorService); private readonly authorService = inject(AuthorService);
private bookService = inject(BookService); private readonly bookService = inject(BookService);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private pageTitle = inject(PageTitleService); private readonly pageTitle = inject(PageTitleService);
private scrollService = inject(RouteScrollPositionService); private readonly scrollService = inject(RouteScrollPositionService);
private t = inject(TranslocoService); private readonly t = inject(TranslocoService);
private router = inject(Router); private readonly router = inject(Router);
private activatedRoute = inject(ActivatedRoute); private readonly activatedRoute = inject(ActivatedRoute);
private destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private localStorageService = inject(LocalStorageService); private readonly localStorageService = inject(LocalStorageService);
private layoutService = inject(LayoutService); private readonly layoutService = inject(LayoutService);
protected userService = inject(UserService); protected userService = inject(UserService);
protected selectionService = inject(AuthorSelectionService); protected selectionService = inject(AuthorSelectionService);
@@ -123,17 +123,17 @@ export class AuthorBrowserComponent implements OnInit {
readonly screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024); readonly screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
thumbnailCacheBusters = new Map<number, number>(); thumbnailCacheBusters = new Map<number, number>();
private selectedAuthors = this.selectionService.selectedAuthors; private readonly selectedAuthors = this.selectionService.selectedAuthors;
private allAuthorsState = signal<AuthorSummary[] | null>(null); private readonly allAuthorsState = signal<AuthorSummary[] | null>(null);
loading = computed(() => this.allAuthorsState() === null || this.bookService.isBooksLoading()); readonly loading = computed(() => this.allAuthorsState() === null || this.bookService.isBooksLoading());
protected currentUser = this.userService.currentUser; protected currentUser = this.userService.currentUser;
selectedCount = computed(() => this.selectedAuthors().size); readonly selectedCount = computed(() => this.selectedAuthors().size);
searchTerm = signal(''); readonly searchTerm = signal('');
sortBy = signal('name'); readonly sortBy = signal('name');
sortDirection = signal<SortDirection>('asc'); readonly sortDirection = signal<SortDirection>('asc');
filters = signal<AuthorFilters>({...DEFAULT_AUTHOR_FILTERS}); readonly filters = signal<AuthorFilters>({...DEFAULT_AUTHOR_FILTERS});
private enrichedAuthors = computed(() => { private readonly enrichedAuthors = computed(() => {
const authors = this.allAuthorsState(); const authors = this.allAuthorsState();
if (!authors) { if (!authors) {
return []; return [];
@@ -141,7 +141,7 @@ export class AuthorBrowserComponent implements OnInit {
return this.enrichAuthors(authors, this.bookService.books()); return this.enrichAuthors(authors, this.bookService.books());
}); });
libraryOptions = computed<FilterOption[]>(() => { readonly libraryOptions = computed<FilterOption[]>(() => {
const allLabel = this.t.translate('authorBrowser.filters.all'); const allLabel = this.t.translate('authorBrowser.filters.all');
const librarySet = new Set<string>(); const librarySet = new Set<string>();
@@ -156,7 +156,7 @@ export class AuthorBrowserComponent implements OnInit {
...[...librarySet].sort().map(library => ({label: library, value: library})) ...[...librarySet].sort().map(library => ({label: library, value: library}))
]; ];
}); });
genreOptions = computed<FilterOption[]>(() => { readonly genreOptions = computed<FilterOption[]>(() => {
const allLabel = this.t.translate('authorBrowser.filters.all'); const allLabel = this.t.translate('authorBrowser.filters.all');
const genreSet = new Set<string>(); const genreSet = new Set<string>();
@@ -171,7 +171,7 @@ export class AuthorBrowserComponent implements OnInit {
...[...genreSet].sort().map(category => ({label: category, value: category})) ...[...genreSet].sort().map(category => ({label: category, value: category}))
]; ];
}); });
activeFilterCount = computed(() => { readonly activeFilterCount = computed(() => {
const filters = this.filters(); const filters = this.filters();
let count = 0; let count = 0;
if (filters.matchStatus !== 'all') count++; if (filters.matchStatus !== 'all') count++;
@@ -182,7 +182,7 @@ export class AuthorBrowserComponent implements OnInit {
if (filters.genre !== 'all') count++; if (filters.genre !== 'all') count++;
return count; return count;
}); });
filteredAuthors = computed<EnrichedAuthor[]>(() => { readonly filteredAuthors = computed<EnrichedAuthor[]>(() => {
let result = this.enrichedAuthors(); let result = this.enrichedAuthors();
const search = this.searchTerm().trim().toLowerCase(); const search = this.searchTerm().trim().toLowerCase();
@@ -443,7 +443,7 @@ export class AuthorBrowserComponent implements OnInit {
} }
return authors.map(author => { return authors.map(author => {
const authorBooks = booksByAuthor.get(author.name.toLowerCase()) || []; const authorBooks = booksByAuthor.get(author.name.toLowerCase()) ?? [];
const libraryIds = new Set<number>(); const libraryIds = new Set<number>();
const libraryNameSet = new Set<string>(); const libraryNameSet = new Set<string>();
@@ -28,8 +28,7 @@
class="select-checkbox" class="select-checkbox"
(click)="captureMouseEvent($event)" (click)="captureMouseEvent($event)"
[ngModel]="isSelected" [ngModel]="isSelected"
(onChange)="toggleSelection($event)"> (onChange)="toggleSelection($event)" />
</p-checkbox>
} }
<div class="card-overlay"> <div class="card-overlay">
@@ -38,14 +37,13 @@
} }
<h4 class="author-name" [pTooltip]="author.name" tooltipPosition="bottom">{{ author.name }}</h4> <h4 class="author-name" [pTooltip]="author.name" tooltipPosition="bottom">{{ author.name }}</h4>
<div class="menu-button-container"> <div class="menu-button-container">
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu> <p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()" />
<p-button <p-button
class="card-menu-btn" class="card-menu-btn"
size="small" size="small"
[text]="true" [text]="true"
(click)="onMenuToggle($event, menu)" (click)="onMenuToggle($event, menu)"
icon="pi pi-ellipsis-v"> icon="pi pi-ellipsis-v" />
</p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -1,4 +1,4 @@
import {ChangeDetectorRef, Component, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges} from '@angular/core'; import {ChangeDetectorRef, Component, inject, Input, OnChanges, output, SimpleChanges} from '@angular/core';
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco'; import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {Tooltip} from '@openng/optimus-ui/tooltip'; import {Tooltip} from '@openng/optimus-ui/tooltip';
import {CheckboxChangeEvent, Checkbox} from '@openng/optimus-ui/checkbox'; import {CheckboxChangeEvent, Checkbox} from '@openng/optimus-ui/checkbox';
@@ -17,26 +17,25 @@ import {AuthorService} from '../../service/author.service';
imports: [TranslocoPipe, Tooltip, Checkbox, FormsModule, TieredMenu, Button] imports: [TranslocoPipe, Tooltip, Checkbox, FormsModule, TieredMenu, Button]
}) })
export class AuthorCardComponent implements OnChanges { export class AuthorCardComponent implements OnChanges {
private readonly authorService = inject(AuthorService);
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readonly cdr = inject(ChangeDetectorRef);
@Input({required: true}) author!: AuthorSummary; @Input({required: true}) author!: AuthorSummary;
@Input() canQuickMatch = false; @Input() canQuickMatch = false;
@Input() canDelete = false; @Input() canDelete = false;
@Input() isCheckboxEnabled = false; @Input() isCheckboxEnabled = false;
@Input() isSelected = false; @Input() isSelected = false;
@Output() cardClick = new EventEmitter<AuthorSummary>(); readonly cardClick = output<AuthorSummary>();
@Output() quickMatched = new EventEmitter<AuthorSummary>(); readonly quickMatched = output<AuthorSummary>();
@Output() checkboxClick = new EventEmitter<{ index: number; author: AuthorSummary; selected: boolean; shiftKey: boolean }>(); readonly checkboxClick = output<{ index: number; author: AuthorSummary; selected: boolean; shiftKey: boolean }>();
@Output() viewAuthor = new EventEmitter<AuthorSummary>(); readonly viewAuthor = output<AuthorSummary>();
@Output() editAuthor = new EventEmitter<AuthorSummary>(); readonly editAuthor = output<AuthorSummary>();
@Output() deleteAuthor = new EventEmitter<AuthorSummary>(); readonly deleteAuthor = output<AuthorSummary>();
@Output() menuToggled = new EventEmitter<boolean>(); readonly menuToggled = output<boolean>();
@Input() index = 0; @Input() index = 0;
@Input() cacheBuster = 0; @Input() cacheBuster = 0;
private authorService = inject(AuthorService);
private messageService = inject(MessageService);
private t = inject(TranslocoService);
private cdr = inject(ChangeDetectorRef);
private lastShiftKey = false; private lastShiftKey = false;
hasPhoto = false; hasPhoto = false;
@@ -1,8 +1,7 @@
<ng-container *transloco="let t; prefix: 'authorBrowser.detail'"> <ng-container *transloco="let t; prefix: 'authorBrowser.detail'">
@if (loading()) { @if (loading()) {
<div class="loading-state"> <div class="loading-state">
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s"> <p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s" />
</p-progressSpinner>
<p style="color: var(--primary-color);">{{ t('loading') }}</p> <p style="color: var(--primary-color);">{{ t('loading') }}</p>
</div> </div>
} }
@@ -50,13 +49,13 @@
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
class="asin-link"> class="asin-link">
<p-tag [value]="'ASIN: ' + author.asin" severity="info"></p-tag> <p-tag [value]="'ASIN: ' + author.asin" severity="info" />
</a> </a>
<a [href]="'https://www.audible.com/author/' + author.asin" <a [href]="'https://www.audible.com/author/' + author.asin"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
class="asin-link"> class="asin-link">
<p-tag value="Audible" severity="warn"></p-tag> <p-tag value="Audible" severity="warn" />
</a> </a>
} }
@if (canEditMetadata) { @if (canEditMetadata) {
@@ -68,15 +67,14 @@
[disabled]="quickMatching" [disabled]="quickMatching"
(onClick)="quickMatch()" (onClick)="quickMatch()"
[pTooltip]="t('quickMatchTooltip')" [pTooltip]="t('quickMatchTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
} }
</div> </div>
@if (author.description) { @if (author.description) {
<div class="description-box"> <div class="description-box">
<div #descriptionContent <div #descriptionContent
[ngClass]="{'line-clamp-5': !isExpanded}" [class.line-clamp-5]="!isExpanded"
class="description-container"> class="description-container">
<div class="readonly-editor">{{ author.description }}</div> <div class="readonly-editor">{{ author.description }}</div>
</div> </div>
@@ -87,8 +85,7 @@
iconPos="right" iconPos="right"
size="small" size="small"
text text
(click)="toggleExpand()"> (click)="toggleExpand()" />
</p-button>
} }
</div> </div>
} }
@@ -120,8 +117,7 @@
[index]="virtualItem.index" [index]="virtualItem.index"
[book]="book" [book]="book"
[isSeriesCollapsed]="false" [isSeriesCollapsed]="false"
[overlayPreferenceService]="bookCardOverlayPreferenceService"> [overlayPreferenceService]="bookCardOverlayPreferenceService" />
</app-legacy-book-card>
</div> </div>
</div> </div>
} }
@@ -138,15 +134,13 @@
<app-author-editor <app-author-editor
[authorId]="author.id" [authorId]="author.id"
[author]="author" [author]="author"
(authorUpdated)="onAuthorUpdated($event)"> (authorUpdated)="onAuthorUpdated($event)" />
</app-author-editor>
</p-tabpanel> </p-tabpanel>
<p-tabpanel value="match"> <p-tabpanel value="match">
<app-author-match <app-author-match
[authorId]="author.id" [authorId]="author.id"
[authorName]="author.name" [authorName]="author.name"
(authorMatched)="onAuthorUpdated($event)"> (authorMatched)="onAuthorUpdated($event)" />
</app-author-match>
</p-tabpanel> </p-tabpanel>
} }
</p-tabpanels> </p-tabpanels>
@@ -1,6 +1,5 @@
import { AfterViewChecked, Component, computed, ElementRef, inject, OnInit, signal, viewChild } from '@angular/core'; import { AfterViewChecked, Component, computed, ElementRef, inject, OnInit, signal, viewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { NgClass } from '@angular/common';
import { Tab, TabList, TabPanel, TabPanels, Tabs } from '@openng/optimus-ui/tabs'; import { Tab, TabList, TabPanel, TabPanels, Tabs } from '@openng/optimus-ui/tabs';
import { ProgressSpinner } from '@openng/optimus-ui/progressspinner'; import { ProgressSpinner } from '@openng/optimus-ui/progressspinner';
import { Button } from '@openng/optimus-ui/button'; import { Button } from '@openng/optimus-ui/button';
@@ -26,7 +25,6 @@ import { createVirtualGrid } from '../../../../shared/util/virtual-grid.util';
templateUrl: './author-detail.component.html', templateUrl: './author-detail.component.html',
styleUrls: ['./author-detail.component.scss'], styleUrls: ['./author-detail.component.scss'],
imports: [ imports: [
NgClass,
Tabs, Tabs,
TabList, TabList,
Tab, Tab,
@@ -46,30 +44,30 @@ export class AuthorDetailComponent implements OnInit, AfterViewChecked {
private static readonly GRID_GAP = 21; private static readonly GRID_GAP = 21;
private route = inject(ActivatedRoute); private readonly route = inject(ActivatedRoute);
private router = inject(Router); private readonly router = inject(Router);
private authorService = inject(AuthorService); private readonly authorService = inject(AuthorService);
private bookService = inject(BookService); private readonly bookService = inject(BookService);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
protected coverScalePreferenceService = inject(CoverScalePreferenceService); protected coverScalePreferenceService = inject(CoverScalePreferenceService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService); protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
protected userService = inject(UserService); protected userService = inject(UserService);
private pageTitle = inject(PageTitleService); private readonly pageTitle = inject(PageTitleService);
private t = inject(TranslocoService); private readonly t = inject(TranslocoService);
readonly descriptionContentRef = viewChild<ElementRef<HTMLElement>>('descriptionContent'); readonly descriptionContentRef = viewChild<ElementRef<HTMLElement>>('descriptionContent');
private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement'); private readonly scrollElement = viewChild<ElementRef<HTMLElement>>('scrollElement');
loading = signal(true); readonly loading = signal(true);
tab = 'books'; tab = 'books';
isExpanded = false; isExpanded = false;
isOverflowing = false; isOverflowing = false;
hasPhoto = true; hasPhoto = true;
photoTimestamp = Date.now(); photoTimestamp = Date.now();
quickMatching = false; quickMatching = false;
private authorState = signal<AuthorDetails | null>(null); private readonly authorState = signal<AuthorDetails | null>(null);
author = this.authorState.asReadonly(); author = this.authorState.asReadonly();
authorBooks = computed(() => { readonly authorBooks = computed(() => {
const authorName = this.author()?.name?.toLowerCase(); const authorName = this.author()?.name?.toLowerCase();
if (!authorName) { if (!authorName) {
return []; return [];
@@ -8,8 +8,7 @@
width="200" width="200"
appendTo="body" appendTo="body"
[preview]="true" [preview]="true"
(onImageError)="onPhotoError()"> (onImageError)="onPhotoError()" />
</p-image>
} @else { } @else {
<div class="photo-placeholder"> <div class="photo-placeholder">
<i class="pi pi-user"></i> <i class="pi pi-user"></i>
@@ -17,7 +16,7 @@
} }
@if (isUploading()) { @if (isUploading()) {
<p-progressSpinner class="upload-spinner" strokeWidth="4" fill="transparent" animationDuration=".8s"></p-progressSpinner> <p-progressSpinner class="upload-spinner" strokeWidth="4" fill="transparent" animationDuration=".8s" />
} }
<div class="cover-actions"> <div class="cover-actions">
@@ -34,8 +33,7 @@
(onUpload)="onUpload()" (onUpload)="onUpload()"
(onError)="onUploadError()" (onError)="onUploadError()"
[auto]="true" [auto]="true"
(onBeforeUpload)="onBeforeUpload()"> (onBeforeUpload)="onBeforeUpload()" />
</p-fileupload>
<p-button <p-button
[pTooltip]="t('searchPhotoTooltip')" [pTooltip]="t('searchPhotoTooltip')"
@@ -45,8 +43,7 @@
[outlined]="true" [outlined]="true"
[disabled]="form.get('photoLocked')?.value" [disabled]="form.get('photoLocked')?.value"
(onClick)="openPhotoSearch()" (onClick)="openPhotoSearch()"
severity="info"> severity="info" />
</p-button>
@if (!form.get('photoLocked')?.value) { @if (!form.get('photoLocked')?.value) {
<p-button <p-button
@@ -56,10 +53,9 @@
icon="pi pi-lock-open" icon="pi pi-lock-open"
[outlined]="true" [outlined]="true"
(onClick)="togglePhotoLock()" (onClick)="togglePhotoLock()"
severity="success"> severity="success" />
</p-button>
} }
@if (form.get('photoLocked')?.value) { @else {
<p-button <p-button
[pTooltip]="t('unlockField')" [pTooltip]="t('unlockField')"
tooltipPosition="top" tooltipPosition="top"
@@ -67,8 +63,7 @@
icon="pi pi-lock" icon="pi pi-lock"
[outlined]="true" [outlined]="true"
(onClick)="togglePhotoLock()" (onClick)="togglePhotoLock()"
severity="warn"> severity="warn" />
</p-button>
} }
</div> </div>
</div> </div>
@@ -79,10 +74,10 @@
<div class="field-with-lock"> <div class="field-with-lock">
<input pInputText id="authorName" formControlName="name"/> <input pInputText id="authorName" formControlName="name"/>
@if (!form.get('nameLocked')?.value) { @if (!form.get('nameLocked')?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('name')" severity="success"></p-button> <p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('name')" severity="success" />
} }
@if (form.get('nameLocked')?.value) { @else {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('name')" severity="warn"></p-button> <p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('name')" severity="warn" />
} }
</div> </div>
</div> </div>
@@ -92,10 +87,10 @@
<div class="field-with-lock"> <div class="field-with-lock">
<input pInputText id="authorAsin" formControlName="asin"/> <input pInputText id="authorAsin" formControlName="asin"/>
@if (!form.get('asinLocked')?.value) { @if (!form.get('asinLocked')?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success"></p-button> <p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success" />
} }
@if (form.get('asinLocked')?.value) { @else {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn"></p-button> <p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn" />
} }
</div> </div>
</div> </div>
@@ -106,26 +101,25 @@
<textarea pTextarea id="authorDescription" formControlName="description" <textarea pTextarea id="authorDescription" formControlName="description"
[rows]="8" [autoResize]="true"></textarea> [rows]="8" [autoResize]="true"></textarea>
@if (!form.get('descriptionLocked')?.value) { @if (!form.get('descriptionLocked')?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('description')" severity="success" size="small"></p-button> <p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('description')" severity="success" size="small" />
} }
@if (form.get('descriptionLocked')?.value) { @else {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('description')" severity="warn" size="small"></p-button> <p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('description')" severity="warn" size="small" />
} }
</div> </div>
</div> </div>
<div class="form-footer"> <div class="form-footer">
<p-divider></p-divider> <p-divider />
<div class="footer-actions"> <div class="footer-actions">
<p-button [label]="t('unlockAllBtn')" icon="pi pi-lock-open" [outlined]="true" severity="success" (onClick)="unlockAll()"></p-button> <p-button [label]="t('unlockAllBtn')" icon="pi pi-lock-open" [outlined]="true" severity="success" (onClick)="unlockAll()" />
<p-button [label]="t('lockAllBtn')" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()"></p-button> <p-button [label]="t('lockAllBtn')" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()" />
<p-divider layout="vertical"/> <p-divider layout="vertical"/>
<p-button <p-button
type="submit" type="submit"
[label]="isSaving() ? t('saving') : t('saveBtn')" [label]="isSaving() ? t('saving') : t('saveBtn')"
[icon]="isSaving() ? 'pi pi-spin pi-spinner' : 'pi pi-check'" [icon]="isSaving() ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[disabled]="isSaving()"> [disabled]="isSaving()" />
</p-button>
</div> </div>
</div> </div>
</form> </form>
@@ -1,4 +1,4 @@
import {Component, EventEmitter, inject, Input, OnChanges, OnInit, Output, signal, SimpleChanges} from '@angular/core'; import {Component, inject, Input, OnChanges, OnInit, output, signal, SimpleChanges} from '@angular/core';
import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms'; import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Button} from '@openng/optimus-ui/button'; import {Button} from '@openng/optimus-ui/button';
@@ -35,19 +35,18 @@ import {AuthorPhotoSearchComponent} from '../author-photo-search/author-photo-se
providers: [DialogService] providers: [DialogService]
}) })
export class AuthorEditorComponent implements OnInit, OnChanges { export class AuthorEditorComponent implements OnInit, OnChanges {
private readonly authorService = inject(AuthorService);
private readonly messageService = inject(MessageService);
private readonly dialogService = inject(DialogService);
private readonly t = inject(TranslocoService);
@Input({required: true}) authorId!: number; @Input({required: true}) authorId!: number;
@Input({required: true}) author!: AuthorDetails; @Input({required: true}) author!: AuthorDetails;
@Output() authorUpdated = new EventEmitter<AuthorDetails>(); readonly authorUpdated = output<AuthorDetails>();
private authorService = inject(AuthorService);
private messageService = inject(MessageService);
private dialogService = inject(DialogService);
private t = inject(TranslocoService);
form!: FormGroup; form!: FormGroup;
isSaving = signal(false); readonly isSaving = signal(false);
isUploading = signal(false); readonly isUploading = signal(false);
hasPhoto = true; hasPhoto = true;
photoTimestamp = Date.now(); photoTimestamp = Date.now();
@@ -19,8 +19,7 @@
(ngModelChange)="selectedRegion.set($event)" (ngModelChange)="selectedRegion.set($event)"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
class="region-dropdown"> class="region-dropdown" />
</p-select>
</div> </div>
<div class="field search-btn-field"> <div class="field search-btn-field">
<p-button <p-button
@@ -28,8 +27,7 @@
icon="pi pi-search" icon="pi pi-search"
(onClick)="search()" (onClick)="search()"
[loading]="searching()" [loading]="searching()"
[disabled]="!canSearch()"> [disabled]="!canSearch()" />
</p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -40,8 +38,7 @@
[style]="{'width': '40px', 'height': '40px'}" [style]="{'width': '40px', 'height': '40px'}"
strokeWidth="3" strokeWidth="3"
fill="transparent" fill="transparent"
animationDuration="1.5s"> animationDuration="1.5s" />
</p-progressSpinner>
<span>{{ t('searching') }}</span> <span>{{ t('searching') }}</span>
</div> </div>
} }
@@ -91,8 +88,7 @@
icon="pi pi-link" icon="pi pi-link"
severity="success" severity="success"
[loading]="matching()" [loading]="matching()"
(onClick)="matchAuthor(result)"> (onClick)="matchAuthor(result)" />
</p-button>
</div> </div>
</div> </div>
} }
@@ -1,4 +1,4 @@
import {ChangeDetectionStrategy, Component, computed, EventEmitter, inject, Input, OnInit, Output, signal} from '@angular/core'; import {ChangeDetectionStrategy, Component, computed, inject, Input, OnInit, output, signal} from '@angular/core';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {Button} from '@openng/optimus-ui/button'; import {Button} from '@openng/optimus-ui/button';
import {InputText} from '@openng/optimus-ui/inputtext'; import {InputText} from '@openng/optimus-ui/inputtext';
@@ -30,24 +30,23 @@ interface RegionOption {
] ]
}) })
export class AuthorMatchComponent implements OnInit { export class AuthorMatchComponent implements OnInit {
private readonly authorService = inject(AuthorService);
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
@Input({required: true}) authorId!: number; @Input({required: true}) authorId!: number;
@Input({required: true}) authorName!: string; @Input({required: true}) authorName!: string;
@Output() authorMatched = new EventEmitter<AuthorDetails>(); readonly authorMatched = output<AuthorDetails>();
private authorService = inject(AuthorService); readonly searchQuery = signal('');
private messageService = inject(MessageService); readonly asinQuery = signal('');
private t = inject(TranslocoService); readonly selectedRegion = signal('us');
readonly searching = signal(false);
readonly matching = signal(false);
readonly results = signal<AuthorSearchResult[]>([]);
readonly hasSearched = signal(false);
searchQuery = signal(''); readonly canSearch = computed(() => !!this.searchQuery().trim() || !!this.asinQuery().trim());
asinQuery = signal('');
selectedRegion = signal('us');
searching = signal(false);
matching = signal(false);
results = signal<AuthorSearchResult[]>([]);
hasSearched = signal(false);
canSearch = computed(() => !!this.searchQuery().trim() || !!this.asinQuery().trim());
regionOptions: RegionOption[] = [ regionOptions: RegionOption[] = [
{label: 'US', value: 'us'}, {label: 'US', value: 'us'},
@@ -21,8 +21,7 @@
[label]="t('searchBtn')" [label]="t('searchBtn')"
icon="pi pi-search" icon="pi pi-search"
[loading]="searching" [loading]="searching"
[disabled]="searchForm.invalid"> [disabled]="searchForm.invalid" />
</p-button>
<p-button <p-button
type="button" type="button"
icon="pi pi-refresh" icon="pi pi-refresh"
@@ -31,8 +30,7 @@
severity="secondary" severity="secondary"
(click)="onClear()" (click)="onClear()"
[pTooltip]="t('resetTooltip')" [pTooltip]="t('resetTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</div> </div>
</div> </div>
</form> </form>
@@ -49,7 +47,7 @@
</div> </div>
} @else if (searching) { } @else if (searching) {
<div class="loading-state"> <div class="loading-state">
<p-progressSpinner strokeWidth="3" animationDuration="1s"></p-progressSpinner> <p-progressSpinner strokeWidth="3" animationDuration="1s" />
<p>{{ t('searching') }}</p> <p>{{ t('searching') }}</p>
</div> </div>
} @else if (photos.length === 0) { } @else if (photos.length === 0) {
@@ -76,8 +74,7 @@
[src]="photo.url" [src]="photo.url"
[alt]="t('photoAlt', { index: i + 1 })" [alt]="t('photoAlt', { index: i + 1 })"
appendTo="body" appendTo="body"
[preview]="true"> [preview]="true" />
</p-image>
@if (photo.width && photo.height) { @if (photo.width && photo.height) {
<div class="resolution-badge"> <div class="resolution-badge">
{{ photo.width }} x {{ photo.height }} {{ photo.width }} x {{ photo.height }}
@@ -88,8 +85,7 @@
(click)="selectAndUploadPhoto(photo)" (click)="selectAndUploadPhoto(photo)"
[label]="t('selectBtn')" [label]="t('selectBtn')"
icon="pi pi-check" icon="pi pi-check"
size="small"> size="small" />
</p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -27,18 +27,17 @@ import {AuthorPhotoResult} from '../../model/author.model';
] ]
}) })
export class AuthorPhotoSearchComponent implements OnInit { export class AuthorPhotoSearchComponent implements OnInit {
private readonly fb = inject(FormBuilder);
private readonly authorService = inject(AuthorService);
private readonly dynamicDialogConfig = inject(DynamicDialogConfig);
protected dynamicDialogRef = inject(DynamicDialogRef);
private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
searchForm: FormGroup; searchForm: FormGroup;
photos: AuthorPhotoResult[] = []; photos: AuthorPhotoResult[] = [];
searching = false; searching = false;
hasSearched = false; hasSearched = false;
private fb = inject(FormBuilder);
private authorService = inject(AuthorService);
private dynamicDialogConfig = inject(DynamicDialogConfig);
protected dynamicDialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService);
private t = inject(TranslocoService);
private authorId!: number; private authorId!: number;
constructor() { constructor() {
@@ -1,4 +1,4 @@
import {computed, Injectable, signal} from '@angular/core'; import {computed, Service, signal} from '@angular/core';
import {AuthorSummary} from '../model/author.model'; import {AuthorSummary} from '../model/author.model';
export interface AuthorCheckboxClickEvent { export interface AuthorCheckboxClickEvent {
@@ -8,7 +8,7 @@ export interface AuthorCheckboxClickEvent {
shiftKey: boolean; shiftKey: boolean;
} }
@Injectable({providedIn: 'root'}) @Service()
export class AuthorSelectionService { export class AuthorSelectionService {
private readonly _selectedAuthors = signal<Set<number>>(new Set()); private readonly _selectedAuthors = signal<Set<number>>(new Set());
readonly selectedAuthors = this._selectedAuthors.asReadonly(); readonly selectedAuthors = this._selectedAuthors.asReadonly();
@@ -1,4 +1,4 @@
import {computed, DestroyRef, effect, inject, Injectable} from '@angular/core'; import {computed, DestroyRef, effect, inject, Service} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http'; import {HttpClient, HttpHeaders} from '@angular/common/http';
import {lastValueFrom, Observable} from 'rxjs'; import {lastValueFrom, Observable} from 'rxjs';
import {map, tap} from 'rxjs/operators'; import {map, tap} from 'rxjs/operators';
@@ -12,29 +12,27 @@ import {AUTHORS_QUERY_KEY} from './author-query-keys';
import {invalidateAuthorsQuery, patchAuthorInCache} from './author-query-cache'; import {invalidateAuthorsQuery, patchAuthorInCache} from './author-query-cache';
import {invalidateAllBookCaches} from '../../book/service/legacy-book-cache'; import {invalidateAllBookCaches} from '../../book/service/legacy-book-cache';
@Injectable({ @Service()
providedIn: 'root'
})
export class AuthorService { export class AuthorService {
private http = inject(HttpClient); private readonly http = inject(HttpClient);
private authService = inject(AuthService); private readonly authService = inject(AuthService);
private sseClient = inject(SseClient); private readonly sseClient = inject(SseClient);
private queryClient = inject(QueryClient); private readonly queryClient = inject(QueryClient);
private destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`; private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`;
private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`; private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`;
private readonly token = this.authService.token; private readonly token = this.authService.token;
private readonly authorInvalidationDebounceMs = 200; private readonly authorInvalidationDebounceMs = 200;
private authorInvalidationTimer: ReturnType<typeof setTimeout> | null = null; private authorInvalidationTimer: ReturnType<typeof setTimeout> | null = null;
private authorsQuery = injectQuery(() => ({ private readonly authorsQuery = injectQuery(() => ({
...this.getAuthorsQueryOptions(), ...this.getAuthorsQueryOptions(),
enabled: !!this.token(), enabled: !!this.token(),
})); }));
allAuthors = computed(() => this.authorsQuery.data() ?? null); readonly allAuthors = computed(() => this.authorsQuery.data() ?? null);
isAuthorsLoading = computed(() => !!this.token() && this.authorsQuery.isPending()); readonly isAuthorsLoading = computed(() => !!this.token() && this.authorsQuery.isPending());
constructor() { constructor() {
this.destroyRef.onDestroy(() => this.clearAuthorInvalidationTimer()); this.destroyRef.onDestroy(() => this.clearAuthorInvalidationTimer());
@@ -60,14 +60,13 @@ const NO_OVERFLOW: ReadonlySet<string> = new Set();
templateUrl: './book-browse-bulk-bar.component.html', templateUrl: './book-browse-bulk-bar.component.html',
}) })
export class BookBrowseBulkBarComponent { export class BookBrowseBulkBarComponent {
private readonly userService = inject(UserService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly shelfDefinitionQuery = inject(ShelfDefinitionQueryService);
readonly selection = input.required<BrowseSelection>(); readonly selection = input.required<BrowseSelection>();
readonly books = input.required<readonly BookSummary[]>(); readonly books = input.required<readonly BookSummary[]>();
readonly total = input.required<number | null>(); readonly total = input.required<number | null>();
readonly fetchIds = input.required<() => Promise<readonly number[]>>(); readonly fetchIds = input.required<() => Promise<readonly number[]>>();
private readonly userService = inject(UserService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly shelfDefinitionQuery = inject(ShelfDefinitionQueryService);
protected readonly commands = createBookBrowseBulkCommands({ protected readonly commands = createBookBrowseBulkCommands({
selection: this.selection, selection: this.selection,
books: this.books, books: this.books,
@@ -1,10 +1,10 @@
import {Injectable, inject} from '@angular/core'; import {Service, inject} from '@angular/core';
import {LocalStorageService} from '../../../shared/service/local-storage.service'; import {LocalStorageService} from '../../../shared/service/local-storage.service';
const STORAGE_KEY = 'browseTableColumnWidths'; const STORAGE_KEY = 'browseTableColumnWidths';
@Injectable({providedIn: 'root'}) @Service()
export class BookBrowseColumnWidthPreferenceService { export class BookBrowseColumnWidthPreferenceService {
private readonly localStorage = inject(LocalStorageService); private readonly localStorage = inject(LocalStorageService);
@@ -1,4 +1,4 @@
import {Injectable, inject} from '@angular/core'; import {Service, inject} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop'; import {toSignal} from '@angular/core/rxjs-interop';
import {TranslocoService} from '@jsverse/transloco'; import {TranslocoService} from '@jsverse/transloco';
@@ -7,7 +7,7 @@ import {type BookSummary} from '../data/book-response.models';
import {formatBookValue} from './book-browse-columns'; import {formatBookValue} from './book-browse-columns';
import {type BookColumnKind, type BookColumnValue, type BookDetailLineSortKey} from './book-browse-fields'; import {type BookColumnKind, type BookColumnValue, type BookDetailLineSortKey} from './book-browse-fields';
@Injectable({providedIn: 'root'}) @Service()
export class BookBrowseDetailLineService { export class BookBrowseDetailLineService {
private readonly transloco = inject(TranslocoService); private readonly transloco = inject(TranslocoService);
private readonly activeLang = toSignal(this.transloco.langChanges$, { private readonly activeLang = toSignal(this.transloco.langChanges$, {
@@ -120,6 +120,14 @@ const BODY_CELL_CLASS =
}, },
}) })
export class BookBrowseTableComponent { export class BookBrowseTableComponent {
private readonly transloco = inject(TranslocoService);
private readonly urlHelper = inject(UrlHelperService);
private readonly router = inject(Router);
private readonly locationStrategy = inject(LocationStrategy);
private readonly route = inject(ActivatedRoute);
private readonly scrollPosition = inject(RouteScrollPositionService);
private readonly destroyRef = inject(DestroyRef);
private readonly columnWidthPreference = inject(BookBrowseColumnWidthPreferenceService);
readonly books = input.required<readonly BookSummary[]>(); readonly books = input.required<readonly BookSummary[]>();
readonly status = input.required<BrowseStatus>(); readonly status = input.required<BrowseStatus>();
readonly hasNextPage = input.required<boolean>(); readonly hasNextPage = input.required<boolean>();
@@ -146,15 +154,6 @@ export class BookBrowseTableComponent {
readonly emptyDef = contentChild.required(BrowseEmptyDef); readonly emptyDef = contentChild.required(BrowseEmptyDef);
private readonly transloco = inject(TranslocoService);
private readonly urlHelper = inject(UrlHelperService);
private readonly router = inject(Router);
private readonly locationStrategy = inject(LocationStrategy);
private readonly route = inject(ActivatedRoute);
private readonly scrollPosition = inject(RouteScrollPositionService);
private readonly destroyRef = inject(DestroyRef);
private readonly columnWidthPreference = inject(BookBrowseColumnWidthPreferenceService);
private readonly initialColumnSizing: ColumnSizingState = this.columnWidthPreference.load(); private readonly initialColumnSizing: ColumnSizingState = this.columnWidthPreference.load();
private readonly selectColumnVisible = computed(() => this.selection() !== null); private readonly selectColumnVisible = computed(() => this.selection() !== null);
private readonly sortOptionsById = computed(() => private readonly sortOptionsById = computed(() =>
@@ -112,8 +112,7 @@
[placeholder]="t('authorsPlaceholder')" [placeholder]="t('authorsPlaceholder')"
(completeMethod)="filterAuthors($event)" (completeMethod)="filterAuthors($event)"
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)" (onKeyUp)="onAutoCompleteKeyUp('authors', $event)"
(onSelect)="onAutoCompleteSelect('authors', $event)"> (onSelect)="onAutoCompleteSelect('authors', $event)" />
</p-autoComplete>
</div> </div>
</div> </div>
</div> </div>
@@ -192,8 +191,7 @@
[(ngModel)]="pageCount" [(ngModel)]="pageCount"
[useGrouping]="false" [useGrouping]="false"
[placeholder]="t('pageCountPlaceholder')" [placeholder]="t('pageCountPlaceholder')"
class="input-full"> class="input-full" />
</p-inputnumber>
</div> </div>
</div> </div>
@@ -217,8 +215,7 @@
[placeholder]="t('categoriesPlaceholder')" [placeholder]="t('categoriesPlaceholder')"
(completeMethod)="filterCategories($event)" (completeMethod)="filterCategories($event)"
(onKeyUp)="onAutoCompleteKeyUp('categories', $event)" (onKeyUp)="onAutoCompleteKeyUp('categories', $event)"
(onSelect)="onAutoCompleteSelect('categories', $event)"> (onSelect)="onAutoCompleteSelect('categories', $event)" />
</p-autoComplete>
</div> </div>
</div> </div>
</div> </div>
@@ -34,12 +34,12 @@ import {TranslocoDirective} from '@jsverse/transloco';
styleUrl: './add-physical-book-dialog.component.scss', styleUrl: './add-physical-book-dialog.component.scss',
}) })
export class AddPhysicalBookDialogComponent { export class AddPhysicalBookDialogComponent {
private dynamicDialogRef = inject(DynamicDialogRef); private readonly dynamicDialogRef = inject(DynamicDialogRef);
private dialogConfig = inject(DynamicDialogConfig); private readonly dialogConfig = inject(DynamicDialogConfig);
private bookService = inject(BookService); private readonly bookService = inject(BookService);
private queryClient = inject(QueryClient); private readonly queryClient = inject(QueryClient);
private sources = inject(MetadataSourceQueryService); private readonly sources = inject(MetadataSourceQueryService);
private libraryService = inject(LibraryService); private readonly libraryService = inject(LibraryService);
selectedLibraryId: number | null = null; selectedLibraryId: number | null = null;
title: string = ''; title: string = '';
@@ -59,8 +59,8 @@ export class AddPhysicalBookDialogComponent {
filteredCategories: string[] = []; filteredCategories: string[] = [];
coverUrl: string | null = null; coverUrl: string | null = null;
isLoading = signal(false); readonly isLoading = signal(false);
isFetchingMetadata = signal(false); readonly isFetchingMetadata = signal(false);
readonly metadataLookupMessage = signal<'metadataNotFound' | 'metadataLookupFailed' | null>(null); readonly metadataLookupMessage = signal<'metadataNotFound' | 'metadataLookupFailed' | null>(null);
private readonly initializeSelectedLibraryEffect = effect(() => { private readonly initializeSelectedLibraryEffect = effect(() => {
const libraries = this.libraries; const libraries = this.libraries;
@@ -14,8 +14,7 @@
[text]="true" [text]="true"
severity="secondary" severity="secondary"
(click)="closeDialog()" (click)="closeDialog()"
class="close-button"> class="close-button" />
</p-button>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
@@ -29,7 +28,7 @@
[placeholder]="t('selectFileType')" [placeholder]="t('selectFileType')"
class="full-width" class="full-width"
[disabled]="isUploading" [disabled]="isUploading"
></p-select> />
<!-- File Upload --> <!-- File Upload -->
<p-fileupload class="file-upload" name="file" <p-fileupload class="file-upload" name="file"
@@ -109,6 +108,7 @@
tooltipPosition="top"> tooltipPosition="top">
</i> </i>
} }
@default never;
} }
</div> </div>
} }
@@ -118,7 +118,7 @@
} }
</div> </div>
</ng-template> </ng-template>
<ng-template #file></ng-template> <ng-template #file />
<ng-template #empty> <ng-template #empty>
<div class="empty-state"> <div class="empty-state">
<i class="pi pi-cloud-upload empty-icon"></i> <i class="pi pi-cloud-upload empty-icon"></i>
@@ -42,12 +42,12 @@ interface UploadingFile {
}) })
export class AdditionalFileUploaderComponent implements OnInit, OnDestroy { export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
private dialogRef = inject(DynamicDialogRef); private readonly dialogRef = inject(DynamicDialogRef);
private config = inject(DynamicDialogConfig); private readonly config = inject(DynamicDialogConfig);
private bookFileService = inject(BookFileService); private readonly bookFileService = inject(BookFileService);
private appSettingsService = inject(AppSettingsService); private readonly appSettingsService = inject(AppSettingsService);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private cdr = inject(ChangeDetectorRef); private readonly cdr = inject(ChangeDetectorRef);
book!: Book; book!: Book;
files: UploadingFile[] = []; files: UploadingFile[] = [];
@@ -60,8 +60,8 @@ export class AdditionalFileUploaderComponent implements OnInit, OnDestroy {
fileTypeOptions: FileTypeOption[] = []; fileTypeOptions: FileTypeOption[] = [];
@ViewChild(FileUpload) private fileUpload!: FileUpload; @ViewChild(FileUpload) private readonly fileUpload!: FileUpload;
private destroy$ = new Subject<void>(); private readonly destroy$ = new Subject<void>();
ngOnInit(): void { ngOnInit(): void {
this.book = this.config.data.book; this.book = this.config.data.book;
@@ -20,8 +20,7 @@
[rounded]="true" [rounded]="true"
[pTooltip]="book.metadata?.title" [pTooltip]="book.metadata?.title"
tooltipPosition="top" tooltipPosition="top"
[ngClass]="{ 'is-visible': isHovered }" [class.is-visible]="isHovered"
(onClick)="openBookInfo(book)"> (onClick)="openBookInfo(book)" />
</p-button>
} }
</div> </div>
@@ -5,7 +5,6 @@ import {CoverComponent} from '../../../../shared/components/cover/cover.componen
import {Button} from '@openng/optimus-ui/button'; import {Button} from '@openng/optimus-ui/button';
import {UserService} from '../../../settings/user-management/user.service'; import {UserService} from '../../../settings/user-management/user.service';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {NgClass} from '@angular/common';
import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service'; import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service';
import {Tooltip} from '@openng/optimus-ui/tooltip'; import {Tooltip} from '@openng/optimus-ui/tooltip';
@@ -14,7 +13,6 @@ import {Tooltip} from '@openng/optimus-ui/tooltip';
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ imports: [
Button, Button,
NgClass,
Tooltip, Tooltip,
CoverComponent CoverComponent
], ],
@@ -22,16 +20,15 @@ import {Tooltip} from '@openng/optimus-ui/tooltip';
styleUrl: './book-card-lite-component.scss' styleUrl: './book-card-lite-component.scss'
}) })
export class BookCardLiteComponent { export class BookCardLiteComponent {
private readonly router = inject(Router);
protected urlHelper = inject(UrlHelperService);
private readonly userService = inject(UserService);
private readonly bookMetadataHostService = inject(BookMetadataHostService);
@Input() book!: Book; @Input() book!: Book;
@Input() isActive: boolean = false; @Input() isActive: boolean = false;
@Input() showSeriesNumber: boolean = false; @Input() showSeriesNumber: boolean = false;
private router = inject(Router); private readonly metadataCenterViewMode = computed(() =>
protected urlHelper = inject(UrlHelperService);
private userService = inject(UserService);
private bookMetadataHostService = inject(BookMetadataHostService);
private metadataCenterViewMode = computed(() =>
this.userService.currentUser()?.userSettings.metadataCenterViewMode ?? 'route' this.userService.currentUser()?.userSettings.metadataCenterViewMode ?? 'route'
); );
isHovered: boolean = false; isHovered: boolean = false;
@@ -9,8 +9,7 @@
<p class="panel-description">{{ isBulkMode ? t('descriptionBulk') : t('description') }}</p> <p class="panel-description">{{ isBulkMode ? t('descriptionBulk') : t('description') }}</p>
</div> </div>
<p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="secondary" (click)="closeDialog()" <p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="secondary" (click)="closeDialog()"
class="close-button"> class="close-button" />
</p-button>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
@@ -61,8 +60,7 @@
<!-- Options --> <!-- Options -->
<div class="delete-option"> <div class="delete-option">
<p-checkbox [(ngModel)]="moveFiles" [binary]="true" inputId="moveFiles" [disabled]="isAttaching"> <p-checkbox [(ngModel)]="moveFiles" [binary]="true" inputId="moveFiles" [disabled]="isAttaching" />
</p-checkbox>
<label for="moveFiles" class="delete-label"> <label for="moveFiles" class="delete-label">
{{ t('moveFilesLabel') }} {{ t('moveFilesLabel') }}
</label> </label>
@@ -84,11 +82,9 @@
<!-- Action Buttons --> <!-- Action Buttons -->
<div class="action-buttons"> <div class="action-buttons">
<p-button [label]="'common.cancel' | transloco" [outlined]="true" severity="secondary" (click)="closeDialog()" <p-button [label]="'common.cancel' | transloco" [outlined]="true" severity="secondary" (click)="closeDialog()"
[disabled]="isAttaching"> [disabled]="isAttaching" />
</p-button>
<p-button [label]="isBulkMode ? t('attachFilesBulk') : t('attachFile')" icon="pi pi-link" (click)="attach()" <p-button [label]="isBulkMode ? t('attachFilesBulk') : t('attachFile')" icon="pi pi-link" (click)="attach()"
[disabled]="!canAttach()" [loading]="isAttaching"> [disabled]="!canAttach()" [loading]="isAttaching" />
</p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -34,6 +34,13 @@ export interface BookFileAttacherSourceBook {
styleUrls: ['./book-file-attacher.component.scss'] styleUrls: ['./book-file-attacher.component.scss']
}) })
export class BookFileAttacherComponent implements OnInit, AfterViewInit, OnDestroy { export class BookFileAttacherComponent implements OnInit, AfterViewInit, OnDestroy {
private readonly t = inject(TranslocoService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly dialogRef = inject(DynamicDialogRef);
private readonly config = inject(DynamicDialogConfig);
private readonly bookService = inject(BookService);
private readonly bookFileService = inject(BookFileService);
private readonly messageService = inject(MessageService);
@ViewChild('autocompleteWrapper') autocompleteWrapper!: ElementRef; @ViewChild('autocompleteWrapper') autocompleteWrapper!: ElementRef;
sourceBooks: readonly BookFileAttacherSourceBook[] = []; sourceBooks: readonly BookFileAttacherSourceBook[] = [];
@@ -44,17 +51,9 @@ export class BookFileAttacherComponent implements OnInit, AfterViewInit, OnDestr
filteredBooks: Book[] = []; filteredBooks: Book[] = [];
autocomplePanelStyle: Record<string, string> = {}; autocomplePanelStyle: Record<string, string> = {};
private destroy$ = new Subject<void>(); private readonly destroy$ = new Subject<void>();
private allBooks: Signal<Book[]> = signal([]); private allBooks: Signal<Book[]> = signal([]);
private readonly t = inject(TranslocoService);
private readonly appSettingsService = inject(AppSettingsService);
private dialogRef = inject(DynamicDialogRef);
private config = inject(DynamicDialogConfig);
private bookService = inject(BookService);
private bookFileService = inject(BookFileService);
private messageService = inject(MessageService);
ngAfterViewInit(): void { ngAfterViewInit(): void {
setTimeout(() => { setTimeout(() => {
const width = this.autocompleteWrapper?.nativeElement?.offsetWidth; const width = this.autocompleteWrapper?.nativeElement?.offsetWidth;
@@ -101,11 +101,6 @@ const BOOK_MENU_READ_ACTION_LABEL_KEYS: Readonly<Record<BookReadAction, string>>
templateUrl: './book-menu.component.html', templateUrl: './book-menu.component.html',
}) })
export class BookMenuComponent { export class BookMenuComponent {
readonly books = input<readonly BookSummary[]>([]);
readonly openInNewTab = input(false, {transform: booleanAttribute});
readonly deleted = output<readonly number[]>();
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
private readonly appSettingsService = inject(AppSettingsService); private readonly appSettingsService = inject(AppSettingsService);
private readonly fileDownload = inject(FileDownloadService); private readonly fileDownload = inject(FileDownloadService);
@@ -119,6 +114,10 @@ export class BookMenuComponent {
private readonly confirmationService = inject(ConfirmationService); private readonly confirmationService = inject(ConfirmationService);
private readonly transloco = inject(TranslocoService); private readonly transloco = inject(TranslocoService);
private readonly router = inject(Router); private readonly router = inject(Router);
readonly books = input<readonly BookSummary[]>([]);
readonly openInNewTab = input(false, {transform: booleanAttribute});
readonly deleted = output<readonly number[]>();
private readonly rootMenu = viewChild.required(AppMenuComponent); private readonly rootMenu = viewChild.required(AppMenuComponent);
private readonly bookSnapshot = signal<BookSummary | null>(null); private readonly bookSnapshot = signal<BookSummary | null>(null);
@@ -16,8 +16,7 @@
(click)="openCreateDialog()" (click)="openCreateDialog()"
pTooltip="Add New Note" pTooltip="Add New Note"
tooltipPosition="top" tooltipPosition="top"
class="action-btn floating-btn"> class="action-btn floating-btn" />
</p-button>
</div> </div>
<p class="empty-state-title">No notes yet for this book</p> <p class="empty-state-title">No notes yet for this book</p>
<p class="empty-state-subtitle"> <p class="empty-state-subtitle">
@@ -55,8 +54,7 @@
(onClick)="openEditDialog(note)" (onClick)="openEditDialog(note)"
pTooltip="Edit note" pTooltip="Edit note"
tooltipPosition="top" tooltipPosition="top"
class="action-btn-hover"> class="action-btn-hover" />
</p-button>
<p-button <p-button
icon="pi pi-trash" icon="pi pi-trash"
size="small" size="small"
@@ -65,8 +63,7 @@
(onClick)="deleteNote(note)" (onClick)="deleteNote(note)"
pTooltip="Delete note" pTooltip="Delete note"
tooltipPosition="top" tooltipPosition="top"
class="action-btn-hover"> class="action-btn-hover" />
</p-button>
</div> </div>
</div> </div>
</div> </div>
@@ -91,8 +88,7 @@
severity="success" severity="success"
(click)="openCreateDialog()" (click)="openCreateDialog()"
pTooltip="Add New Note" pTooltip="Add New Note"
tooltipPosition="left"> tooltipPosition="left" />
</p-button>
</div> </div>
} }
@@ -136,15 +132,13 @@
label="Cancel" label="Cancel"
severity="secondary" severity="secondary"
outlined outlined
(onClick)="cancelCreate()"> (onClick)="cancelCreate()" />
</p-button>
<p-button <p-button
outlined outlined
severity="success" severity="success"
label="Save Note" label="Save Note"
icon="pi pi-save" icon="pi pi-save"
(onClick)="createNote()"> (onClick)="createNote()" />
</p-button>
</div> </div>
</ng-template> </ng-template>
</p-dialog> </p-dialog>
@@ -189,18 +183,16 @@
label="Cancel" label="Cancel"
severity="secondary" severity="secondary"
outlined outlined
(onClick)="cancelEdit()"> (onClick)="cancelEdit()" />
</p-button>
<p-button <p-button
outlined outlined
severity="success" severity="success"
label="Update Note" label="Update Note"
icon="pi pi-save" icon="pi pi-save"
(onClick)="updateNote()"> (onClick)="updateNote()" />
</p-button>
</div> </div>
</ng-template> </ng-template>
</p-dialog> </p-dialog>
<p-confirmDialog key="deleteNote"></p-confirmDialog> <p-confirmDialog key="deleteNote" />
</div> </div>
@@ -29,16 +29,15 @@ import {BookNote, BookNoteService, CreateBookNoteRequest} from '../../../../shar
styleUrl: './book-notes-component.scss' styleUrl: './book-notes-component.scss'
}) })
export class BookNotesComponent implements OnInit, OnChanges { export class BookNotesComponent implements OnInit, OnChanges {
private readonly bookNoteService = inject(BookNoteService);
private readonly confirmationService = inject(ConfirmationService);
private readonly messageService = inject(MessageService);
private readonly destroyRef = inject(DestroyRef);
private readonly t = inject(TranslocoService);
@Input() bookId!: number; @Input() bookId!: number;
private bookNoteService = inject(BookNoteService);
private confirmationService = inject(ConfirmationService);
private messageService = inject(MessageService);
private destroyRef = inject(DestroyRef);
private readonly t = inject(TranslocoService);
notes: BookNote[] = []; notes: BookNote[] = [];
loading = signal(false); readonly loading = signal(false);
showCreateDialog = false; showCreateDialog = false;
showEditDialog = false; showEditDialog = false;
selectedNote: BookNote | null = null; selectedNote: BookNote | null = null;
@@ -62,7 +61,7 @@ export class BookNotesComponent implements OnInit, OnChanges {
} }
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
if (changes['bookId'] && changes['bookId'].currentValue) { if (changes['bookId']?.currentValue) {
this.loadNotes(); this.loadNotes();
} }
} }
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs'; import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../../core/config/api-config'; import {API_CONFIG} from '../../../../core/config/api-config';
@@ -17,13 +17,11 @@ export interface BookReview {
textReviewsCount?: number; textReviewsCount?: number;
} }
@Injectable({ @Service()
providedIn: 'root',
})
export class BookReviewService { export class BookReviewService {
private readonly http = inject(HttpClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/reviews`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/reviews`;
private http = inject(HttpClient);
getByBookId(bookId: number): Observable<BookReview[]> { getByBookId(bookId: number): Observable<BookReview[]> {
return this.http.get<BookReview[]>(`${this.url}/book/${bookId}`); return this.http.get<BookReview[]>(`${this.url}/book/${bookId}`);
@@ -18,8 +18,7 @@
(click)="fetchNewReviews()" (click)="fetchNewReviews()"
[pTooltip]="t('tooltip.fetchReviews')" [pTooltip]="t('tooltip.fetchReviews')"
tooltipPosition="top" tooltipPosition="top"
class="action-btn floating-btn"> class="action-btn floating-btn" />
</p-button>
} }
</div> </div>
<p class="empty-state-title">{{ t('empty.noReviews') }}</p> <p class="empty-state-title">{{ t('empty.noReviews') }}</p>
@@ -25,27 +25,26 @@ import {MetadataCatalogService} from '../../../../shared/metadata/metadata-catal
styleUrl: './book-reviews.component.scss' styleUrl: './book-reviews.component.scss'
}) })
export class BookReviewsComponent implements OnInit, OnChanges { export class BookReviewsComponent implements OnInit, OnChanges {
private readonly reviewService = inject(BookReviewService);
private readonly bookMetadataManageService = inject(BookMetadataManageService);
private readonly confirmationService = inject(ConfirmationService);
private readonly messageService = inject(MessageService);
private readonly userService = inject(UserService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly destroyRef = inject(DestroyRef);
private readonly t = inject(TranslocoService);
protected readonly catalog = inject(MetadataCatalogService);
@Input() bookId!: number; @Input() bookId!: number;
@Input() reviews: BookReview[] | undefined = []; @Input() reviews: BookReview[] | undefined = [];
@Input() active: boolean = false; @Input() active: boolean = false;
@Input() reviewsLocked = false; @Input() reviewsLocked = false;
private reviewService = inject(BookReviewService);
private bookMetadataManageService = inject(BookMetadataManageService);
private confirmationService = inject(ConfirmationService);
private messageService = inject(MessageService);
private userService = inject(UserService);
private appSettingsService = inject(AppSettingsService);
private destroyRef = inject(DestroyRef);
private readonly t = inject(TranslocoService);
protected readonly catalog = inject(MetadataCatalogService);
private loadingBookId: number | null = null; private loadingBookId: number | null = null;
private loadingRequestSeq = 0; private loadingRequestSeq = 0;
private activeLoadingRequestSeq: number | null = null; private activeLoadingRequestSeq: number | null = null;
loading = signal(false); readonly loading = signal(false);
hasPermission = false; hasPermission = false;
revealedSpoilers = new Set<number>(); revealedSpoilers = new Set<number>();
sortAscending = false; sortAscending = false;
@@ -58,7 +57,7 @@ export class BookReviewsComponent implements OnInit, OnChanges {
} }
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
if (changes['bookId'] && changes['bookId'].currentValue) { if (changes['bookId']?.currentValue) {
this.loadReviews(); this.loadReviews();
} }
} }
@@ -320,7 +319,7 @@ export class BookReviewsComponent implements OnInit, OnChanges {
} }
private updateSpoilerState(): void { private updateSpoilerState(): void {
const spoilerReviews = this.reviews?.filter(r => r.spoiler) || []; const spoilerReviews = this.reviews?.filter(r => r.spoiler) ?? [];
const revealedSpoilerReviews = spoilerReviews.filter(r => r.id && this.revealedSpoilers.has(r.id)); const revealedSpoilerReviews = spoilerReviews.filter(r => r.id && this.revealedSpoilers.has(r.id));
this.allSpoilersRevealed = spoilerReviews.length > 0 && spoilerReviews.length === revealedSpoilerReviews.length; this.allSpoilersRevealed = spoilerReviews.length > 0 && spoilerReviews.length === revealedSpoilerReviews.length;
} }
@@ -14,8 +14,7 @@
[text]="true" [text]="true"
severity="secondary" severity="secondary"
(click)="dynamicDialogRef.close()" (click)="dynamicDialogRef.close()"
class="close-button"> class="close-button" />
</p-button>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
@@ -29,8 +28,7 @@
[placeholder]="t('selectProvider')" [placeholder]="t('selectProvider')"
[(ngModel)]="selectedProvider" [(ngModel)]="selectedProvider"
appendTo="body" appendTo="body"
class="full-width"> class="full-width" />
</p-select>
</div> </div>
<div class="form-field"> <div class="form-field">
@@ -43,8 +41,7 @@
[(ngModel)]="selectedRecipient" [(ngModel)]="selectedRecipient"
[disabled]="!selectedProvider" [disabled]="!selectedProvider"
appendTo="body" appendTo="body"
class="full-width"> class="full-width" />
</p-select>
</div> </div>
@if (emailableFiles.length > 0) { @if (emailableFiles.length > 0) {
@@ -79,8 +76,7 @@
icon="pi pi-envelope" icon="pi pi-envelope"
[label]="t('sendBook')" [label]="t('sendBook')"
[disabled]="!selectedProvider || !selectedRecipient" [disabled]="!selectedProvider || !selectedRecipient"
(onClick)="sendBook()"> (onClick)="sendBook()" />
</p-button>
</div> </div>
</div> </div>
</ng-container> </ng-container>
@@ -41,13 +41,13 @@ const LARGE_FILE_THRESHOLD_KB = 25 * 1024; // 25MB
}) })
export class BookSenderComponent implements OnInit { export class BookSenderComponent implements OnInit {
private emailProviderService = inject(EmailV2ProviderService); private readonly emailProviderService = inject(EmailV2ProviderService);
private emailRecipientService = inject(EmailV2RecipientService); private readonly emailRecipientService = inject(EmailV2RecipientService);
private emailService = inject(EmailService); private readonly emailService = inject(EmailService);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
dynamicDialogRef = inject(DynamicDialogRef); dynamicDialogRef = inject(DynamicDialogRef);
private dynamicDialogConfig = inject(DynamicDialogConfig); private readonly dynamicDialogConfig = inject(DynamicDialogConfig);
book: BookSenderSource = this.dynamicDialogConfig.data.book; book: BookSenderSource = this.dynamicDialogConfig.data.book;
@@ -217,6 +217,7 @@
@case ('created') { <i class="pi pi-check-circle"></i> } @case ('created') { <i class="pi pi-check-circle"></i> }
@case ('created-no-metadata') { <i class="pi pi-exclamation-triangle"></i> } @case ('created-no-metadata') { <i class="pi pi-exclamation-triangle"></i> }
@case ('failed') { <i class="pi pi-times-circle"></i> } @case ('failed') { <i class="pi pi-times-circle"></i> }
@default never;
} }
</div> </div>
<code class="progress-item-isbn">{{ entry.isbn }}</code> <code class="progress-item-isbn">{{ entry.isbn }}</code>
@@ -60,29 +60,29 @@ type ImportPhase = 'upload' | 'processing' | 'summary';
styleUrl: './bulk-isbn-import-dialog.component.scss', styleUrl: './bulk-isbn-import-dialog.component.scss',
}) })
export class BulkIsbnImportDialogComponent { export class BulkIsbnImportDialogComponent {
private dynamicDialogRef = inject(DynamicDialogRef); private readonly dynamicDialogRef = inject(DynamicDialogRef);
private dialogConfig = inject(DynamicDialogConfig); private readonly dialogConfig = inject(DynamicDialogConfig);
private bookService = inject(BookService); private readonly bookService = inject(BookService);
private queryClient = inject(QueryClient); private readonly queryClient = inject(QueryClient);
private sources = inject(MetadataSourceQueryService); private readonly sources = inject(MetadataSourceQueryService);
private libraryService = inject(LibraryService); private readonly libraryService = inject(LibraryService);
selectedLibraryId: number | null = null; selectedLibraryId: number | null = null;
phase: WritableSignal<ImportPhase> = signal('upload'); readonly phase: WritableSignal<ImportPhase> = signal('upload');
pasteText = ''; pasteText = '';
entries: WritableSignal<IsbnEntry[]> = signal([]); readonly entries: WritableSignal<IsbnEntry[]> = signal([]);
skipped: WritableSignal<SkippedEntry[]> = signal([]); readonly skipped: WritableSignal<SkippedEntry[]> = signal([]);
duplicatesRemoved = signal(0); readonly duplicatesRemoved = signal(0);
showSkipped = false; showSkipped = false;
processedCount = signal(0); readonly processedCount = signal(0);
createdCount = signal(0); readonly createdCount = signal(0);
noMetadataCount = signal(0); readonly noMetadataCount = signal(0);
failedCount = signal(0); readonly failedCount = signal(0);
cancelled = false; cancelled = false;
parseError = signal(''); readonly parseError = signal('');
readonly maxIsbnCount = MAX_ISBN_COUNT; readonly maxIsbnCount = MAX_ISBN_COUNT;
private readonly initializeSelectedLibraryEffect = effect(() => { private readonly initializeSelectedLibraryEffect = effect(() => {
const libraries = this.libraries; const libraries = this.libraries;
@@ -218,7 +218,7 @@ export class BulkIsbnImportDialogComponent {
this.dynamicDialogRef.close(); this.dynamicDialogRef.close();
} }
progressPercent = computed( readonly progressPercent = computed(
() => this.entries().length > 0 ? Math.round((this.processedCount() / this.entries().length) * 100) : 0 () => this.entries().length > 0 ? Math.round((this.processedCount() / this.entries().length) * 100) : 0
); );
@@ -70,6 +70,11 @@ export function bookCardCoverSrc(
templateUrl: './book-card.component.html', templateUrl: './book-card.component.html',
}) })
export class BookCardComponent { export class BookCardComponent {
private readonly urlHelper = inject(UrlHelperService);
private readonly transloco = inject(TranslocoService);
private readonly router = inject(Router);
private readonly locationStrategy = inject(LocationStrategy);
private readonly destroyRef = inject(DestroyRef);
readonly book = input.required<BookSummary>(); readonly book = input.required<BookSummary>();
readonly squareCovers = input(false, {transform: booleanAttribute}); readonly squareCovers = input(false, {transform: booleanAttribute});
readonly showBadge = input(true, {transform: booleanAttribute}); readonly showBadge = input(true, {transform: booleanAttribute});
@@ -89,12 +94,6 @@ export class BookCardComponent {
readonly action = output<void>(); readonly action = output<void>();
readonly menuRequested = output<ContextMenuRequest>(); readonly menuRequested = output<ContextMenuRequest>();
readonly detailRequested = output<void>(); readonly detailRequested = output<void>();
private readonly urlHelper = inject(UrlHelperService);
private readonly transloco = inject(TranslocoService);
private readonly router = inject(Router);
private readonly locationStrategy = inject(LocationStrategy);
private readonly destroyRef = inject(DestroyRef);
private readonly activeLang = toSignal(this.transloco.langChanges$, { private readonly activeLang = toSignal(this.transloco.langChanges$, {
initialValue: this.transloco.getActiveLang(), initialValue: this.transloco.getActiveLang(),
}); });
@@ -14,8 +14,7 @@
[text]="true" [text]="true"
severity="secondary" severity="secondary"
(click)="closeDialog()" (click)="closeDialog()"
class="close-button"> class="close-button" />
</p-button>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
@@ -27,13 +26,12 @@
(onChange)="onPresetChange()" (onChange)="onPresetChange()"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
[disabled]="isScanning() || isMerging()"> [disabled]="isScanning() || isMerging()" />
</p-selectButton>
</div> </div>
<!-- Advanced Toggles --> <!-- Advanced Toggles -->
<div class="advanced-section"> <div class="advanced-section">
<button class="advanced-toggle" (click)="showAdvanced = !showAdvanced"> <button type="button" class="advanced-toggle" (click)="showAdvanced = !showAdvanced">
<i class="pi" [class.pi-chevron-right]="!showAdvanced" [class.pi-chevron-down]="showAdvanced"></i> <i class="pi" [class.pi-chevron-right]="!showAdvanced" [class.pi-chevron-down]="showAdvanced"></i>
{{ t('advanced') }} {{ t('advanced') }}
</button> </button>
@@ -41,23 +39,23 @@
@if (showAdvanced) { @if (showAdvanced) {
<div class="signal-checkboxes"> <div class="signal-checkboxes">
<div class="signal-checkbox"> <div class="signal-checkbox">
<p-checkbox [(ngModel)]="matchByIsbn" [binary]="true" inputId="isbn" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()"></p-checkbox> <p-checkbox [(ngModel)]="matchByIsbn" [binary]="true" inputId="isbn" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()" />
<label for="isbn">{{ t('signalIsbn') }}</label> <label for="isbn">{{ t('signalIsbn') }}</label>
</div> </div>
<div class="signal-checkbox"> <div class="signal-checkbox">
<p-checkbox [(ngModel)]="matchByExternalId" [binary]="true" inputId="externalId" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()"></p-checkbox> <p-checkbox [(ngModel)]="matchByExternalId" [binary]="true" inputId="externalId" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()" />
<label for="externalId">{{ t('signalExternalId') }}</label> <label for="externalId">{{ t('signalExternalId') }}</label>
</div> </div>
<div class="signal-checkbox"> <div class="signal-checkbox">
<p-checkbox [(ngModel)]="matchByTitleAuthor" [binary]="true" inputId="titleAuthor" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()"></p-checkbox> <p-checkbox [(ngModel)]="matchByTitleAuthor" [binary]="true" inputId="titleAuthor" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()" />
<label for="titleAuthor">{{ t('signalTitleAuthor') }}</label> <label for="titleAuthor">{{ t('signalTitleAuthor') }}</label>
</div> </div>
<div class="signal-checkbox"> <div class="signal-checkbox">
<p-checkbox [(ngModel)]="matchByDirectory" [binary]="true" inputId="directory" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()"></p-checkbox> <p-checkbox [(ngModel)]="matchByDirectory" [binary]="true" inputId="directory" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()" />
<label for="directory">{{ t('signalDirectory') }}</label> <label for="directory">{{ t('signalDirectory') }}</label>
</div> </div>
<div class="signal-checkbox"> <div class="signal-checkbox">
<p-checkbox [(ngModel)]="matchByFilename" [binary]="true" inputId="filename" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()"></p-checkbox> <p-checkbox [(ngModel)]="matchByFilename" [binary]="true" inputId="filename" (onChange)="onSignalToggle()" [disabled]="isScanning() || isMerging()" />
<label for="filename">{{ t('signalFilename') }}</label> <label for="filename">{{ t('signalFilename') }}</label>
</div> </div>
</div> </div>
@@ -72,8 +70,7 @@
icon="pi pi-search" icon="pi pi-search"
(click)="scan()" (click)="scan()"
[disabled]="!canScan" [disabled]="!canScan"
[loading]="isScanning()"> [loading]="isScanning()" />
</p-button>
</div> </div>
<div class="action-bar-right"> <div class="action-bar-right">
<div class="delete-option"> <div class="delete-option">
@@ -81,8 +78,7 @@
[(ngModel)]="moveFiles" [(ngModel)]="moveFiles"
[binary]="true" [binary]="true"
inputId="moveFiles" inputId="moveFiles"
[disabled]="isMerging()"> [disabled]="isMerging()" />
</p-checkbox>
<label for="moveFiles">{{ 'book.fileAttacher.moveFilesLabel' | transloco }}</label> <label for="moveFiles">{{ 'book.fileAttacher.moveFilesLabel' | transloco }}</label>
</div> </div>
@if (activeGroups.length > 0) { @if (activeGroups.length > 0) {
@@ -92,15 +88,14 @@
severity="success" severity="success"
(click)="mergeAll()" (click)="mergeAll()"
[disabled]="isMerging()" [disabled]="isMerging()"
[loading]="isMerging()"> [loading]="isMerging()" />
</p-button>
} }
</div> </div>
</div> </div>
<!-- Merge Progress --> <!-- Merge Progress -->
@if (isMerging()) { @if (isMerging()) {
<p-progressBar [value]="mergeTotal() > 0 ? (mergeProgress() / mergeTotal()) * 100 : 0" [showValue]="false"></p-progressBar> <p-progressBar [value]="mergeTotal() > 0 ? (mergeProgress() / mergeTotal()) * 100 : 0" [showValue]="false" />
} }
<!-- Help Text --> <!-- Help Text -->
@@ -139,9 +134,9 @@
<div class="duplicate-group"> <div class="duplicate-group">
<div class="group-header"> <div class="group-header">
<span class="group-label">{{ t('groupLabel', { index: pageFirst + $index + 1 }) }}</span> <span class="group-label">{{ t('groupLabel', { index: pageFirst + $index + 1 }) }}</span>
<p-tag [value]="getMatchReasonLabel(group.matchReason)" [severity]="getMatchReasonSeverity(group.matchReason)"></p-tag> <p-tag [value]="getMatchReasonLabel(group.matchReason)" [severity]="getMatchReasonSeverity(group.matchReason)" />
@if (hasSameFormatConflict(group)) { @if (hasSameFormatConflict(group)) {
<p-tag [value]="t('sameFormatWarning')" severity="warn" icon="pi pi-exclamation-triangle"></p-tag> <p-tag [value]="t('sameFormatWarning')" severity="warn" icon="pi pi-exclamation-triangle" />
} }
<div class="group-actions"> <div class="group-actions">
<p-button <p-button
@@ -150,8 +145,7 @@
size="small" size="small"
severity="success" severity="success"
(click)="mergeGroup(group)" (click)="mergeGroup(group)"
[disabled]="isMerging()"> [disabled]="isMerging()" />
</p-button>
@if (getDeleteSelectedCount(group) > 0) { @if (getDeleteSelectedCount(group) > 0) {
<p-button <p-button
[label]="t('deleteSelected', { count: getDeleteSelectedCount(group) })" [label]="t('deleteSelected', { count: getDeleteSelectedCount(group) })"
@@ -160,8 +154,7 @@
severity="danger" severity="danger"
[outlined]="true" [outlined]="true"
(click)="deleteGroup(group)" (click)="deleteGroup(group)"
[disabled]="isMerging()"> [disabled]="isMerging()" />
</p-button>
} }
<p-button <p-button
[label]="t('dismiss')" [label]="t('dismiss')"
@@ -170,8 +163,7 @@
severity="secondary" severity="secondary"
[outlined]="true" [outlined]="true"
(click)="dismissGroup(group)" (click)="dismissGroup(group)"
[disabled]="isMerging()"> [disabled]="isMerging()" />
</p-button>
</div> </div>
</div> </div>
<div class="group-books"> <div class="group-books">
@@ -183,8 +175,7 @@
[ngModel]="group.selectedForDeletion.has(book.id)" [ngModel]="group.selectedForDeletion.has(book.id)"
(onChange)="toggleDeleteSelection(group, book.id)" (onChange)="toggleDeleteSelection(group, book.id)"
[disabled]="isMerging()" [disabled]="isMerging()"
class="delete-checkbox"> class="delete-checkbox" />
</p-checkbox>
} }
<app-cover class="book-cover" <app-cover class="book-cover"
aria-hidden="true" aria-hidden="true"
@@ -222,8 +213,7 @@
[value]="book.id" [value]="book.id"
[(ngModel)]="group.selectedTargetBookId" [(ngModel)]="group.selectedTargetBookId"
(onClick)="onTargetChange(group)" (onClick)="onTargetChange(group)"
[disabled]="isMerging()"> [disabled]="isMerging()" />
</p-radioButton>
@if (book.id === group.selectedTargetBookId) { @if (book.id === group.selectedTargetBookId) {
<span class="target-label">{{ t('target') }}</span> <span class="target-label">{{ t('target') }}</span>
} }
@@ -241,8 +231,7 @@
[totalRecords]="activeGroups.length" [totalRecords]="activeGroups.length"
[first]="pageFirst" [first]="pageFirst"
(onPageChange)="onPageChange($event)" (onPageChange)="onPageChange($event)"
[rowsPerPageOptions]="[10, 20, 50]"> [rowsPerPageOptions]="[10, 20, 50]" />
</p-paginator>
} }
} }
</div> </div>
@@ -8,7 +8,7 @@ import {SelectButton} from '@openng/optimus-ui/selectbutton';
import {ProgressBar} from '@openng/optimus-ui/progressbar'; import {ProgressBar} from '@openng/optimus-ui/progressbar';
import {Tag} from '@openng/optimus-ui/tag'; import {Tag} from '@openng/optimus-ui/tag';
import {Paginator, PaginatorState} from '@openng/optimus-ui/paginator'; import {Paginator, PaginatorState} from '@openng/optimus-ui/paginator';
import {Subject, takeUntil} from 'rxjs'; import {lastValueFrom, Subject, takeUntil} from 'rxjs';
import {BookFileService} from '../../service/book-file.service'; import {BookFileService} from '../../service/book-file.service';
import {BookService} from '../../service/book.service'; import {BookService} from '../../service/book.service';
import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model'; import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model';
@@ -46,30 +46,6 @@ interface DisplayGroup extends DuplicateGroup {
styleUrls: ['./duplicate-merger.component.scss'] styleUrls: ['./duplicate-merger.component.scss']
}) })
export class DuplicateMergerComponent implements OnInit, OnDestroy { export class DuplicateMergerComponent implements OnInit, OnDestroy {
libraryId!: number;
presetMode: PresetMode = 'balanced';
showAdvanced = false;
matchByIsbn = true;
matchByExternalId = true;
matchByTitleAuthor = true;
matchByDirectory = false;
matchByFilename = false;
isScanning = signal(false);
isMerging = signal(false);
hasScanned = signal(false);
moveFiles = false;
mergeProgress = signal(0);
mergeTotal = signal(0);
groups: DisplayGroup[] = [];
presetOptions: { label: string; value: PresetMode }[] = [];
pageFirst = 0;
pageSize = 20;
private destroy$ = new Subject<void>();
private readonly bookFileService = inject(BookFileService); private readonly bookFileService = inject(BookFileService);
private readonly bookService = inject(BookService); private readonly bookService = inject(BookService);
private readonly messageService = inject(MessageService); private readonly messageService = inject(MessageService);
@@ -80,6 +56,30 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
readonly urlHelper = inject(UrlHelperService); readonly urlHelper = inject(UrlHelperService);
private readonly appSettingsService = inject(AppSettingsService); private readonly appSettingsService = inject(AppSettingsService);
private readonly changeDetectorRef = inject(ChangeDetectorRef); private readonly changeDetectorRef = inject(ChangeDetectorRef);
libraryId!: number;
presetMode: PresetMode = 'balanced';
showAdvanced = false;
matchByIsbn = true;
matchByExternalId = true;
matchByTitleAuthor = true;
matchByDirectory = false;
matchByFilename = false;
readonly isScanning = signal(false);
readonly isMerging = signal(false);
readonly hasScanned = signal(false);
moveFiles = false;
readonly mergeProgress = signal(0);
readonly mergeTotal = signal(0);
groups: DisplayGroup[] = [];
presetOptions: { label: string; value: PresetMode }[] = [];
pageFirst = 0;
pageSize = 20;
private readonly destroy$ = new Subject<void>();
ngOnInit(): void { ngOnInit(): void {
this.libraryId = this.config.data.libraryId; this.libraryId = this.config.data.libraryId;
@@ -298,9 +298,8 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
group.dismissed = true; group.dismissed = true;
try { try {
await this.bookFileService.attachBookFiles(targetId, sourceIds, this.moveFiles) await lastValueFrom(this.bookFileService.attachBookFiles(targetId, sourceIds, this.moveFiles)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$)), {defaultValue: undefined});
.toPromise();
} catch { } catch {
group.dismissed = false; group.dismissed = false;
this.messageService.add({ this.messageService.add({
@@ -335,9 +334,8 @@ export class DuplicateMergerComponent implements OnInit, OnDestroy {
} }
try { try {
await this.bookFileService.attachBookFiles(targetId, sourceIds, this.moveFiles) await lastValueFrom(this.bookFileService.attachBookFiles(targetId, sourceIds, this.moveFiles)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$)), {defaultValue: undefined});
.toPromise();
group.dismissed = true; group.dismissed = true;
successCount++; successCount++;
} catch { } catch {
@@ -1,13 +1,11 @@
import {effect, inject, Injectable, signal} from '@angular/core'; import {effect, inject, Service, signal} from '@angular/core';
import {EntityViewPreference, UserService} from '../../../settings/user-management/user.service'; import {EntityViewPreference, UserService} from '../../../settings/user-management/user.service';
interface LegacyOverlayPreference extends Partial<EntityViewPreference> { interface LegacyOverlayPreference extends Partial<EntityViewPreference> {
showBookTypePill?: boolean; showBookTypePill?: boolean;
} }
@Injectable({ @Service()
providedIn: 'root'
})
export class BookCardOverlayPreferenceService { export class BookCardOverlayPreferenceService {
private static readonly PERSIST_DELAY_MS = 500; private static readonly PERSIST_DELAY_MS = 500;
@@ -16,7 +14,7 @@ export class BookCardOverlayPreferenceService {
private readonly _showBookTypePill = signal(true); private readonly _showBookTypePill = signal(true);
readonly showBookTypePill = this._showBookTypePill.asReadonly(); readonly showBookTypePill = this._showBookTypePill.asReadonly();
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null; private readonly currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
private persistTimeout: ReturnType<typeof setTimeout> | null = null; private persistTimeout: ReturnType<typeof setTimeout> | null = null;
constructor() { constructor() {
@@ -90,9 +88,7 @@ export class BookCardOverlayPreferenceService {
overrides: [] overrides: []
}); });
if (!prefs.overrides) { prefs.overrides ??= [];
prefs.overrides = [];
}
if (this.currentContext) { if (this.currentContext) {
let override = prefs.overrides.find(o => let override = prefs.overrides.find(o =>
@@ -5,7 +5,7 @@
(click)="onCardClick($event)" (click)="onCardClick($event)"
(keydown.enter)="onCardClick($event)"> (keydown.enter)="onCardClick($event)">
<div class="cover-container" [ngClass]="{ 'center-info-btn': isSeriesViewActive() || !hasDigitalFile(), 'audiobook-cover': isAudiobook(), 'square-library-cover': useSquareCovers() }"> <div class="cover-container" [class]="{ 'center-info-btn': isSeriesViewActive() || !hasDigitalFile(), 'audiobook-cover': isAudiobook(), 'square-library-cover': useSquareCovers() }">
<app-cover <app-cover
class="book-cover" class="book-cover"
[class.square-cover]="isAudiobook() || useSquareCovers()" [class.square-cover]="isAudiobook() || useSquareCovers()"
@@ -17,7 +17,7 @@
<div class="top-left-overlay-stack"> <div class="top-left-overlay-stack">
@if (showBookTypePill() && displayFormat(); as fmt) { @if (showBookTypePill() && displayFormat(); as fmt) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + fmt.toLowerCase()"> <div class="book-type-pill-overlay" [class]="'book-type-' + fmt.toLowerCase()">
{{ fmt }} {{ fmt }}
</div> </div>
} }
@@ -59,24 +59,23 @@
class="select-checkbox" class="select-checkbox"
(click)="captureMouseEvent($event)" (click)="captureMouseEvent($event)"
[ngModel]="isSelected()" [ngModel]="isSelected()"
(onChange)="toggleSelection($event)"> (onChange)="toggleSelection($event)" />
</p-checkbox>
} }
@if (hasProgress()) { @if (hasProgress()) {
<div class="cover-progress-bar-container" [pTooltip]="progressTooltip()" tooltipPosition="top"> <div class="cover-progress-bar-container" [pTooltip]="progressTooltip()" tooltipPosition="top">
@if (progressPercentage() !== null) { @if (progressPercentage() !== null) {
<div class="cover-progress-bar" [ngClass]="{ 'progress-complete': progressPercentage() === 100, 'progress-incomplete': progressPercentage()! < 100 }"> <div class="cover-progress-bar" [class]="{ 'progress-complete': progressPercentage() === 100, 'progress-incomplete': progressPercentage()! < 100 }">
<div class="progress-fill" [style.width.%]="progressPercentage()!"></div> <div class="progress-fill" [style.width.%]="progressPercentage()!"></div>
</div> </div>
} }
@if (koProgressPercentage() !== null) { @if (koProgressPercentage() !== null) {
<div class="cover-progress-bar" [ngClass]="koProgressPercentage() === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'"> <div class="cover-progress-bar" [class]="koProgressPercentage() === 100 ? 'progress-complete-ko' : 'progress-incomplete-ko'">
<div class="progress-fill" [style.width.%]="koProgressPercentage()!"></div> <div class="progress-fill" [style.width.%]="koProgressPercentage()!"></div>
</div> </div>
} }
@if (koboProgressPercentage() !== null) { @if (koboProgressPercentage() !== null) {
<div class="cover-progress-bar" [ngClass]="koboProgressPercentage() === 100 ? 'progress-complete-kobo' : 'progress-incomplete-kobo'"> <div class="cover-progress-bar" [class]="koboProgressPercentage() === 100 ? 'progress-complete-kobo' : 'progress-incomplete-kobo'">
<div class="progress-fill" [style.width.%]="koboProgressPercentage()!"></div> <div class="progress-fill" [style.width.%]="koboProgressPercentage()!"></div>
</div> </div>
} }
@@ -87,7 +86,7 @@
@if (!bottomBarHidden()) { @if (!bottomBarHidden()) {
<div class="book-title-container"> <div class="book-title-container">
<div class="read-status-indicator" <div class="read-status-indicator"
[ngClass]="readStatusClass()" [class]="readStatusClass()"
[pTooltip]="readStatusTooltip()" [pTooltip]="readStatusTooltip()"
tooltipPosition="bottom" tooltipPosition="bottom"
(click)="toggleReadStatusMenu($event, readStatusMenu)" (click)="toggleReadStatusMenu($event, readStatusMenu)"
@@ -97,13 +96,13 @@
[attr.aria-label]="'book.card.alt.readStatusMenu' | transloco"> [attr.aria-label]="'book.card.alt.readStatusMenu' | transloco">
<i [class]="readStatusIcon()" style="font-size: 0.9rem"></i> <i [class]="readStatusIcon()" style="font-size: 0.9rem"></i>
</div> </div>
<p-tieredmenu #readStatusMenu [model]="readStatusMenuItems()" [popup]="true" appendTo="body"></p-tieredmenu> <p-tieredmenu #readStatusMenu [model]="readStatusMenuItems()" [popup]="true" appendTo="body" />
<h4 class="book-title" <h4 class="book-title"
tooltipPosition="bottom" tooltipPosition="bottom"
[pTooltip]="titleTooltip()"> [pTooltip]="titleTooltip()">
{{ displayTitle() }} {{ displayTitle() }}
</h4> </h4>
<p-tieredmenu #menu [model]="items()" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu> <p-tieredmenu #menu [model]="items()" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()" />
<button pButton type="button" <button pButton type="button"
class="p-button p-component p-button-text p-button-sm custom-button-padding" class="p-button p-component p-button-text p-button-sm custom-button-padding"
(click)="onMenuToggle($event, menu)" (click)="onMenuToggle($event, menu)"
@@ -148,7 +148,7 @@ describe('LegacyBookCardComponent', () => {
appSettings: ReturnType<typeof vi.fn>; appSettings: ReturnType<typeof vi.fn>;
}; };
let queryClient: { let queryClient: {
fetchQuery: ReturnType<typeof vi.fn>; query: ReturnType<typeof vi.fn>;
}; };
beforeEach(() => { beforeEach(() => {
@@ -204,7 +204,7 @@ describe('LegacyBookCardComponent', () => {
appSettings: vi.fn(() => ({diskType: 'LOCAL'})), appSettings: vi.fn(() => ({diskType: 'LOCAL'})),
}; };
queryClient = { queryClient = {
fetchQuery: vi.fn(), query: vi.fn(),
}; };
TestBed.configureTestingModule({ TestBed.configureTestingModule({
@@ -10,7 +10,6 @@ import {FormsModule} from '@angular/forms';
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum'; import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
import {UrlHelperService} from '../../../../shared/service/url-helper.service'; import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverComponent} from '../../../../shared/components/cover/cover.component'; import {CoverComponent} from '../../../../shared/components/cover/cover.component';
import {NgClass} from '@angular/common';
import {UserService} from '../../../settings/user-management/user.service'; import {UserService} from '../../../settings/user-management/user.service';
import {EmailService} from '../../../settings/email-v2/email.service'; import {EmailService} from '../../../settings/email-v2/email.service';
import {TieredMenu} from '@openng/optimus-ui/tieredmenu'; import {TieredMenu} from '@openng/optimus-ui/tieredmenu';
@@ -31,11 +30,28 @@ import {ButtonDirective} from '@openng/optimus-ui/button';
selector: 'app-legacy-book-card', selector: 'app-legacy-book-card',
templateUrl: './legacy-book-card.component.html', templateUrl: './legacy-book-card.component.html',
styleUrls: ['./legacy-book-card.component.scss'], styleUrls: ['./legacy-book-card.component.scss'],
imports: [ButtonDirective, Checkbox, FormsModule, NgClass, TieredMenu, Tooltip, RouterLink, TranslocoPipe, CoverComponent], imports: [ButtonDirective, Checkbox, FormsModule, TieredMenu, Tooltip, RouterLink, TranslocoPipe, CoverComponent],
standalone: true, standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class LegacyBookCardComponent { export class LegacyBookCardComponent {
private readonly overlayService = inject(BookCardOverlayPreferenceService);
private readonly bookService = inject(BookService);
private readonly bookFileService = inject(BookFileService);
private readonly bookMetadataManageService = inject(BookMetadataManageService);
private readonly taskHelperService = inject(TaskHelperService);
private readonly userService = inject(UserService);
private readonly emailService = inject(EmailService);
private readonly messageService = inject(MessageService);
private readonly router = inject(Router);
private readonly urlHelper = inject(UrlHelperService);
private readonly confirmationService = inject(ConfirmationService);
private readonly bookDialogHelperService = inject(BookDialogHelperService);
private readonly bookNavigationService = inject(BookNavigationService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
private readonly queryClient = inject(QueryClient);
protected readStatusHelper = inject(ReadStatusHelper);
// --- Inputs --- // --- Inputs ---
readonly book = input.required<Book>(); readonly book = input.required<Book>();
@@ -47,7 +63,6 @@ export class LegacyBookCardComponent {
readonly seriesViewEnabled = input(false); readonly seriesViewEnabled = input(false);
readonly isSeriesCollapsed = input(false); readonly isSeriesCollapsed = input(false);
readonly overlayPreferenceService = input<BookCardOverlayPreferenceService | undefined>(); readonly overlayPreferenceService = input<BookCardOverlayPreferenceService | undefined>();
private readonly overlayService = inject(BookCardOverlayPreferenceService);
readonly showBookTypePill = computed(() => (this.overlayPreferenceService() ?? this.overlayService).showBookTypePill()); readonly showBookTypePill = computed(() => (this.overlayPreferenceService() ?? this.overlayService).showBookTypePill());
readonly forceEbookMode = input(false); readonly forceEbookMode = input(false);
readonly useSquareCovers = input(false); readonly useSquareCovers = input(false);
@@ -63,25 +78,8 @@ export class LegacyBookCardComponent {
private menuBookId: number | undefined; private menuBookId: number | undefined;
private menuInitialized = false; private menuInitialized = false;
private bookService = inject(BookService);
private bookFileService = inject(BookFileService);
private bookMetadataManageService = inject(BookMetadataManageService);
private taskHelperService = inject(TaskHelperService);
private userService = inject(UserService);
private emailService = inject(EmailService);
private messageService = inject(MessageService);
private router = inject(Router);
private urlHelper = inject(UrlHelperService);
private confirmationService = inject(ConfirmationService);
private bookDialogHelperService = inject(BookDialogHelperService);
private bookNavigationService = inject(BookNavigationService);
private appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
private queryClient = inject(QueryClient);
protected readStatusHelper = inject(ReadStatusHelper);
private readonly currentUser = computed(() => this.userService.currentUser()); private readonly currentUser = computed(() => this.userService.currentUser());
private readonly metadataCenterViewMode = computed(() => this.currentUser()?.userSettings?.metadataCenterViewMode ?? 'route' as 'route' | 'dialog'); private readonly metadataCenterViewMode = computed(() => this.currentUser()?.userSettings?.metadataCenterViewMode ?? 'route');
private readonly diskType = computed(() => this.appSettingsService.appSettings()?.diskType ?? 'LOCAL'); private readonly diskType = computed(() => this.appSettingsService.appSettings()?.diskType ?? 'LOCAL');
@@ -257,7 +255,7 @@ export class LegacyBookCardComponent {
if (!this.additionalFilesLoaded() && !this.isSubMenuLoading() && this.needsAdditionalFilesData()) { if (!this.additionalFilesLoaded() && !this.isSubMenuLoading() && this.needsAdditionalFilesData()) {
this.isSubMenuLoading.set(true); this.isSubMenuLoading.set(true);
const requestedBookId = currentBookId; const requestedBookId = currentBookId;
void this.queryClient.fetchQuery(this.bookService.bookDetailQueryOptions(requestedBookId, true)) void this.queryClient.query(this.bookService.bookDetailQueryOptions(requestedBookId, true))
.then((fetchedBook) => { .then((fetchedBook) => {
if (this.book().id !== requestedBookId) return; if (this.book().id !== requestedBookId) return;
this.additionalFilesLoaded.set(true); this.additionalFilesLoaded.set(true);
@@ -629,7 +627,7 @@ export class LegacyBookCardComponent {
const items: MenuItem[] = []; const items: MenuItem[] = [];
items.push({ items.push({
label: `${b.fileName || 'Book File'}`, label: b.fileName || 'Book File',
icon: 'pi pi-file', icon: 'pi pi-file',
command: () => this.bookFileService.downloadFile(this.book()) command: () => this.bookFileService.downloadFile(this.book())
}); });
@@ -128,10 +128,9 @@ export function libraryShelfMenuAvailable(
`, `,
}) })
export class LibraryShelfMenuItemsComponent { export class LibraryShelfMenuItemsComponent {
readonly target = input.required<LibraryShelfMenuTarget>();
private readonly currentUser = inject(UserService).currentUser; private readonly currentUser = inject(UserService).currentUser;
protected readonly actions = inject(LibraryShelfMenuService); protected readonly actions = inject(LibraryShelfMenuService);
readonly target = input.required<LibraryShelfMenuTarget>();
protected readonly canManageShelf = computed(() => { protected readonly canManageShelf = computed(() => {
const target = this.target(); const target = this.target();
@@ -26,6 +26,7 @@ import {libraryShelfMenuAvailable, LibraryShelfMenuItemsComponent} from './libra
`, `,
}) })
export class LibraryShelfMenuComponent { export class LibraryShelfMenuComponent {
private readonly currentUser = inject(UserService).currentUser;
readonly target = input.required<LibraryShelfMenuTarget>(); readonly target = input.required<LibraryShelfMenuTarget>();
readonly ariaLabel = input.required<string>(); readonly ariaLabel = input.required<string>();
@@ -33,8 +34,6 @@ export class LibraryShelfMenuComponent {
readonly closed = output<void>(); readonly closed = output<void>();
readonly menu = viewChild.required(AppMenuComponent); readonly menu = viewChild.required(AppMenuComponent);
private readonly currentUser = inject(UserService).currentUser;
readonly available = computed( readonly available = computed(
() => libraryShelfMenuAvailable(this.target(), this.currentUser()), () => libraryShelfMenuAvailable(this.target(), this.currentUser()),
); );
@@ -14,8 +14,7 @@
[text]="true" [text]="true"
severity="secondary" severity="secondary"
(click)="dialogRef.close()" (click)="dialogRef.close()"
class="close-button"> class="close-button" />
</p-button>
</div> </div>
<div class="dialog-content"> <div class="dialog-content">
@@ -29,7 +28,7 @@
[icon]="getLockIcon(field)" [icon]="getLockIcon(field)"
[severity]="fieldLocks[field] === true ? 'danger' : fieldLocks[field] === false ? 'success' : 'secondary'" [severity]="fieldLocks[field] === true ? 'danger' : fieldLocks[field] === false ? 'success' : 'secondary'"
(click)="cycleLockState(field)" (click)="cycleLockState(field)"
></p-button> />
</div> </div>
} }
</div> </div>
@@ -37,13 +36,13 @@
<div class="dialog-footer"> <div class="dialog-footer">
<div class="footer-actions"> <div class="footer-actions">
<p-button icon="pi pi-refresh" [label]="t('reset')" outlined="true" severity="warn" (onClick)="resetFieldLocks()"></p-button> <p-button icon="pi pi-refresh" [label]="t('reset')" outlined="true" severity="warn" (onClick)="resetFieldLocks()" />
</div> </div>
<div class="footer-actions"> <div class="footer-actions">
<p-button icon="pi pi-lock" [label]="t('lockAll')" outlined="true" severity="danger" (onClick)="toggleLockAll('LOCK')"></p-button> <p-button icon="pi pi-lock" [label]="t('lockAll')" outlined="true" severity="danger" (onClick)="toggleLockAll('LOCK')" />
<p-button icon="pi pi-lock-open" [label]="t('unlockAll')" outlined="true" severity="success" (onClick)="toggleLockAll('UNLOCK')"></p-button> <p-button icon="pi pi-lock-open" [label]="t('unlockAll')" outlined="true" severity="success" (onClick)="toggleLockAll('UNLOCK')" />
<p-divider layout="vertical"></p-divider> <p-divider layout="vertical" />
<p-button [label]="isSaving ? t('saving') : t('save')" [outlined]="true" icon="pi pi-check" severity="info" (onClick)="applyFieldLocks()" [disabled]="bookIds.size === 0 || isSaving"></p-button> <p-button [label]="isSaving ? t('saving') : t('save')" [outlined]="true" icon="pi pi-check" severity="info" (onClick)="applyFieldLocks()" [disabled]="bookIds.size === 0 || isSaving" />
</div> </div>
</div> </div>
</div> </div>
@@ -24,18 +24,17 @@ import {MetadataProviderFieldsService} from '../../../../shared/metadata';
styleUrl: './lock-unlock-metadata-dialog.component.scss' styleUrl: './lock-unlock-metadata-dialog.component.scss'
}) })
export class LockUnlockMetadataDialogComponent implements OnInit { export class LockUnlockMetadataDialogComponent implements OnInit {
private bookMetadataManageService = inject(BookMetadataManageService); private readonly bookMetadataManageService = inject(BookMetadataManageService);
private dynamicDialogConfig = inject(DynamicDialogConfig); private readonly dynamicDialogConfig = inject(DynamicDialogConfig);
dialogRef = inject(DynamicDialogRef); dialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private loadingService = inject(LoadingService); private readonly loadingService = inject(LoadingService);
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
private readonly providerFields = inject(MetadataProviderFieldsService);
fieldLocks: Record<string, boolean | undefined> = {}; fieldLocks: Record<string, boolean | undefined> = {};
bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds; bookIds: Set<number> = this.dynamicDialogConfig.data.bookIds;
private readonly providerFields = inject(MetadataProviderFieldsService);
lockableFields: string[] = [ lockableFields: string[] = [
'titleLocked', 'subtitleLocked', 'publisherLocked', 'publishedDateLocked', 'descriptionLocked', 'titleLocked', 'subtitleLocked', 'publisherLocked', 'publishedDateLocked', 'descriptionLocked',
'isbn13Locked', 'isbn10Locked', 'pageCountLocked', 'thumbnailLocked', 'languageLocked', 'coverLocked', 'isbn13Locked', 'isbn10Locked', 'pageCountLocked', 'thumbnailLocked', 'languageLocked', 'coverLocked',
@@ -1,8 +1,7 @@
<ng-container *transloco="let t; prefix: 'book.seriesPage'"> <ng-container *transloco="let t; prefix: 'book.seriesPage'">
@if (isBooksLoading()) { @if (isBooksLoading()) {
<div class="loading-state"> <div class="loading-state">
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s"> <p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s" />
</p-progressSpinner>
<p style="color: var(--primary-color);"> <p style="color: var(--primary-color);">
{{ t('loadingSeriesDetails') }} {{ t('loadingSeriesDetails') }}
</p> </p>
@@ -207,8 +206,7 @@
<p-progressBar <p-progressBar
[value]="nextUp.progressPercent" [value]="nextUp.progressPercent"
[showValue]="false" [showValue]="false"
class="next-up-progress"> class="next-up-progress" />
</p-progressBar>
<span class="next-up-percent">{{ nextUp.progressPercent }}%</span> <span class="next-up-percent">{{ nextUp.progressPercent }}%</span>
</div> </div>
} }
@@ -223,7 +221,7 @@
<div class="read-progress-bar"> <div class="read-progress-bar">
@for (seg of segments; track seg.status) { @for (seg of segments; track seg.status) {
<div class="read-progress-segment" <div class="read-progress-segment"
[ngStyle]="{'width': seg.percent + '%', 'background-color': getStatusColor(seg.status)}" [style]="{'width': seg.percent + '%', 'background-color': getStatusColor(seg.status)}"
[pTooltip]="getStatusLabel(seg.status) + ': ' + seg.count"> [pTooltip]="getStatusLabel(seg.status) + ': ' + seg.count">
</div> </div>
} }
@@ -231,9 +229,9 @@
<div class="read-progress-legend"> <div class="read-progress-legend">
@for (seg of segments; track seg.status) { @for (seg of segments; track seg.status) {
<span class="legend-item" <span class="legend-item"
[ngStyle]="{'border-color': getStatusColor(seg.status)}"> [style.border-color]="getStatusColor(seg.status)">
<span class="legend-dot" <span class="legend-dot"
[ngStyle]="{'background-color': getStatusColor(seg.status)}"></span> [style.background-color]="getStatusColor(seg.status)"></span>
{{ getStatusLabel(seg.status) }} ({{ seg.count }}) {{ getStatusLabel(seg.status) }} ({{ seg.count }})
</span> </span>
} }
@@ -259,15 +257,15 @@
<span>{{ t('synopsis') }}</span> <span>{{ t('synopsis') }}</span>
</div> </div>
<div class="description-body"> <div class="description-body">
<div #descriptionContent [ngClass]="{ 'description-content-collapsed': !isExpanded() }" <div #descriptionContent [class.description-content-collapsed]="!isExpanded()"
class="description-content"> class="description-content">
<div class="description-html" <div class="description-html"
[innerHTML]="firstDescription() || t('noDescription')"></div> [innerHTML]="firstDescription() || t('noDescription')"></div>
</div> </div>
@if (isExpanded() || isOverflowing()) { @if (isExpanded() || isOverflowing()) {
<button class="expand-toggle" (click)="toggleExpand()"> <button type="button" class="expand-toggle" (click)="toggleExpand()">
{{ isExpanded() ? t('showLess') : t('showMore') }} {{ isExpanded() ? t('showLess') : t('showMore') }}
<i class="pi" [ngClass]="isExpanded() ? 'pi-chevron-up' : 'pi-chevron-down'"></i> <i class="pi" [class]="isExpanded() ? 'pi-chevron-up' : 'pi-chevron-down'"></i>
</button> </button>
} }
</div> </div>
@@ -295,8 +293,7 @@
(checkboxClick)="onCheckboxClicked($event)" (checkboxClick)="onCheckboxClicked($event)"
[isSelected]="isBookSelected(book)" [isSelected]="isBookSelected(book)"
[useSquareCovers]="seriesCardsUseSquareCovers" [useSquareCovers]="seriesCardsUseSquareCovers"
[overlayPreferenceService]="bookCardOverlayPreferenceService"> [overlayPreferenceService]="bookCardOverlayPreferenceService" />
</app-legacy-book-card>
} }
</div> </div>
@@ -345,7 +342,7 @@
@if (getBookProgress(book); as progress) { @if (getBookProgress(book); as progress) {
<div class="list-progress-row"> <div class="list-progress-row">
<div class="list-progress-bar"> <div class="list-progress-bar">
<div class="list-progress-fill" [ngStyle]="{'width': progress + '%'}"></div> <div class="list-progress-fill" [style.width]="progress + '%'"></div>
</div> </div>
<span class="list-progress-text">{{ progress }}%</span> <span class="list-progress-text">{{ progress }}%</span>
</div> </div>
@@ -354,7 +351,7 @@
<div class="list-rating-row"> <div class="list-rating-row">
@for (star of [1,2,3,4,5]; track star) { @for (star of [1,2,3,4,5]; track star) {
<i class="pi list-star" <i class="pi list-star"
[ngClass]="book.personalRating! >= star * 2 ? 'pi-star-fill' : (book.personalRating! >= star * 2 - 1 ? 'pi-star-half-fill' : 'pi-star')"> [class]="book.personalRating! >= star * 2 ? 'pi-star-fill' : (book.personalRating! >= star * 2 - 1 ? 'pi-star-half-fill' : 'pi-star')">
</i> </i>
} }
<span class="list-rating-value">{{ book.personalRating }}/10</span> <span class="list-rating-value">{{ book.personalRating }}/10</span>
@@ -364,7 +361,7 @@
<div class="list-right-col"> <div class="list-right-col">
<div class="list-badges"> <div class="list-badges">
<span class="list-status-badge" <span class="list-status-badge"
[ngStyle]="{'background-color': getStatusColor(book.readStatus)}"> [style.background-color]="getStatusColor(book.readStatus)">
{{ getStatusLabel(book.readStatus) }} {{ getStatusLabel(book.readStatus) }}
</span> </span>
@if (book.primaryFile?.bookType; as bookType) { @if (book.primaryFile?.bookType; as bookType) {
@@ -377,11 +374,11 @@
} }
</div> </div>
<div class="list-actions"> <div class="list-actions">
<button class="list-action-btn btn-read" (click)="readBook(book.id); $event.stopPropagation()" <button type="button" class="list-action-btn btn-read" (click)="readBook(book.id); $event.stopPropagation()"
[pTooltip]="t('readButton')" tooltipPosition="top"> [pTooltip]="t('readButton')" tooltipPosition="top">
<i class="pi pi-book"></i> <i class="pi pi-book"></i>
</button> </button>
<button class="list-action-btn btn-details" (click)="viewBookDetails(book.id); $event.stopPropagation()" <button type="button" class="list-action-btn btn-details" (click)="viewBookDetails(book.id); $event.stopPropagation()"
[pTooltip]="t('viewDetails')" tooltipPosition="top"> [pTooltip]="t('viewDetails')" tooltipPosition="top">
<i class="pi pi-info-circle"></i> <i class="pi pi-info-circle"></i>
</button> </button>
@@ -389,7 +386,7 @@
</div> </div>
</div> </div>
} }
@if (books.length === 0) { @empty {
<div class="empty-state">{{ t('noBooksFound') }}</div> <div class="empty-state">{{ t('noBooksFound') }}</div>
} }
</div> </div>
@@ -418,8 +415,7 @@
tooltipPosition="top" tooltipPosition="top"
outlined="true" outlined="true"
severity="info" severity="info"
icon="pi pi-database"> icon="pi pi-database" />
</p-button>
} }
<p-button <p-button
icon="pi pi-bookmark-fill" icon="pi pi-bookmark-fill"
@@ -427,8 +423,7 @@
severity="info" severity="info"
(onClick)="openShelfAssigner()" (onClick)="openShelfAssigner()"
[pTooltip]="t('tooltip.assignToShelf')" [pTooltip]="t('tooltip.assignToShelf')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
@if (user.permissions.canBulkLockUnlockMetadata) { @if (user.permissions.canBulkLockUnlockMetadata) {
<p-button <p-button
outlined="true" outlined="true"
@@ -436,8 +431,7 @@
severity="info" severity="info"
(click)="lockUnlockMetadata()" (click)="lockUnlockMetadata()"
[pTooltip]="t('tooltip.lockUnlockMetadata')" [pTooltip]="t('tooltip.lockUnlockMetadata')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
} }
@if (user.permissions.canMoveOrganizeFiles && appSettings()?.diskType === 'LOCAL') { @if (user.permissions.canMoveOrganizeFiles && appSettings()?.diskType === 'LOCAL') {
<p-button <p-button
@@ -446,8 +440,7 @@
severity="info" severity="info"
(click)="moveFiles()" (click)="moveFiles()"
[pTooltip]="t('tooltip.organizeFiles')" [pTooltip]="t('tooltip.organizeFiles')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
} }
@if (hasMoreActionsItems) { @if (hasMoreActionsItems) {
<div class="more-actions-wrapper"> <div class="more-actions-wrapper">
@@ -457,13 +450,12 @@
tooltipPosition="top" tooltipPosition="top"
outlined="true" outlined="true"
severity="info" severity="info"
icon="pi pi-ellipsis-v"> icon="pi pi-ellipsis-v" />
</p-button>
<p-tieredMenu #moreActionsMenu [model]="moreActionsMenuItems()" [popup]="true" appendTo="body"/> <p-tieredMenu #moreActionsMenu [model]="moreActionsMenuItems()" [popup]="true" appendTo="body"/>
</div> </div>
} }
</div> </div>
<p-divider layout="vertical"></p-divider> <p-divider layout="vertical" />
<div class="footer-action-group"> <div class="footer-action-group">
<p-button <p-button
outlined="true" outlined="true"
@@ -471,27 +463,24 @@
severity="success" severity="success"
(click)="selectAllBooks()" (click)="selectAllBooks()"
[pTooltip]="t('tooltip.selectAll')" [pTooltip]="t('tooltip.selectAll')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
<p-button <p-button
outlined="true" outlined="true"
icon="pi pi-times" icon="pi pi-times"
severity="warn" severity="warn"
(click)="deselectAllBooks()" (click)="deselectAllBooks()"
[pTooltip]="t('tooltip.deselectAll')" [pTooltip]="t('tooltip.deselectAll')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</div> </div>
@if (user.permissions.admin || user.permissions.canDeleteBook) { @if (user.permissions.admin || user.permissions.canDeleteBook) {
<p-divider layout="vertical"></p-divider> <p-divider layout="vertical" />
<p-button <p-button
outlined="true" outlined="true"
icon="pi pi-trash" icon="pi pi-trash"
severity="danger" severity="danger"
(click)="confirmDeleteBooks()" (click)="confirmDeleteBooks()"
[pTooltip]="t('tooltip.deleteSelected')" [pTooltip]="t('tooltip.deleteSelected')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
} }
</div> </div>
<div class="footer-right"></div> <div class="footer-right"></div>
@@ -2,7 +2,7 @@ import {FormsModule} from "@angular/forms";
import {Button} from "@openng/optimus-ui/button"; import {Button} from "@openng/optimus-ui/button";
import {ActivatedRoute, Router} from "@angular/router"; import {ActivatedRoute, Router} from "@angular/router";
import {toSignal} from '@angular/core/rxjs-interop'; import {toSignal} from '@angular/core/rxjs-interop';
import {DecimalPipe, KeyValuePipe, NgClass, NgStyle} from "@angular/common"; import {DecimalPipe, KeyValuePipe} from "@angular/common";
import {finalize, map, take} from "rxjs/operators"; import {finalize, map, take} from "rxjs/operators";
import {Book, BookType, computeSeriesReadStatus, ReadStatus} from "../../model/book.model"; import {Book, BookType, computeSeriesReadStatus, ReadStatus} from "../../model/book.model";
import {BookService} from "../../service/book.service"; import {BookService} from "../../service/book.service";
@@ -75,8 +75,6 @@ interface SeriesStats {
KeyValuePipe, KeyValuePipe,
Button, Button,
FormsModule, FormsModule,
NgStyle,
NgClass,
LegacyBookCardComponent, LegacyBookCardComponent,
ProgressSpinner, ProgressSpinner,
ProgressBar, ProgressBar,
@@ -94,32 +92,32 @@ interface SeriesStats {
], ],
}) })
export class SeriesPageComponent implements AfterViewChecked { export class SeriesPageComponent implements AfterViewChecked {
private readonly route = inject(ActivatedRoute);
private readonly bookService = inject(BookService);
private readonly languageResolver = inject(LanguageResolverService);
private readonly bookMetadataManageService = inject(BookMetadataManageService);
private readonly router = inject(Router);
protected userService = inject(UserService);
private readonly bookMenuService = inject(BookMenuService);
protected confirmationService = inject(ConfirmationService);
private readonly loadingService = inject(LoadingService);
private readonly dialogHelperService = inject(BookDialogHelperService);
protected taskHelperService = inject(TaskHelperService);
private readonly messageService = inject(MessageService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
protected appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
protected urlHelper = inject(UrlHelperService);
private readonly authorService = inject(AuthorService);
private readonly layoutService = inject(LayoutService);
private readonly DEFAULT_SERIES_CARD_WIDTH = 135; private readonly DEFAULT_SERIES_CARD_WIDTH = 135;
private readonly DEFAULT_SERIES_CARD_HEIGHT = 220; private readonly DEFAULT_SERIES_CARD_HEIGHT = 220;
private readonly DESKTOP_SERIES_GRID_GAP = 21; private readonly DESKTOP_SERIES_GRID_GAP = 21;
private readonly MOBILE_SERIES_GRID_GAP = 8; private readonly MOBILE_SERIES_GRID_GAP = 8;
private readonly MOBILE_GRID_COLUMNS = 2; private readonly MOBILE_GRID_COLUMNS = 2;
private route = inject(ActivatedRoute); private readonly metadataCenterViewMode: "route" | "dialog" = "route";
private bookService = inject(BookService);
private languageResolver = inject(LanguageResolverService);
private bookMetadataManageService = inject(BookMetadataManageService);
private metadataCenterViewMode: "route" | "dialog" = "route";
private dialogRef?: DynamicDialogRef | null; private dialogRef?: DynamicDialogRef | null;
private router = inject(Router);
protected userService = inject(UserService);
private bookMenuService = inject(BookMenuService);
protected confirmationService = inject(ConfirmationService);
private loadingService = inject(LoadingService);
private dialogHelperService = inject(BookDialogHelperService);
protected taskHelperService = inject(TaskHelperService);
private messageService = inject(MessageService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
protected appSettingsService = inject(AppSettingsService);
private readonly t = inject(TranslocoService);
protected urlHelper = inject(UrlHelperService);
private authorService = inject(AuthorService);
private layoutService = inject(LayoutService);
private readonly descriptionContentRef = viewChild<ElementRef<HTMLElement>>('descriptionContent'); private readonly descriptionContentRef = viewChild<ElementRef<HTMLElement>>('descriptionContent');
private readonly seriesGridElement = viewChild<ElementRef<HTMLElement>>('seriesGrid'); private readonly seriesGridElement = viewChild<ElementRef<HTMLElement>>('seriesGrid');
@@ -143,11 +141,11 @@ export class SeriesPageComponent implements AfterViewChecked {
protected readonly seriesCardsUseSquareCovers = false; protected readonly seriesCardsUseSquareCovers = false;
protected readonly onSeriesBookCardSelect = this.handleBookSelect.bind(this); protected readonly onSeriesBookCardSelect = this.handleBookSelect.bind(this);
private seriesParam = toSignal(this.route.paramMap.pipe( private readonly seriesParam = toSignal(this.route.paramMap.pipe(
map((params) => params.get("seriesName") || ""), map((params) => params.get("seriesName") || ""),
), {initialValue: ""}); ), {initialValue: ""});
filteredBooks = computed(() => { readonly filteredBooks = computed(() => {
const seriesName = this.seriesParam().trim().toLowerCase(); const seriesName = this.seriesParam().trim().toLowerCase();
const inSeries = this.bookService.books().filter( const inSeries = this.bookService.books().filter(
(book) => book.metadata?.seriesName?.trim().toLowerCase() === seriesName (book) => book.metadata?.seriesName?.trim().toLowerCase() === seriesName
@@ -177,16 +175,16 @@ export class SeriesPageComponent implements AfterViewChecked {
this.seriesCardSizeForWidth(this.seriesGridCardWidth()).height this.seriesCardSizeForWidth(this.seriesGridCardWidth()).height
); );
coverBook = computed(() => this.filteredBooks()[0] ?? null); readonly coverBook = computed(() => this.filteredBooks()[0] ?? null);
private firstBookId = computed(() => this.coverBook()?.id ?? null); private readonly firstBookId = computed(() => this.coverBook()?.id ?? null);
private firstBookDetailQuery = injectQuery(() => ({ private readonly firstBookDetailQuery = injectQuery(() => ({
...this.bookService.bookDetailQueryOptions(this.firstBookId() ?? -1, true), ...this.bookService.bookDetailQueryOptions(this.firstBookId() ?? -1, true),
enabled: this.firstBookId() != null, enabled: this.firstBookId() != null,
})); }));
seriesTitle = computed(() => this.filteredBooks()[0]?.metadata?.seriesName || this.seriesParam()); readonly seriesTitle = computed(() => this.filteredBooks()[0]?.metadata?.seriesName || this.seriesParam());
yearsRange = computed(() => { readonly yearsRange = computed(() => {
const years = this.filteredBooks() const years = this.filteredBooks()
.map((book) => book.metadata?.publishedDate) .map((book) => book.metadata?.publishedDate)
.filter((date): date is string => !!date) .filter((date): date is string => !!date)
@@ -202,18 +200,18 @@ export class SeriesPageComponent implements AfterViewChecked {
return min === max ? String(min) : `${min}-${max}`; return min === max ? String(min) : `${min}-${max}`;
}); });
firstBookWithDesc = computed(() => this.firstBookDetailQuery.data() ?? null); readonly firstBookWithDesc = computed(() => this.firstBookDetailQuery.data() ?? null);
firstDescription = computed(() => this.firstBookWithDesc()?.metadata?.description || ""); readonly firstDescription = computed(() => this.firstBookWithDesc()?.metadata?.description || "");
seriesReadStatus = computed(() => computeSeriesReadStatus(this.filteredBooks())); readonly seriesReadStatus = computed(() => computeSeriesReadStatus(this.filteredBooks()));
seriesReadProgress = computed(() => { readonly seriesReadProgress = computed(() => {
const books = this.filteredBooks(); const books = this.filteredBooks();
const readCount = books.filter((book) => book.readStatus === ReadStatus.READ).length; const readCount = books.filter((book) => book.readStatus === ReadStatus.READ).length;
return `${readCount}/${books.length}`; return `${readCount}/${books.length}`;
}); });
allAuthors = computed(() => { readonly allAuthors = computed(() => {
const authors = new Set<string>(); const authors = new Set<string>();
for (const book of this.filteredBooks()) { for (const book of this.filteredBooks()) {
book.metadata?.authors?.forEach((author) => authors.add(author)); book.metadata?.authors?.forEach((author) => authors.add(author));
@@ -221,7 +219,7 @@ export class SeriesPageComponent implements AfterViewChecked {
return Array.from(authors); return Array.from(authors);
}); });
allCategories = computed(() => { readonly allCategories = computed(() => {
const categories = new Set<string>(); const categories = new Set<string>();
for (const book of this.filteredBooks()) { for (const book of this.filteredBooks()) {
book.metadata?.categories?.forEach((category) => categories.add(category)); book.metadata?.categories?.forEach((category) => categories.add(category));
@@ -229,7 +227,7 @@ export class SeriesPageComponent implements AfterViewChecked {
return Array.from(categories); return Array.from(categories);
}); });
allPublishers = computed(() => { readonly allPublishers = computed(() => {
const publishers = new Set<string>(); const publishers = new Set<string>();
for (const book of this.filteredBooks()) { for (const book of this.filteredBooks()) {
if (book.metadata?.publisher) { if (book.metadata?.publisher) {
@@ -239,7 +237,7 @@ export class SeriesPageComponent implements AfterViewChecked {
return Array.from(publishers); return Array.from(publishers);
}); });
allLanguages = computed(() => { readonly allLanguages = computed(() => {
const languages = new Set<string>(); const languages = new Set<string>();
for (const book of this.filteredBooks()) { for (const book of this.filteredBooks()) {
if (book.metadata?.language) { if (book.metadata?.language) {
@@ -249,7 +247,7 @@ export class SeriesPageComponent implements AfterViewChecked {
return Array.from(languages); return Array.from(languages);
}); });
seriesCompletion = computed<SeriesCompletion | null>(() => { readonly seriesCompletion = computed<SeriesCompletion | null>(() => {
const totals = this.filteredBooks() const totals = this.filteredBooks()
.map((book) => book.metadata?.seriesTotal) .map((book) => book.metadata?.seriesTotal)
.filter((total): total is number => total != null && total > 0); .filter((total): total is number => total != null && total > 0);
@@ -276,7 +274,7 @@ export class SeriesPageComponent implements AfterViewChecked {
}; };
}); });
readStatusBreakdown = computed(() => { readonly readStatusBreakdown = computed(() => {
const books = this.filteredBooks(); const books = this.filteredBooks();
if (books.length === 0) return []; if (books.length === 0) return [];
@@ -294,14 +292,14 @@ export class SeriesPageComponent implements AfterViewChecked {
return segments; return segments;
}); });
nextUp = computed<NextUpBook | null>(() => { readonly nextUp = computed<NextUpBook | null>(() => {
const books = this.filteredBooks(); const books = this.filteredBooks();
const reading = books.find(book => const reading = books.find(book =>
book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.READING ||
book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.RE_READING ||
book.readStatus === ReadStatus.PAUSED book.readStatus === ReadStatus.PAUSED
); );
const target = reading || books.find(book => book.readStatus === ReadStatus.UNREAD || !book.readStatus); const target = reading ?? books.find(book => book.readStatus === ReadStatus.UNREAD || !book.readStatus);
if (!target) return null; if (!target) return null;
const isAudiobook = target.primaryFile?.bookType === 'AUDIOBOOK'; const isAudiobook = target.primaryFile?.bookType === 'AUDIOBOOK';
@@ -330,7 +328,7 @@ export class SeriesPageComponent implements AfterViewChecked {
return {book: target, thumbnailUrl, isReading, progressPercent}; return {book: target, thumbnailUrl, isReading, progressPercent};
}); });
seriesStats = computed<SeriesStats>(() => { readonly seriesStats = computed<SeriesStats>(() => {
let totalPages = 0; let totalPages = 0;
const personalRatings: number[] = []; const personalRatings: number[] = [];
const goodreadsRatings: number[] = []; const goodreadsRatings: number[] = [];
@@ -20,8 +20,7 @@
[rounded]="true" [rounded]="true"
severity="secondary" severity="secondary"
(onClick)="closeDialog()" (onClick)="closeDialog()"
class="close-button"> class="close-button" />
</p-button>
</div> </div>
<div class="shelves-container"> <div class="shelves-container">
@@ -37,18 +37,18 @@ import {IconSelection, toIconSelection} from '../../../../shared/icons/icon-sele
}) })
export class ShelfAssignerComponent { export class ShelfAssignerComponent {
private shelfService = inject(ShelfService); private readonly shelfService = inject(ShelfService);
private dynamicDialogConfig = inject(DynamicDialogConfig); private readonly dynamicDialogConfig = inject(DynamicDialogConfig);
private dynamicDialogRef = inject(DynamicDialogRef); private readonly dynamicDialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private bookService = inject(BookService); private readonly bookService = inject(BookService);
private bookDialogHelper = inject(BookDialogHelperService); private readonly bookDialogHelper = inject(BookDialogHelperService);
private loadingService = inject(LoadingService); private readonly loadingService = inject(LoadingService);
private userService = inject(UserService); private readonly userService = inject(UserService);
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
searchQuery = ''; searchQuery = '';
private currentUser = this.userService.currentUser; private readonly currentUser = this.userService.currentUser;
book: Book = this.dynamicDialogConfig.data.book; book: Book = this.dynamicDialogConfig.data.book;
selectedShelves: Shelf[] = []; selectedShelves: Shelf[] = [];
@@ -99,7 +99,7 @@
{{ t('visibilityLabel') }} {{ t('visibilityLabel') }}
</span> </span>
<div class="input-wrapper" style="display: flex; align-items: center; gap: 0.4375rem;"> <div class="input-wrapper" style="display: flex; align-items: center; gap: 0.4375rem;">
<p-checkbox [(ngModel)]="isPublic" [binary]="true" inputId="publicShelf"></p-checkbox> <p-checkbox [(ngModel)]="isPublic" [binary]="true" inputId="publicShelf" />
<label for="publicShelf" style="cursor: pointer">{{ t('makePublicLabel') }}</label> <label for="publicShelf" style="cursor: pointer">{{ t('makePublicLabel') }}</label>
</div> </div>
</div> </div>
@@ -30,11 +30,11 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
styleUrl: './shelf-creator.component.scss', styleUrl: './shelf-creator.component.scss',
}) })
export class ShelfCreatorComponent { export class ShelfCreatorComponent {
private shelfService = inject(ShelfService); private readonly shelfService = inject(ShelfService);
private dynamicDialogRef = inject(DynamicDialogRef); private readonly dynamicDialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private iconPickerService = inject(IconPickerService); private readonly iconPickerService = inject(IconPickerService);
private userService = inject(UserService); private readonly userService = inject(UserService);
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
shelfName: string = ''; shelfName: string = '';
@@ -16,8 +16,7 @@
[rounded]="true" [rounded]="true"
severity="secondary" severity="secondary"
(onClick)="closeDialog()" (onClick)="closeDialog()"
class="close-button"> class="close-button" />
</p-button>
</div> </div>
<div class="shelf-container"> <div class="shelf-container">
@@ -31,10 +30,10 @@
<span class="label">{{ t('shelfIconLabel') }}</span> <span class="label">{{ t('shelfIconLabel') }}</span>
<div class="icon-section"> <div class="icon-section">
@if (!selectedIcon) { @if (!selectedIcon) {
<p-button [label]="t('selectIcon')" icon="pi pi-search" [outlined]="true" severity="info" (onClick)="openIconPicker()"></p-button> <p-button [label]="t('selectIcon')" icon="pi pi-search" [outlined]="true" severity="info" (onClick)="openIconPicker()" />
} }
@if (selectedIcon) { @else {
<div class="icon-container"> <div class="icon-container">
<div class="icon-wrapper"> <div class="icon-wrapper">
<app-icon-display <app-icon-display
@@ -43,7 +42,7 @@
iconClass="icon" iconClass="icon"
/> />
</div> </div>
<p-button icon="pi pi-times" (onClick)="clearSelectedIcon()" [rounded]="true" [text]="true" severity="danger"></p-button> <p-button icon="pi pi-times" (onClick)="clearSelectedIcon()" [rounded]="true" [text]="true" severity="danger" />
</div> </div>
} }
</div> </div>
@@ -53,7 +52,7 @@
<div class="shelf-row"> <div class="shelf-row">
<span class="label">{{ t('visibilityLabel') }}</span> <span class="label">{{ t('visibilityLabel') }}</span>
<div class="visibility-section" style="display: flex; align-items: center; gap: 0.4375rem;"> <div class="visibility-section" style="display: flex; align-items: center; gap: 0.4375rem;">
<p-checkbox [(ngModel)]="isPublic" [binary]="true" inputId="publicShelf"></p-checkbox> <p-checkbox [(ngModel)]="isPublic" [binary]="true" inputId="publicShelf" />
<label for="publicShelf" style="cursor: pointer; user-select: none;">{{ t('publicShelfLabel') }}</label> <label for="publicShelf" style="cursor: pointer; user-select: none;">{{ t('publicShelfLabel') }}</label>
</div> </div>
</div> </div>
@@ -31,12 +31,12 @@ import {IconSelection, toIconSelection} from '../../../../shared/icons/icon-sele
}) })
export class ShelfEditDialogComponent implements OnInit { export class ShelfEditDialogComponent implements OnInit {
private shelfService = inject(ShelfService); private readonly shelfService = inject(ShelfService);
private dynamicDialogConfig = inject(DynamicDialogConfig); private readonly dynamicDialogConfig = inject(DynamicDialogConfig);
private dynamicDialogRef = inject(DynamicDialogRef); private readonly dynamicDialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private iconPickerService = inject(IconPickerService); private readonly iconPickerService = inject(IconPickerService);
private userService = inject(UserService); private readonly userService = inject(UserService);
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
private readonly injector = inject(Injector); private readonly injector = inject(Injector);
private shelfInitialized = false; private shelfInitialized = false;
@@ -1,5 +1,5 @@
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {mutationOptions} from '@tanstack/angular-query-experimental'; import {mutationOptions} from '@tanstack/angular-query-experimental';
import {lastValueFrom} from 'rxjs'; import {lastValueFrom} from 'rxjs';
@@ -7,7 +7,7 @@ import {API_CONFIG} from '../../../core/config/api-config';
import {bookBackgroundSubmissionKeys} from './book-background-submission-keys'; import {bookBackgroundSubmissionKeys} from './book-background-submission-keys';
import {ChangeCoversVariables, QuickSendBookVariables} from './book-background-submission.models'; import {ChangeCoversVariables, QuickSendBookVariables} from './book-background-submission.models';
@Injectable({providedIn: 'root'}) @Service()
export class BookBackgroundSubmissionService { export class BookBackgroundSubmissionService {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`; private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
@@ -1,5 +1,5 @@
import {HttpClient, HttpParams} from '@angular/common/http'; import {HttpClient, HttpParams} from '@angular/common/http';
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {lastValueFrom} from 'rxjs'; import {lastValueFrom} from 'rxjs';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
@@ -34,7 +34,7 @@ const RESET_PROGRESS_BACKEND_TYPES = {
KOBO: 'KOBO', KOBO: 'KOBO',
} as const satisfies Record<BookProgressSource, string>; } as const satisfies Record<BookProgressSource, string>;
@Injectable({providedIn: 'root'}) @Service()
export class BookCommandService { export class BookCommandService {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`; private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
@@ -1,5 +1,5 @@
import {HttpClient, HttpParams} from '@angular/common/http'; import {HttpClient, HttpParams} from '@angular/common/http';
import {effect, inject, Injectable} from '@angular/core'; import {effect, inject, Service} from '@angular/core';
import { import {
type InfiniteData, type InfiniteData,
infiniteQueryOptions, infiniteQueryOptions,
@@ -30,7 +30,7 @@ import {BookDetail, BookRecommendation, BookSummary} from './book-response.model
import {abortSignal, QUERY_DEFAULTS} from '../../../core/data/query-transport'; import {abortSignal, QUERY_DEFAULTS} from '../../../core/data/query-transport';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
@Injectable({providedIn: 'root'}) @Service()
export class BookQueryService { export class BookQueryService {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
@@ -1,5 +1,5 @@
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {lastValueFrom} from 'rxjs'; import {lastValueFrom} from 'rxjs';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
@@ -14,7 +14,7 @@ import {BookShelf} from './book-response.models';
import {applyBookQueryChangeSet} from './book-query-cache'; import {applyBookQueryChangeSet} from './book-query-cache';
import {invalidateShelfDefinitions} from './shelf-definition-query-cache'; import {invalidateShelfDefinitions} from './shelf-definition-query-cache';
@Injectable({providedIn: 'root'}) @Service()
export class BookShelfCommandService { export class BookShelfCommandService {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
private readonly membershipUrl = `${API_CONFIG.BASE_URL}/api/v1/books/shelves`; private readonly membershipUrl = `${API_CONFIG.BASE_URL}/api/v1/books/shelves`;
@@ -1,5 +1,5 @@
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {effect, inject, Injectable} from '@angular/core'; import {effect, inject, Service} from '@angular/core';
import {queryOptions, QueryClient} from '@tanstack/angular-query-experimental'; import {queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
import {lastValueFrom, takeUntil} from 'rxjs'; import {lastValueFrom, takeUntil} from 'rxjs';
@@ -9,7 +9,7 @@ import {ShelfDefinition} from './shelf-definition.models';
import {shelfDefinitionQueryKeys} from './shelf-definition-query-keys'; import {shelfDefinitionQueryKeys} from './shelf-definition-query-keys';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
@Injectable({providedIn: 'root'}) @Service()
export class ShelfDefinitionQueryService { export class ShelfDefinitionQueryService {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
private readonly authService = inject(AuthService); private readonly authService = inject(AuthService);
@@ -1,9 +1,7 @@
import {Injectable} from '@angular/core'; import {Service} from '@angular/core';
import {ReadStatus} from '../model/book.model'; import {ReadStatus} from '../model/book.model';
@Injectable({ @Service()
providedIn: 'root'
})
export class ReadStatusHelper { export class ReadStatusHelper {
getReadStatusIcon(readStatus: ReadStatus | undefined): string { getReadStatusIcon(readStatus: ReadStatus | undefined): string {
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog'; import {DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog';
import {DialogLauncherService, DialogSize, DialogStyle} from '../../../shared/services/dialog-launcher.service'; import {DialogLauncherService, DialogSize, DialogStyle} from '../../../shared/services/dialog-launcher.service';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum'; import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
@@ -12,10 +12,10 @@ interface MetadataRefreshDialogContext {
libraryId?: number; libraryId?: number;
} }
@Injectable({providedIn: 'root'}) @Service()
export class BookDialogHelperService { export class BookDialogHelperService {
private dialogLauncherService = inject(DialogLauncherService); private readonly dialogLauncherService = inject(DialogLauncherService);
private openDialog(component: unknown, options: object): DynamicDialogRef | null { private openDialog(component: unknown, options: object): DynamicDialogRef | null {
return this.dialogLauncherService.openDialog(component, options); return this.dialogLauncherService.openDialog(component, options);
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {Observable, throwError, from} from 'rxjs'; import {Observable, throwError, from} from 'rxjs';
import {HttpClient, HttpEventType, HttpRequest} from '@angular/common/http'; import {HttpClient, HttpEventType, HttpRequest} from '@angular/common/http';
import {catchError, filter, map, tap} from 'rxjs/operators'; import {catchError, filter, map, tap} from 'rxjs/operators';
@@ -13,21 +13,18 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
import {patchAttachedBookFilesInCache, patchBookInCacheWith, upsertBooksInCache} from './legacy-book-cache'; import {patchAttachedBookFilesInCache, patchBookInCacheWith, upsertBooksInCache} from './legacy-book-cache';
import {mitigateWebkitUploadBug} from '../../../shared/util/mitigate-webkit-upload-bug'; import {mitigateWebkitUploadBug} from '../../../shared/util/mitigate-webkit-upload-bug';
@Injectable({ @Service()
providedIn: 'root',
})
export class BookFileService { export class BookFileService {
private readonly http = inject(HttpClient);
private readonly messageService = inject(MessageService);
private readonly fileDownloadService = inject(FileDownloadService);
private readonly queryClient = inject(QueryClient);
private readonly cacheStorageService = inject(CacheStorageService);
private readonly localSettingsService = inject(LocalSettingsService);
private readonly t = inject(TranslocoService);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private messageService = inject(MessageService);
private fileDownloadService = inject(FileDownloadService);
private queryClient = inject(QueryClient);
private cacheStorageService = inject(CacheStorageService);
private localSettingsService = inject(LocalSettingsService);
private readonly t = inject(TranslocoService);
getFileContent(bookId: number, bookType?: string): Observable<Blob> { getFileContent(bookId: number, bookType?: string): Observable<Blob> {
let url = `${this.url}/${bookId}/content`; let url = `${this.url}/${bookId}/content`;
if (bookType) { if (bookType) {
@@ -81,7 +78,7 @@ export class BookFileService {
tap(() => { tap(() => {
patchBookInCacheWith(this.queryClient, bookId, book => { patchBookInCacheWith(this.queryClient, bookId, book => {
if (isPrimary) { if (isPrimary) {
const remaining = book.alternativeFormats?.filter(f => f.id !== fileId) || []; const remaining = book.alternativeFormats?.filter(f => f.id !== fileId) ?? [];
const [newPrimary, ...rest] = remaining; const [newPrimary, ...rest] = remaining;
return {...book, primaryFile: newPrimary, alternativeFormats: rest}; return {...book, primaryFile: newPrimary, alternativeFormats: rest};
} }
@@ -143,9 +140,9 @@ export class BookFileService {
.pipe(tap(newFile => { .pipe(tap(newFile => {
patchBookInCacheWith(this.queryClient, bookId, book => { patchBookInCacheWith(this.queryClient, bookId, book => {
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) { if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
return {...book, alternativeFormats: [...(book.alternativeFormats || []), newFile]}; return {...book, alternativeFormats: [...(book.alternativeFormats ?? []), newFile]};
} }
return {...book, supplementaryFiles: [...(book.supplementaryFiles || []), newFile]}; return {...book, supplementaryFiles: [...(book.supplementaryFiles ?? []), newFile]};
}); });
this.messageService.add({ this.messageService.add({
severity: 'success', severity: 'success',
@@ -166,8 +163,8 @@ export class BookFileService {
downloadAdditionalFile(book: Book, fileId: number): void { downloadAdditionalFile(book: Book, fileId: number): void {
const additionalFile = [ const additionalFile = [
...(book.alternativeFormats || []), ...(book.alternativeFormats ?? []),
...(book.supplementaryFiles || []) ...(book.supplementaryFiles ?? [])
].find((f: AdditionalFile) => f.id === fileId); ].find((f: AdditionalFile) => f.id === fileId);
const downloadUrl = `${this.url}/${book.id}/files/${fileId}/download`; const downloadUrl = `${this.url}/${book.id}/files/${fileId}/download`;
this.fileDownloadService.downloadFile(downloadUrl, additionalFile?.fileName ?? 'file'); this.fileDownloadService.downloadFile(downloadUrl, additionalFile?.fileName ?? 'file');
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {ConfirmationService, MenuItem, MessageService} from '@openng/optimus-ui/api'; import {ConfirmationService, MenuItem, MessageService} from '@openng/optimus-ui/api';
import {BookService} from './book.service'; import {BookService} from './book.service';
import {BookMetadataManageService} from './book-metadata-manage.service'; import {BookMetadataManageService} from './book-metadata-manage.service';
@@ -12,9 +12,7 @@ import {APIException} from '../../../shared/models/api-exception.model';
import {HttpErrorResponse} from '@angular/common/http'; import {HttpErrorResponse} from '@angular/common/http';
import {TranslocoService} from '@jsverse/transloco'; import {TranslocoService} from '@jsverse/transloco';
@Injectable({ @Service()
providedIn: 'root'
})
export class BookMenuService { export class BookMenuService {
confirmationService = inject(ConfirmationService); confirmationService = inject(ConfirmationService);
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {Observable, of} from 'rxjs'; import {Observable, of} from 'rxjs';
import {HttpClient, HttpEventType, HttpParams, HttpRequest} from '@angular/common/http'; import {HttpClient, HttpEventType, HttpParams, HttpRequest} from '@angular/common/http';
import {catchError, filter, map, tap, mergeMap} from 'rxjs/operators'; import {catchError, filter, map, tap, mergeMap} from 'rxjs/operators';
@@ -10,18 +10,15 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
import {invalidateAllBookCaches, invalidateBooksById, patchBookMetadataInCache, patchBooksInCacheWith} from './legacy-book-cache'; import {invalidateAllBookCaches, invalidateBooksById, patchBookMetadataInCache, patchBooksInCacheWith} from './legacy-book-cache';
import {mitigateWebkitUploadBug} from '../../../shared/util/mitigate-webkit-upload-bug'; import {mitigateWebkitUploadBug} from '../../../shared/util/mitigate-webkit-upload-bug';
@Injectable({ @Service()
providedIn: 'root',
})
export class BookMetadataManageService { export class BookMetadataManageService {
private readonly http = inject(HttpClient);
private readonly messageService = inject(MessageService);
private readonly queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private messageService = inject(MessageService);
private queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean, replaceMode: 'REPLACE_ALL' | 'REPLACE_WHEN_PROVIDED' = 'REPLACE_ALL'): Observable<BookMetadata> { updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean, replaceMode: 'REPLACE_ALL' | 'REPLACE_WHEN_PROVIDED' = 'REPLACE_ALL'): Observable<BookMetadata> {
const params = new HttpParams().set('mergeCategories', mergeCategories.toString()).set('replaceMode', replaceMode); const params = new HttpParams().set('mergeCategories', mergeCategories.toString()).set('replaceMode', replaceMode);
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe( return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
@@ -201,7 +198,7 @@ export class BookMetadataManageService {
} }
supportsDualCovers(book: Book): boolean { supportsDualCovers(book: Book): boolean {
const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType); const allFiles = [book.primaryFile, ...(book.alternativeFormats ?? [])].filter(f => f?.bookType);
const hasAudiobook = allFiles.some(f => f!.bookType === 'AUDIOBOOK'); const hasAudiobook = allFiles.some(f => f!.bookType === 'AUDIOBOOK');
const hasEbook = allFiles.some(f => f!.bookType !== 'AUDIOBOOK'); const hasEbook = allFiles.some(f => f!.bookType !== 'AUDIOBOOK');
return hasAudiobook && hasEbook; return hasAudiobook && hasEbook;
@@ -1,4 +1,4 @@
import {computed, inject, Injectable, signal} from '@angular/core'; import {computed, inject, Service, signal} from '@angular/core';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {UserService} from '../../settings/user-management/user.service'; import {UserService} from '../../settings/user-management/user.service';
@@ -10,9 +10,7 @@ export interface BookNavigationState {
currentIndex: number; currentIndex: number;
} }
@Injectable({ @Service()
providedIn: 'root'
})
export class BookNavigationService { export class BookNavigationService {
private readonly router = inject(Router); private readonly router = inject(Router);
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http'; import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable, Subject} from 'rxjs'; import {Observable, Subject} from 'rxjs';
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators'; import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
@@ -32,18 +32,15 @@ function getResetProgressFields(type: ResetProgressType): Partial<Book> {
}; };
} }
@Injectable({ @Service()
providedIn: 'root',
})
export class BookPatchService { export class BookPatchService {
private readonly http = inject(HttpClient);
private readonly queryClient = inject(QueryClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient); private readonly epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number; bookFileId?: number }>();
private queryClient = inject(QueryClient);
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number; bookFileId?: number }>(); private readonly epubProgress$ = this.epubProgressSubject.pipe(
private epubProgress$ = this.epubProgressSubject.pipe(
distinctUntilChanged((prev, curr) => distinctUntilChanged((prev, curr) =>
prev.bookId === curr.bookId && prev.bookId === curr.bookId &&
prev.cfi === curr.cfi && prev.cfi === curr.cfi &&
@@ -1,8 +1,8 @@
import {DestroyRef, inject, Injectable} from '@angular/core'; import {DestroyRef, inject, Service} from '@angular/core';
import {QueryClient} from '@tanstack/angular-query-experimental'; import {QueryClient} from '@tanstack/angular-query-experimental';
import {invalidateBookRecommendations} from '../data/book-query-cache'; import {invalidateBookRecommendations} from '../data/book-query-cache';
import {TaskProgressPayload} from '../../settings/task-management/task.service'; import {TaskProgressPayload, TaskStatus} from '../../settings/task-management/task.service';
import {Book} from '../model/book.model'; import {Book} from '../model/book.model';
import { import {
BookCoverPatch, BookCoverPatch,
@@ -17,7 +17,7 @@ import {
function isBookIdArray(payload: Book | readonly number[]): payload is readonly number[] { function isBookIdArray(payload: Book | readonly number[]): payload is readonly number[] {
return Array.isArray(payload); return Array.isArray(payload);
} }
@Injectable({providedIn: 'root'}) @Service()
export class BookSocketService { export class BookSocketService {
private readonly queryClient = inject(QueryClient); private readonly queryClient = inject(QueryClient);
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
@@ -55,7 +55,7 @@ export class BookSocketService {
} }
handleTaskProgress(payload: TaskProgressPayload): void { handleTaskProgress(payload: TaskProgressPayload): void {
if (payload.taskType !== 'UPDATE_BOOK_RECOMMENDATIONS' || payload.taskStatus !== 'COMPLETED') { if (payload.taskType !== 'UPDATE_BOOK_RECOMMENDATIONS' || payload.taskStatus !== TaskStatus.COMPLETED) {
return; return;
} }
void Promise.all([ void Promise.all([
@@ -1,4 +1,4 @@
import {computed, effect, inject, Injectable} from '@angular/core'; import {computed, effect, inject, Service} from '@angular/core';
import {first, from, lastValueFrom, Observable, throwError} from 'rxjs'; import {first, from, lastValueFrom, Observable, throwError} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http'; import {HttpClient, HttpParams} from '@angular/common/http';
import {catchError, map, tap} from 'rxjs/operators'; import {catchError, map, tap} from 'rxjs/operators';
@@ -26,29 +26,26 @@ import {
patchBooksInCache, patchBooksInCache,
} from './legacy-book-cache'; } from './legacy-book-cache';
@Injectable({ @Service()
providedIn: 'root',
})
export class BookService { export class BookService {
private readonly http = inject(HttpClient);
private readonly messageService = inject(MessageService);
private readonly authService = inject(AuthService);
private readonly router = inject(Router);
private readonly bookSocketService = inject(BookSocketService);
private readonly bookPatchService = inject(BookPatchService);
private readonly queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private messageService = inject(MessageService);
private authService = inject(AuthService);
private router = inject(Router);
private bookSocketService = inject(BookSocketService);
private bookPatchService = inject(BookPatchService);
private queryClient = inject(QueryClient);
private readonly t = inject(TranslocoService);
private readonly token = this.authService.token; private readonly token = this.authService.token;
private booksQuery = injectQuery(() => ({ private readonly booksQuery = injectQuery(() => ({
...this.getBooksQueryOptions(), ...this.getBooksQueryOptions(),
enabled: !!this.token(), enabled: !!this.token(),
})); }));
books = computed(() => this.booksQuery.data() ?? []); readonly books = computed(() => this.booksQuery.data() ?? []);
/** Pre-computed unique metadata values for autocomplete across the app. */ /** Pre-computed unique metadata values for autocomplete across the app. */
readonly uniqueMetadata = computed(() => { readonly uniqueMetadata = computed(() => {
@@ -81,7 +78,7 @@ export class BookService {
}; };
}); });
booksError = computed<string | null>(() => { readonly booksError = computed<string | null>(() => {
if (!this.token() || !this.booksQuery.isError()) { if (!this.token() || !this.booksQuery.isError()) {
return null; return null;
} }
@@ -90,7 +87,7 @@ export class BookService {
return error instanceof Error ? error.message : 'Failed to load books'; return error instanceof Error ? error.message : 'Failed to load books';
}); });
isBooksLoading = computed(() => !!this.token() && this.booksQuery.isPending()); readonly isBooksLoading = computed(() => !!this.token() && this.booksQuery.isPending());
constructor() { constructor() {
effect(() => { effect(() => {
@@ -121,7 +118,7 @@ export class BookService {
} }
ensureBookDetail(bookId: number, withDescription: boolean): Promise<Book> { ensureBookDetail(bookId: number, withDescription: boolean): Promise<Book> {
return this.queryClient.ensureQueryData(this.bookDetailQueryOptions(bookId, withDescription)); return this.queryClient.query({...this.bookDetailQueryOptions(bookId, withDescription), staleTime: 'static'});
} }
/** /**
@@ -132,7 +129,7 @@ export class BookService {
* this network request is necessary to pick up progress saved on another device or browser. * this network request is necessary to pick up progress saved on another device or browser.
*/ */
fetchFreshBookDetail(bookId: number, withDescription: boolean): Promise<Book> { fetchFreshBookDetail(bookId: number, withDescription: boolean): Promise<Book> {
return this.queryClient.fetchQuery({ return this.queryClient.query({
...this.bookDetailQueryOptions(bookId, withDescription), ...this.bookDetailQueryOptions(bookId, withDescription),
staleTime: 0, staleTime: 0,
}); });
@@ -170,7 +167,7 @@ export class BookService {
} }
getBooksInSeries(bookId: number): Observable<Book[]> { getBooksInSeries(bookId: number): Observable<Book[]> {
return from(this.queryClient.ensureQueryData(this.getBooksQueryOptions())).pipe( return from(this.queryClient.query({...this.getBooksQueryOptions(), staleTime: 'static'})).pipe(
map(books => { map(books => {
const currentBook = books.find(book => book.id === bookId); const currentBook = books.find(book => book.id === bookId);
if (!currentBook?.metadata?.seriesName) { if (!currentBook?.metadata?.seriesName) {
@@ -185,7 +182,7 @@ export class BookService {
} }
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> { getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
return from(this.queryClient.ensureQueryData(this.bookRecommendationsQueryOptions(bookId, limit))); return from(this.queryClient.query({...this.bookRecommendationsQueryOptions(bookId, limit), staleTime: 'static'}));
} }
/*------------------ Book Operations ------------------*/ /*------------------ Book Operations ------------------*/
@@ -290,7 +287,7 @@ export class BookService {
case 'EPUB': case 'EPUB':
baseUrl = 'ebook-reader'; baseUrl = 'ebook-reader';
if (reader === 'epub-streaming') { if (reader === 'epub-streaming') {
queryParams['streaming'] = true; queryParams.streaming = true;
} }
break; break;
@@ -315,7 +312,7 @@ export class BookService {
} }
if (isAlternativeFormat) { if (isAlternativeFormat) {
queryParams['bookType'] = bookType; queryParams.bookType = bookType;
} }
const hasQueryParams = Object.keys(queryParams).length > 0; const hasQueryParams = Object.keys(queryParams).length > 0;
@@ -1,5 +1,5 @@
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {Injectable, inject} from '@angular/core'; import {Service, inject} from '@angular/core';
import {API_CONFIG} from '../../../core/config/api-config'; import {API_CONFIG} from '../../../core/config/api-config';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
@@ -8,13 +8,13 @@ export interface CbxPageInfo {
displayName: string; displayName: string;
} }
@Injectable({providedIn: 'root'}) @Service()
export class CbxReaderService { export class CbxReaderService {
private readonly authService = inject(AuthService);
private readonly http = inject(HttpClient);
private readonly pagesUrl = `${API_CONFIG.BASE_URL}/api/v1/cbx`; private readonly pagesUrl = `${API_CONFIG.BASE_URL}/api/v1/cbx`;
private readonly imageUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book`; private readonly imageUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book`;
private authService = inject(AuthService);
private http = inject(HttpClient);
private getToken(): string | null { private getToken(): string | null {
return this.authService.getInternalAccessToken(); return this.authService.getInternalAccessToken();
@@ -32,9 +32,9 @@ describe('LibraryHealthService', () => {
}); });
async function fetchHealth(): Promise<void> { async function fetchHealth(): Promise<void> {
const fetchQuerySpy = vi.spyOn(queryClient, 'fetchQuery'); const querySpy = vi.spyOn(queryClient, 'query');
service.fetchHealth(); service.fetchHealth();
await fetchQuerySpy.mock.results[0]?.value; await querySpy.mock.results[0]?.value;
} }
it('fetches health', async () => { it('fetches health', async () => {
@@ -1,4 +1,4 @@
import {computed, inject, Injectable, DestroyRef} from '@angular/core'; import {computed, inject, Service, DestroyRef} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {lastValueFrom} from 'rxjs'; import {lastValueFrom} from 'rxjs';
@@ -8,22 +8,22 @@ import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-ex
const LIBRARY_HEALTH_QUERY_KEY = ['libraryHealth'] as const; const LIBRARY_HEALTH_QUERY_KEY = ['libraryHealth'] as const;
@Injectable({providedIn: 'root'}) @Service()
export class LibraryHealthService { export class LibraryHealthService {
private readonly http = inject(HttpClient);
private readonly rxStompService = inject(RxStompService);
private readonly queryClient = inject(QueryClient);
private readonly destroyRef = inject(DestroyRef);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`;
private http = inject(HttpClient);
private rxStompService = inject(RxStompService);
private queryClient = inject(QueryClient);
private destroyRef = inject(DestroyRef);
private socketInitialized = false; private socketInitialized = false;
private healthQuery = injectQuery(() => ({ private readonly healthQuery = injectQuery(() => ({
...this.getHealthQueryOptions(), ...this.getHealthQueryOptions(),
enabled: false, // manually triggered via initialize() enabled: false, // manually triggered via initialize()
})); }));
health = computed(() => this.healthQuery.data() ?? {}); readonly health = computed(() => this.healthQuery.data() ?? {});
private getHealthQueryOptions() { private getHealthQueryOptions() {
return queryOptions({ return queryOptions({
@@ -33,7 +33,7 @@ export class LibraryHealthService {
} }
fetchHealth(): void { fetchHealth(): void {
void this.queryClient.fetchQuery(this.getHealthQueryOptions()); void this.queryClient.query(this.getHealthQueryOptions());
} }
initWebsocket(): void { initWebsocket(): void {
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {TranslocoService} from '@jsverse/transloco'; import {TranslocoService} from '@jsverse/transloco';
import {ConfirmationService, MessageService} from '@openng/optimus-ui/api'; import {ConfirmationService, MessageService} from '@openng/optimus-ui/api';
@@ -15,7 +15,7 @@ import {ShelfService} from './shelf.service';
type LibraryShelfActionTarget = Readonly<{id: number; name: string}>; type LibraryShelfActionTarget = Readonly<{id: number; name: string}>;
@Injectable({providedIn: 'root'}) @Service()
export class LibraryShelfMenuService { export class LibraryShelfMenuService {
private readonly confirmationService = inject(ConfirmationService); private readonly confirmationService = inject(ConfirmationService);
private readonly messageService = inject(MessageService); private readonly messageService = inject(MessageService);
@@ -102,7 +102,7 @@ describe('LibraryService', () => {
expect(queryClientHarness.queryClient.removeQueries).toHaveBeenCalledWith({queryKey: libraryFormatCountsQueryKey(4), exact: true}); expect(queryClientHarness.queryClient.removeQueries).toHaveBeenCalledWith({queryKey: libraryFormatCountsQueryKey(4), exact: true});
}); });
it('hydrates format counts through ensureQueryData', async () => { it('hydrates format counts through query', async () => {
httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]); httpTestingController.expectOne(req => req.url.endsWith('/api/v1/libraries')).flush([]);
const resultPromise = new Promise<Record<string, number>>((resolve, reject) => { const resultPromise = new Promise<Record<string, number>>((resolve, reject) => {
@@ -1,4 +1,4 @@
import {computed, effect, inject, Injectable} from '@angular/core'; import {computed, effect, inject, Service} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {from, lastValueFrom, Observable} from 'rxjs'; import {from, lastValueFrom, Observable} from 'rxjs';
import {tap} from 'rxjs/operators'; import {tap} from 'rxjs/operators';
@@ -13,22 +13,22 @@ import {invalidateShelfDefinitions} from '../data/shelf-definition-query-cache';
import {invalidateAllBookCaches} from './legacy-book-cache'; import {invalidateAllBookCaches} from './legacy-book-cache';
import {SHELVES_QUERY_KEY} from './shelf-query-keys'; import {SHELVES_QUERY_KEY} from './shelf-query-keys';
@Injectable({providedIn: 'root'}) @Service()
export class LibraryService { export class LibraryService {
private readonly http = inject(HttpClient);
private readonly authService = inject(AuthService);
private readonly queryClient = inject(QueryClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`;
private http = inject(HttpClient);
private authService = inject(AuthService);
private queryClient = inject(QueryClient);
private readonly token = this.authService.token; private readonly token = this.authService.token;
private librariesQuery = injectQuery(() => ({ private readonly librariesQuery = injectQuery(() => ({
...this.getLibrariesQueryOptions(), ...this.getLibrariesQueryOptions(),
enabled: !!this.token(), enabled: !!this.token(),
})); }));
libraries = computed(() => this.librariesQuery.data() ?? []); readonly libraries = computed(() => this.librariesQuery.data() ?? []);
librariesError = computed<string | null>(() => { readonly librariesError = computed<string | null>(() => {
if (!this.token() || !this.librariesQuery.isError()) { if (!this.token() || !this.librariesQuery.isError()) {
return null; return null;
} }
@@ -37,7 +37,7 @@ export class LibraryService {
return error instanceof Error ? error.message : 'Failed to load libraries'; return error instanceof Error ? error.message : 'Failed to load libraries';
}); });
isLibrariesLoading = computed(() => !!this.token() && this.librariesQuery.isPending()); readonly isLibrariesLoading = computed(() => !!this.token() && this.librariesQuery.isPending());
constructor() { constructor() {
effect(() => { effect(() => {
@@ -126,7 +126,7 @@ export class LibraryService {
} }
getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> { getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> {
return from(this.queryClient.ensureQueryData(this.getLibraryFormatCountsQueryOptions(libraryId))); return from(this.queryClient.query({...this.getLibraryFormatCountsQueryOptions(libraryId), staleTime: 'static'}));
} }
private sortLibraries(libraries: Library[]): Library[] { private sortLibraries(libraries: Library[]): Library[] {
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core'; import {inject, Service} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {Observable, map} from 'rxjs'; import {Observable, map} from 'rxjs';
import {BookMetadata} from '../model/book.model'; import {BookMetadata} from '../model/book.model';
@@ -35,13 +35,11 @@ export interface MetadataFetchTask {
proposals: FetchedProposal[]; proposals: FetchedProposal[];
} }
@Injectable({ @Service()
providedIn: 'root'
})
export class MetadataTaskService { export class MetadataTaskService {
private readonly http = inject(HttpClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/metadata/tasks`; private readonly url = `${API_CONFIG.BASE_URL}/api/metadata/tasks`;
private http = inject(HttpClient);
getTaskWithProposals(taskId: string): Observable<MetadataFetchTask> { getTaskWithProposals(taskId: string): Observable<MetadataFetchTask> {
return this.http.get<{ task: MetadataFetchTask }>(`${this.url}/${taskId}`) return this.http.get<{ task: MetadataFetchTask }>(`${this.url}/${taskId}`)
@@ -1,4 +1,4 @@
import {computed, effect, inject, Injectable} from '@angular/core'; import {computed, effect, inject, Service} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {lastValueFrom, Observable} from 'rxjs'; import {lastValueFrom, Observable} from 'rxjs';
import {tap} from 'rxjs/operators'; import {tap} from 'rxjs/operators';
@@ -16,23 +16,23 @@ import {AuthService} from '../../../shared/service/auth.service';
const KOBO_SHELF_NAME = 'Kobo'; const KOBO_SHELF_NAME = 'Kobo';
const KOBO_SHELF_ICON = 'pi pi-tablet'; const KOBO_SHELF_ICON = 'pi pi-tablet';
@Injectable({providedIn: 'root'}) @Service()
export class ShelfService { export class ShelfService {
private readonly http = inject(HttpClient);
private readonly bookService = inject(BookService);
private readonly authService = inject(AuthService);
private readonly queryClient = inject(QueryClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
private http = inject(HttpClient);
private bookService = inject(BookService);
private authService = inject(AuthService);
private queryClient = inject(QueryClient);
private readonly token = this.authService.token; private readonly token = this.authService.token;
private shelvesQuery = injectQuery(() => ({ private readonly shelvesQuery = injectQuery(() => ({
...this.getShelvesQueryOptions(), ...this.getShelvesQueryOptions(),
enabled: !!this.token(), enabled: !!this.token(),
})); }));
shelves = computed(() => this.shelvesQuery.data() ?? []); readonly shelves = computed(() => this.shelvesQuery.data() ?? []);
shelvesError = computed<string | null>(() => { readonly shelvesError = computed<string | null>(() => {
if (!this.token() || !this.shelvesQuery.isError()) { if (!this.token() || !this.shelvesQuery.isError()) {
return null; return null;
} }
@@ -41,7 +41,7 @@ export class ShelfService {
return error instanceof Error ? error.message : 'Failed to load shelves'; return error instanceof Error ? error.message : 'Failed to load shelves';
}); });
isShelvesLoading = computed(() => !!this.token() && this.shelvesQuery.isPending()); readonly isShelvesLoading = computed(() => !!this.token() && this.shelvesQuery.isPending());
constructor() { constructor() {
effect(() => { effect(() => {
@@ -5,7 +5,7 @@
<span [innerHTML]="t('infoBanner', { fileCount: fileCount })"></span> <span [innerHTML]="t('infoBanner', { fileCount: fileCount })"></span>
</div> </div>
<p-divider></p-divider> <p-divider />
<div class="fields-section"> <div class="fields-section">
<h4>{{ t('textFieldsTitle') }}</h4> <h4>{{ t('textFieldsTitle') }}</h4>
@@ -16,8 +16,7 @@
[binary]="true" [binary]="true"
[ngModel]="isFieldEnabled(field.name)" [ngModel]="isFieldEnabled(field.name)"
(ngModelChange)="toggleField(field.name)" (ngModelChange)="toggleField(field.name)"
[ariaLabel]="t('enableField', { label: field.label })"> [ariaLabel]="t('enableField', { label: field.label })" />
</p-checkbox>
<label class="field-label" [attr.for]="field.controlName">{{ field.label }}</label> <label class="field-label" [attr.for]="field.controlName">{{ field.label }}</label>
<input <input
pInputText pInputText
@@ -30,7 +29,7 @@
</div> </div>
</div> </div>
<p-divider></p-divider> <p-divider />
<div class="fields-section"> <div class="fields-section">
<h4>{{ t('numberFieldsTitle') }}</h4> <h4>{{ t('numberFieldsTitle') }}</h4>
@@ -41,8 +40,7 @@
[binary]="true" [binary]="true"
[ngModel]="isFieldEnabled(field.name)" [ngModel]="isFieldEnabled(field.name)"
(ngModelChange)="toggleField(field.name)" (ngModelChange)="toggleField(field.name)"
[ariaLabel]="t('enableField', { label: field.label })"> [ariaLabel]="t('enableField', { label: field.label })" />
</p-checkbox>
<label class="field-label" [attr.for]="field.controlName">{{ field.label }}</label> <label class="field-label" [attr.for]="field.controlName">{{ field.label }}</label>
<input <input
pInputText pInputText
@@ -56,7 +54,7 @@
</div> </div>
</div> </div>
<p-divider></p-divider> <p-divider />
<div class="fields-section"> <div class="fields-section">
<div class="section-header"> <div class="section-header">
@@ -68,8 +66,7 @@
[(ngModel)]="mergeArrays" [(ngModel)]="mergeArrays"
optionLabel="label" optionLabel="label"
optionValue="value" optionValue="value"
ariaLabelledBy="merge-mode-label"> ariaLabelledBy="merge-mode-label" />
</p-selectButton>
</div> </div>
</div> </div>
<p class="helper-text"><i class="pi pi-info-circle"></i> {{ t('helperText') }}</p> <p class="helper-text"><i class="pi pi-info-circle"></i> {{ t('helperText') }}</p>
@@ -80,8 +77,7 @@
[binary]="true" [binary]="true"
[ngModel]="isFieldEnabled(field.name)" [ngModel]="isFieldEnabled(field.name)"
(ngModelChange)="toggleField(field.name)" (ngModelChange)="toggleField(field.name)"
[ariaLabel]="t('enableField', { label: field.label })"> [ariaLabel]="t('enableField', { label: field.label })" />
</p-checkbox>
<label class="field-label" [attr.for]="field.controlName">{{ field.label }}</label> <label class="field-label" [attr.for]="field.controlName">{{ field.label }}</label>
<p-autoComplete <p-autoComplete
[formControl]="getControl(field.controlName)" [formControl]="getControl(field.controlName)"
@@ -92,29 +88,26 @@
[dropdown]="false" [dropdown]="false"
[ariaLabel]="field.label" [ariaLabel]="field.label"
(onBlur)="onAutoCompleteBlur(field.name, $event)" (onBlur)="onAutoCompleteBlur(field.name, $event)"
class="field-input"> class="field-input" />
</p-autoComplete>
</div> </div>
} }
</div> </div>
</div> </div>
<p-divider></p-divider> <p-divider />
<div class="dialog-footer"> <div class="dialog-footer">
<p-button <p-button
[label]="'common.cancel' | transloco" [label]="'common.cancel' | transloco"
icon="pi pi-times" icon="pi pi-times"
severity="secondary" severity="secondary"
(click)="cancel()"> (click)="cancel()" />
</p-button>
<p-button <p-button
[label]="t('applyToSelected')" [label]="t('applyToSelected')"
icon="pi pi-check" icon="pi pi-check"
severity="success" severity="success"
[disabled]="!hasEnabledFields" [disabled]="!hasEnabledFields"
(click)="apply()"> (click)="apply()" />
</p-button>
</div> </div>
</div> </div>
</ng-container> </ng-container>
@@ -52,10 +52,8 @@
appendTo="body" appendTo="body"
lazyLoad lazyLoad
[preview]="true" [preview]="true"
[ngClass]="{ [class.changed]="isValueCopied('thumbnailUrl')"
'changed': isValueCopied('thumbnailUrl'), />
}"
></p-image>
} }
@else { @else {
<div class="thumbnail no-cover-text">{{ t('noCoverImage') }}</div> <div class="thumbnail no-cover-text">{{ t('noCoverImage') }}</div>
@@ -80,7 +78,7 @@
appendTo="body" appendTo="body"
lazyLoad lazyLoad
[preview]="true" [preview]="true"
></p-image> />
} }
@else { @else {
<div class="thumbnail no-cover-text">{{ t('coverImageNotFound') }}</div> <div class="thumbnail no-cover-text">{{ t('coverImageNotFound') }}</div>
@@ -100,17 +98,13 @@
id="{{field.controlName}}" id="{{field.controlName}}"
formControlName="{{field.controlName}}" formControlName="{{field.controlName}}"
class="dest" class="dest"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
/> />
<p-button <p-button
size="small" size="small"
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')" [icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')"
[outlined]="true" [outlined]="true"
[ngClass]="{ [class.nosrc]="!fetchedMetadata[field.fetchedKey]"
'nosrc' : !fetchedMetadata[field.fetchedKey]
}"
class="arrow-button" class="arrow-button"
[severity]="isValueChanged(field.controlName) ? 'warn' : null" [severity]="isValueChanged(field.controlName) ? 'warn' : null"
[disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)" [disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)"
@@ -123,9 +117,7 @@
[value]="fetchedMetadata[field.fetchedKey] ?? null" [value]="fetchedMetadata[field.fetchedKey] ?? null"
class="src" class="src"
disabled disabled
[ngClass]="{ [class.diff]="isFetchedDifferent(field.controlName)"
'diff': isFetchedDifferent(field.controlName),
}"
/> />
} }
</div> </div>
@@ -147,17 +139,12 @@
[iconDisplay]="'input'" [iconDisplay]="'input'"
appendTo="body" appendTo="body"
class="dest" class="dest"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)" />
'changed': isValueChanged(field.controlName),
}">
</p-datepicker>
<p-button <p-button
size="small" size="small"
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')" [icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')"
[outlined]="true" [outlined]="true"
[ngClass]="{ [class.nosrc]="!fetchedMetadata[field.fetchedKey]"
'nosrc' : !fetchedMetadata[field.fetchedKey]
}"
class="arrow-button" class="arrow-button"
[severity]="isValueChanged(field.controlName) ? 'warn' : null" [severity]="isValueChanged(field.controlName) ? 'warn' : null"
[disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)" [disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)"
@@ -170,9 +157,7 @@
[value]="fetchedMetadata[field.fetchedKey] ?? null" [value]="fetchedMetadata[field.fetchedKey] ?? null"
class="src" class="src"
disabled disabled
[ngClass]="{ [class.diff]="isFetchedDifferent(field.controlName)"
'diff': isFetchedDifferent(field.controlName),
}"
/> />
} }
</div> </div>
@@ -186,7 +171,7 @@
<div class="author-chips-container dest full-width" <div class="author-chips-container dest full-width"
cdkDropList cdkDropListOrientation="mixed" cdkDropList cdkDropListOrientation="mixed"
(cdkDropListDropped)="dropAuthor($event)" (cdkDropListDropped)="dropAuthor($event)"
[ngClass]="{ 'changed': isValueChanged('authors') }"> [class.changed]="isValueChanged('authors')">
@for (author of metadataForm.get('authors')!.value; track $index) { @for (author of metadataForm.get('authors')!.value; track $index) {
<span class="author-chip" [class.main-author]="$index === 0" cdkDrag> <span class="author-chip" [class.main-author]="$index === 0" cdkDrag>
@if ($index === 0) { <span class="main-author-badge">m</span> } @if ($index === 0) { <span class="main-author-badge">m</span> }
@@ -220,9 +205,7 @@
[dropdown]="false" [dropdown]="false"
[forceSelection]="false" [forceSelection]="false"
class="dest full-width" class="dest full-width"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
(onBlur)="onAutoCompleteBlur(field.controlName, $event)" (onBlur)="onAutoCompleteBlur(field.controlName, $event)"
/> />
} }
@@ -230,9 +213,7 @@
size="small" size="small"
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')" [icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')"
[outlined]="true" [outlined]="true"
[ngClass]="{ [class.nosrc]="!fetchedMetadata[field.fetchedKey]"
'nosrc' : !fetchedMetadata[field.fetchedKey]
}"
class="arrow-button" class="arrow-button"
[severity]="isValueChanged(field.controlName) ? 'warn' : null" [severity]="isValueChanged(field.controlName) ? 'warn' : null"
[disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)" [disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)"
@@ -249,9 +230,7 @@
[dropdown]="false" [dropdown]="false"
[forceSelection]="false" [forceSelection]="false"
class="src full-width" class="src full-width"
[ngClass]="{ [class.diff]="isFetchedDifferent(field.controlName)"
'diff': isFetchedDifferent(field.controlName),
}"
/> />
} }
</div> </div>
@@ -268,17 +247,13 @@
id="{{field.controlName}}" id="{{field.controlName}}"
formControlName="{{field.controlName}}" formControlName="{{field.controlName}}"
class="dest" class="dest"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
></textarea> ></textarea>
<p-button <p-button
size="small" size="small"
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')" [icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')"
[outlined]="true" [outlined]="true"
[ngClass]="{ [class.nosrc]="!fetchedMetadata[field.fetchedKey]"
'nosrc' : !fetchedMetadata[field.fetchedKey]
}"
class="arrow-button" class="arrow-button"
[severity]="isValueChanged(field.controlName) ? 'warn' : null" [severity]="isValueChanged(field.controlName) ? 'warn' : null"
[disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)" [disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)"
@@ -292,9 +267,7 @@
[value]="fetchedMetadata[field.fetchedKey] ?? null" [value]="fetchedMetadata[field.fetchedKey] ?? null"
class="src" class="src"
disabled disabled
[ngClass]="{ [class.diff]="isFetchedDifferent(field.controlName)"
'diff': isFetchedDifferent(field.controlName),
}"
></textarea> ></textarea>
} }
</div> </div>
@@ -310,17 +283,13 @@
id="{{field.controlName}}" id="{{field.controlName}}"
formControlName="{{field.controlName}}" formControlName="{{field.controlName}}"
class="dest" class="dest"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
/> />
<p-button <p-button
size="small" size="small"
[icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')" [icon]="isValueSaved(field.controlName) ? 'pi pi-check' : (isValueChanged(field.controlName) || !fetchedMetadata[field.fetchedKey] ? 'pi pi-refresh' : 'pi pi-angle-left')"
[outlined]="true" [outlined]="true"
[ngClass]="{ [class.nosrc]="!fetchedMetadata[field.fetchedKey]"
'nosrc' : !fetchedMetadata[field.fetchedKey]
}"
class="arrow-button" class="arrow-button"
[severity]="isValueChanged(field.controlName) ? 'warn' : null" [severity]="isValueChanged(field.controlName) ? 'warn' : null"
[disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)" [disabled]="!isFetchedDifferent(field.controlName) && !isValueChanged(field.controlName)"
@@ -333,9 +302,7 @@
[value]="fetchedMetadata[field.fetchedKey] ?? null" [value]="fetchedMetadata[field.fetchedKey] ?? null"
class="src" class="src"
disabled disabled
[ngClass]="{ [class.diff]="isFetchedDifferent(field.controlName)"
'diff': isFetchedDifferent(field.controlName),
}"
/> />
} }
</div> </div>
@@ -359,7 +326,7 @@
[pTooltip]="t('resetAllTooltip')" [pTooltip]="t('resetAllTooltip')"
tooltipPosition="left" tooltipPosition="left"
(onClick)="confirmReset()" (onClick)="confirmReset()"
></p-button> />
</div> </div>
<div class="metabody"> <div class="metabody">
<div class="editor-thumbnail-wrapper"> <div class="editor-thumbnail-wrapper">
@@ -383,9 +350,7 @@
pInputText pInputText
id="{{field.controlName}}" id="{{field.controlName}}"
formControlName="{{field.controlName}}" formControlName="{{field.controlName}}"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
/> />
<p-button <p-button
size="small" size="small"
@@ -416,10 +381,7 @@
[iconDisplay]="'input'" [iconDisplay]="'input'"
appendTo="body" appendTo="body"
class="full-width" class="full-width"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)" />
'changed': isValueChanged(field.controlName),
}">
</p-datepicker>
<p-button <p-button
size="small" size="small"
icon="pi pi-refresh" icon="pi pi-refresh"
@@ -441,7 +403,7 @@
<div class="author-chips-container full-width" <div class="author-chips-container full-width"
cdkDropList cdkDropListOrientation="mixed" cdkDropList cdkDropListOrientation="mixed"
(cdkDropListDropped)="dropAuthor($event)" (cdkDropListDropped)="dropAuthor($event)"
[ngClass]="{ 'changed': isValueChanged('authors') }"> [class.changed]="isValueChanged('authors')">
@for (author of metadataForm.get('authors')!.value; track $index) { @for (author of metadataForm.get('authors')!.value; track $index) {
<span class="author-chip" [class.main-author]="$index === 0" cdkDrag> <span class="author-chip" [class.main-author]="$index === 0" cdkDrag>
@if ($index === 0) { <span class="main-author-badge">m</span> } @if ($index === 0) { <span class="main-author-badge">m</span> }
@@ -475,9 +437,7 @@
[dropdown]="false" [dropdown]="false"
[forceSelection]="false" [forceSelection]="false"
class="full-width" class="full-width"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
(onBlur)="onAutoCompleteBlur(field.controlName, $event)" (onBlur)="onAutoCompleteBlur(field.controlName, $event)"
/> />
} }
@@ -505,9 +465,7 @@
pSize="small" pSize="small"
id="{{field.controlName}}" id="{{field.controlName}}"
formControlName="{{field.controlName}}" formControlName="{{field.controlName}}"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
></textarea> ></textarea>
<p-button <p-button
size="small" size="small"
@@ -532,9 +490,7 @@
pInputText pInputText
id="{{field.controlName}}" id="{{field.controlName}}"
formControlName="{{field.controlName}}" formControlName="{{field.controlName}}"
[ngClass]="{ [class.changed]="isValueChanged(field.controlName)"
'changed': isValueChanged(field.controlName),
}"
/> />
<p-button <p-button
size="small" size="small"
@@ -1,7 +1,6 @@
import {Component, computed, effect, EventEmitter, inject, Input, Output, signal} from '@angular/core'; import {Component, computed, effect, inject, Input, output, signal} from '@angular/core';
import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Button} from '@openng/optimus-ui/button'; import {Button} from '@openng/optimus-ui/button';
import {NgClass} from '@angular/common';
import {Tooltip} from '@openng/optimus-ui/tooltip'; import {Tooltip} from '@openng/optimus-ui/tooltip';
import {InputText} from '@openng/optimus-ui/inputtext'; import {InputText} from '@openng/optimus-ui/inputtext';
import {BookMetadata} from '../../../book/model/book.model'; import {BookMetadata} from '../../../book/model/book.model';
@@ -27,7 +26,6 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
Button, Button,
Tooltip, Tooltip,
InputText, InputText,
NgClass,
FormsModule, FormsModule,
Textarea, Textarea,
AutoComplete, AutoComplete,
@@ -57,7 +55,7 @@ export class BookdropFileMetadataPickerComponent {
@Input() savedFields: Record<string, boolean> = {}; @Input() savedFields: Record<string, boolean> = {};
@Input() bookdropFileId!: number; @Input() bookdropFileId!: number;
@Output() metadataCopied = new EventEmitter<boolean>(); readonly metadataCopied = output<boolean>();
authorInputValue = ''; authorInputValue = '';
@@ -23,8 +23,7 @@
outlined outlined
(click)="rescanBookdrop()" (click)="rescanBookdrop()"
[pTooltip]="t('rescanTooltip')" [pTooltip]="t('rescanTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</div> </div>
</div> </div>
<div class="card-body"> <div class="card-body">
@@ -54,7 +53,7 @@
@if (bookdropFileUis.length !== 0) { @if (bookdropFileUis.length !== 0) {
<div class="controls-row"> <div class="controls-row">
<div class="action-buttons"> <div class="action-buttons">
<p-inputgroup class="importmetadata" [ngClass]="!hasSelectedFiles ? 'disabled' : ''"> <p-inputgroup class="importmetadata" [class]="!hasSelectedFiles ? 'disabled' : ''">
<p-button <p-button
size="small" size="small"
outlined outlined
@@ -64,15 +63,13 @@
[disabled]="!hasSelectedFiles" [disabled]="!hasSelectedFiles"
(click)="copyMetadata()" (click)="copyMetadata()"
[pTooltip]="t('importMetadataTooltip')" [pTooltip]="t('importMetadataTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
<p-inputgroup-addon [pTooltip]="t('includeCoversTooltip')" tooltipPosition="top"> <p-inputgroup-addon [pTooltip]="t('includeCoversTooltip')" tooltipPosition="top">
<p-checkbox <p-checkbox
inputId="includecovers" inputId="includecovers"
[disabled]="!hasSelectedFiles" [disabled]="!hasSelectedFiles"
[binary]="true" [binary]="true"
[(ngModel)]="includeCoversOnCopy"> [(ngModel)]="includeCoversOnCopy" />
</p-checkbox>
<label for="includecovers"><i class="pi pi-image icon-padding-left"></i></label> <label for="includecovers"><i class="pi pi-image icon-padding-left"></i></label>
</p-inputgroup-addon> </p-inputgroup-addon>
</p-inputgroup> </p-inputgroup>
@@ -87,8 +84,7 @@
[disabled]="!hasSelectedFiles" [disabled]="!hasSelectedFiles"
(click)="openBulkEditDialog()" (click)="openBulkEditDialog()"
[pTooltip]="t('bulkEditTooltip')" [pTooltip]="t('bulkEditTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
<p-button <p-button
size="small" size="small"
@@ -100,8 +96,7 @@
[disabled]="!hasSelectedFiles" [disabled]="!hasSelectedFiles"
(click)="openPatternExtractDialog()" (click)="openPatternExtractDialog()"
[pTooltip]="t('extractPatternTooltip')" [pTooltip]="t('extractPatternTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</div> </div>
<div class="default-controls"> <div class="default-controls">
@@ -116,8 +111,7 @@
optionValue="value" optionValue="value"
[placeholder]="t('libraryPlaceholder')" [placeholder]="t('libraryPlaceholder')"
appendTo="body" appendTo="body"
[(ngModel)]="defaultLibraryId"> [(ngModel)]="defaultLibraryId" />
</p-select>
<p-select <p-select
size="small" size="small"
@@ -126,8 +120,7 @@
optionValue="value" optionValue="value"
[placeholder]="t('subpathPlaceholder')" [placeholder]="t('subpathPlaceholder')"
appendTo="body" appendTo="body"
[(ngModel)]="defaultPathId"> [(ngModel)]="defaultPathId" />
</p-select>
<p-button <p-button
size="small" size="small"
@@ -136,28 +129,22 @@
[disabled]="!canApplyDefaults" [disabled]="!canApplyDefaults"
(click)="applyLibraryDefaults()" (click)="applyLibraryDefaults()"
[pTooltip]="t('applyLibraryTooltip')" [pTooltip]="t('applyLibraryTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</div> </div>
</div> </div>
} }
</div> </div>
<div class="content-area"> <div class="content-area">
@if (bookdropFileUis.length === 0) {
<div class="empty-state">
{{ t('emptyState') }}
</div>
} @else {
@for (file of bookdropFileUis; track file.file.id) { @for (file of bookdropFileUis; track file.file.id) {
<div class="file-item"> <div class="file-item">
<div class="file-row" [ngClass]="file.showDetails ? ' expanded' : ''"> <div class="file-row" [class]="file.showDetails ? ' expanded' : ''">
<p-checkbox <p-checkbox
[binary]="true" [binary]="true"
[(ngModel)]="file.selected" [(ngModel)]="file.selected"
(ngModelChange)="toggleFileSelection(file.file.id, $event)"> (ngModelChange)="toggleFileSelection(file.file.id, $event)" />
</p-checkbox>
@if (file.metadataForm.get('thumbnailUrl')?.value) { @if (file.metadataForm.get('thumbnailUrl')?.value) {
<img <img
@@ -221,8 +208,7 @@
class="library-select" class="library-select"
appendTo="body" appendTo="body"
[(ngModel)]="file.selectedLibraryId" [(ngModel)]="file.selectedLibraryId"
(onChange)="onLibraryChange(file)"> (onChange)="onLibraryChange(file)" />
</p-select>
<p-select <p-select
size="small" size="small"
@@ -232,8 +218,7 @@
[placeholder]="t('subpathPlaceholder')" [placeholder]="t('subpathPlaceholder')"
class="path-select" class="path-select"
appendTo="body" appendTo="body"
[(ngModel)]="file.selectedPathId"> [(ngModel)]="file.selectedPathId" />
</p-select>
<p-button <p-button
size="small" size="small"
@@ -245,8 +230,7 @@
: file.file.fetchedMetadata?.title : file.file.fetchedMetadata?.title
? t('reviewMetadataTooltip') ? t('reviewMetadataTooltip')
: t('showMetadataTooltip')" : t('showMetadataTooltip')"
tooltipPosition="left"> tooltipPosition="left" />
</p-button>
</div> </div>
</div> </div>
@@ -259,18 +243,21 @@
[copiedFields]="file.copiedFields" [copiedFields]="file.copiedFields"
[savedFields]="file.savedFields" [savedFields]="file.savedFields"
[bookdropFileId]="file.file.id" [bookdropFileId]="file.file.id"
(metadataCopied)="onMetadataCopied(file.file.id, $event)"> (metadataCopied)="onMetadataCopied(file.file.id, $event)" />
</app-bookdrop-file-metadata-picker-component>
} }
</div> </div>
} } @empty {
<div class="empty-state">
{{ t('emptyState') }}
</div>
} }
</div> </div>
} }
</div> </div>
@if (!loading()) { @if (!loading()) {
<p-divider></p-divider> <p-divider />
<div class="footer"> <div class="footer">
@@ -287,8 +274,7 @@
(click)="selectAll(true)" (click)="selectAll(true)"
outlined outlined
[pTooltip]="t('selectAllTooltip')" [pTooltip]="t('selectAllTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</p-inputgroup> </p-inputgroup>
<p-button <p-button
@@ -299,8 +285,7 @@
(click)="selectAll(false)" (click)="selectAll(false)"
outlined outlined
[pTooltip]="t('clearTooltip')" [pTooltip]="t('clearTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
} @else { } @else {
<div class="spacer"></div> <div class="spacer"></div>
} }
@@ -316,8 +301,7 @@
[showJumpToPageDropdown]="true" [showJumpToPageDropdown]="true"
[showPageLinks]="false" [showPageLinks]="false"
[showFirstLastIcon]="false" [showFirstLastIcon]="false"
currentPageReportTemplate="Page {currentPage} of {totalPages}"> currentPageReportTemplate="Page {currentPage} of {totalPages}" />
</p-paginator>
</div> </div>
} }
@@ -330,8 +314,7 @@
outlined outlined
(click)="confirmReset()" (click)="confirmReset()"
[pTooltip]="t('resetTooltip')" [pTooltip]="t('resetTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
<p-button <p-button
[label]="t('delete')" [label]="t('delete')"
icon="pi pi-times" icon="pi pi-times"
@@ -340,8 +323,7 @@
outlined outlined
(click)="confirmDelete()" (click)="confirmDelete()"
[pTooltip]="t('deleteTooltip')" [pTooltip]="t('deleteTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
<p-button <p-button
[label]="t('finalize')" [label]="t('finalize')"
[icon]="saving ? 'pi pi-spin pi-spinner' : 'pi pi-save'" [icon]="saving ? 'pi pi-spin pi-spinner' : 'pi pi-save'"
@@ -350,8 +332,7 @@
[disabled]="!canFinalize || saving" [disabled]="!canFinalize || saving"
(click)="confirmFinalize()" (click)="confirmFinalize()"
[pTooltip]="t('finalizeTooltip')" [pTooltip]="t('finalizeTooltip')"
tooltipPosition="top"> tooltipPosition="top" />
</p-button>
</div> </div>
</div> </div>

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